path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
src/pages/host.dashboard.js
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import { withUser } from '../components/UserProvider'; import HostDashboard from '../components/HostDashboard'; import Loading from '../components/Loading'; import withData from '../lib/withData'; import withIntl from '../lib/withIntl'; class HostExpensesPage extends React.Component { static getInitialProps({ query: { hostCollectiveSlug } }) { return { hostCollectiveSlug, ssr: false }; } static propTypes = { hostCollectiveSlug: PropTypes.string, // for addData ssr: PropTypes.bool, data: PropTypes.object, // from withData getLoggedInUser: PropTypes.func.isRequired, // from withLoggedInUser }; render() { const { LoggedInUser, loadingLoggedInUser } = this.props; return ( <div className="HostExpensesPage"> {loadingLoggedInUser ? ( <Loading /> ) : ( <HostDashboard hostCollectiveSlug={this.props.hostCollectiveSlug} LoggedInUser={LoggedInUser} /> )} </div> ); } } export default withData(withIntl(withUser(HostExpensesPage)));
packages/material-ui-icons/src/ConfirmationNumber.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><defs><path id="a" d="M0 0h24v24H0z" /></defs><path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z" /></React.Fragment> , 'ConfirmationNumber');
ajax/libs/react-slick/0.3.3/react-slick.min.js
emijrp/cdnjs
!function(t,n){"object"==typeof exports&&"object"==typeof module?module.exports=n(require("react")):"function"==typeof define&&define.amd?define(["react"],n):"object"==typeof exports?exports.Slider=n(require("react")):t.Slider=n(t.React)}(this,function(t){return function(t){function n(r){if(e[r])return e[r].exports;var o=e[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var e={};return n.m=t,n.c=e,n.p="",n(0)}([function(t,n,e){"use strict";t.exports=e(1)},function(t,n,e){"use strict";var r=e(2),o=e(3),i=e(4),u=e(5),s=e(6),c=e(7),a=e(8),f=e(9),l=r.createClass({displayName:"Slider",mixins:[f],getInitialState:function(){return{breakpoint:null}},componentDidMount:function(){var t=i(u(this.props.responsive,"breakpoint"));t.forEach(function(n,e){var r;r=a(0===e?{minWidth:0,maxWidth:n}:{minWidth:t[e-1],maxWidth:n}),this.media(r,function(){this.setState({breakpoint:n})}.bind(this))}.bind(this));var n=a({minWidth:t.slice(-1)[0]});this.media(n,function(){this.setState({breakpoint:null})}.bind(this))},render:function(){var t,n;return this.state.breakpoint?(n=s(this.props.responsive,{breakpoint:this.state.breakpoint}),t=c({},this.props,n[0].settings)):t=this.props,r.createElement(o,t)}});t.exports=l},function(n){n.exports=t},function(t,n,e){"use strict";var r=e(2),o=e(14),i=e(15),u=e(10),s=e(11),c=e(12),a=e(13),f=e(7),l=r.createClass({displayName:"Slider",mixins:[u,s],getInitialState:function(){return c},getDefaultProps:function(){return a},componentDidMount:function(){this.initialize(this.props)},componentWillReceiveProps:function(t){this.initialize(t)},renderDots:function(){var t,n,e=[];if(this.props.dots===!0&&this.state.slideCount>this.props.slidesToShow){for(var o=0;o<=this.getDotCount();o+=1)t={"slick-active":this.state.currentSlide===o*this.props.slidesToScroll},n={message:"index",index:o},e.push(r.createElement("li",{key:o,className:i(t)},r.createElement("button",{onClick:this.changeSlide.bind(this,n)},o)));return r.createElement("ul",{className:this.props.dotsClass,style:{display:"block"}},e)}return null},renderSlides:function(){var t,n=[],e=[],i=[],u=r.Children.count(this.props.children);return r.Children.forEach(this.props.children,function(r,s){var c;n.push(o(r,{key:s,"data-index":s,className:this.getSlideClasses(s),style:f({},this.getSlideStyle(),r.props.style)})),this.props.infinite===!0&&(c=this.props.centerMode===!0?this.props.slidesToShow+1:this.props.slidesToShow,s>=u-c&&(t=-(u-s),e.push(o(r,{key:t,"data-index":t,className:this.getSlideClasses(t),style:f({},this.getSlideStyle(),r.props.style)}))),c>s&&(t=u+s,i.push(o(r,{key:t,"data-index":t,className:this.getSlideClasses(t),style:f({},this.getSlideStyle(),r.props.style)}))))}.bind(this)),e.concat(n,i)},renderTrack:function(){return r.createElement("div",{ref:"track",className:"slick-track",style:this.state.trackStyle},this.renderSlides())},renderArrows:function(){if(this.props.arrows===!0){var t={"slick-prev":!0},n={"slick-next":!0},e=this.changeSlide.bind(this,{message:"previous"}),o=this.changeSlide.bind(this,{message:"next"});this.props.infinite===!1&&(0===this.state.currentSlide&&(t["slick-disabled"]=!0,e=null),this.state.currentSlide>=this.state.slideCount-this.props.slidesToShow&&(n["slick-disabled"]=!0,o=null));var u=r.createElement("button",{key:0,ref:"previous",type:"button","data-role":"none",className:i(t),style:{display:"block"},onClick:e}," Previous"),s=r.createElement("button",{key:1,ref:"next",type:"button","data-role":"none",className:i(n),style:{display:"block"},onClick:o},"Next");return[u,s]}return null},render:function(){return r.createElement("div",{className:"slick-initialized slick-slider "+this.props.className},r.createElement("div",{ref:"list",className:"slick-list",style:this.getListStyle(),onMouseDown:this.swipeStart,onMouseMove:this.state.dragging?this.swipeMove:null,onMouseUp:this.swipeEnd,onMouseLeave:this.state.dragging?this.swipeEnd:null,onTouchStart:this.swipeStart,onTouchMove:this.state.dragging?this.swipeMove:null,onTouchEnd:this.swipeEnd,onTouchCancel:this.state.dragging?this.swipeEnd:null},this.renderTrack()),this.renderArrows(),this.renderDots())}});t.exports=l},function(t,n,e){function r(t,n){return s(t.criteria,n.criteria)||t.index-n.index}function o(t){return"number"==typeof t&&t>-1&&t%1==0&&l>=t}function i(t,n,e){var i=-1,s=t?t.length:0,l=o(s)?Array(s):[];return e&&f(t,n,e)&&(n=null),n=u(n,e,3),c(t,function(t,e,r){l[++i]={criteria:n(t,e,r),index:i,value:t}}),a(l,r)}var u=e(19),s=e(20),c=e(21),a=e(22),f=e(23),l=Math.pow(2,53)-1;t.exports=i},function(t,n,e){function r(t,n){return i(t,o(n))}var o=e(17),i=e(18);t.exports=r},function(t,n,e){function r(t,n,e){var r=s(t)?o:u;return n=i(n,e,3),r(t,n)}var o=e(24),i=e(25),u=e(26),s=e(27);t.exports=r},function(t,n,e){var r=e(28),o=e(29),i=o(r);t.exports=i},function(t,n,e){var r=e(31),o=function(t){var n=/[height|width]$/;return n.test(t)},i=function(t){var n="",e=Object.keys(t);return e.forEach(function(i,u){var s=t[i];i=r(i),o(i)&&"number"==typeof s&&(s+="px"),n+=s===!0?i:s===!1?"not "+i:"("+i+": "+s+")",u<e.length-1&&(n+=" and ")}),n},u=function(t){var n="";return"string"==typeof t?t:t instanceof Array?(t.forEach(function(e,r){n+=i(e),r<t.length-1&&(n+=", ")}),n):i(t)};t.exports=u},function(t,n,e){var r=e(30),o=r&&e(32),i=e(8),u={media:function(t,n){t=i(t),"function"==typeof n&&(n={match:n}),o.register(t,n),this._responsiveMediaHandlers||(this._responsiveMediaHandlers=[]),this._responsiveMediaHandlers.push({query:t,handler:n})},componentWillUnmount:function(){this._responsiveMediaHandlers.forEach(function(t){o.unregister(t.query,t.handler)})}};t.exports=u},function(t){var n={changeSlide:function(t){var n,e,r;if(r=this.state.slideCount%this.props.slidesToScroll!==0,n=r?0:(this.state.slideCount-this.state.currentSlide)%this.props.slidesToScroll,"previous"===t.message)e=0===n?this.props.slidesToScroll:this.props.slidesToShow-n,this.state.slideCount>this.props.slidesToShow&&this.slideHandler(this.state.currentSlide-e,!1);else if("next"===t.message)e=0===n?this.props.slidesToScroll:n,this.state.slideCount>this.props.slidesToShow&&this.slideHandler(this.state.currentSlide+e,!1);else if("index"===t.message){var o=t.index*this.props.slidesToScroll;o!==this.state.currentSlide&&this.slideHandler(o)}this.autoPlay()},keyHandler:function(){},selectHandler:function(){},swipeStart:function(t){var n,e;this.props.swipe===!1||"ontouchend"in document&&this.props.swipe===!1||(this.props.draggable!==!1||-1===t.type.indexOf("mouse"))&&(n=void 0!==t.touches?t.touches[0].pageX:t.clientX,e=void 0!==t.touches?t.touches[0].pageY:t.clientY,this.setState({dragging:!0,touchObject:{startX:n,startY:e,curX:n,curY:e}}),t.preventDefault())},swipeMove:function(t){if(this.state.dragging&&!this.state.animating){var n,e,r=this.state.touchObject;e=this.getLeft(this.state.currentSlide),r.curX=t.touches?t.touches[0].pageX:t.clientX,r.curY=t.touches?t.touches[0].pageY:t.clientY,r.swipeLength=Math.round(Math.sqrt(Math.pow(r.curX-r.startX,2))),positionOffset=(this.props.rtl===!1?1:-1)*(r.curX>r.startX?1:-1),n=e+r.swipeLength*positionOffset,this.setState({touchObject:r,swipeLeft:n,trackStyle:this.getCSS(n)}),t.preventDefault()}},swipeEnd:function(t){if(this.state.dragging){var n=this.state.touchObject,e=this.state.listWidth/this.props.touchThreshold,r=this.swipeDirection(n);this.setState({dragging:!1,touchObject:{}}),n.swipeLength>e?"left"===r?this.slideHandler(this.state.currentSlide+this.props.slidesToScroll):"right"===r?this.slideHandler(this.state.currentSlide-this.props.slidesToScroll):this.slideHandler(this.state.currentSlide,null,!0):this.slideHandler(this.state.currentSlide,null,!0),t.preventDefault()}}};t.exports=n},function(t,n,e){var r=(e(33),e(2)),o=e(15),i=e(16),u={initialize:function(t){var n=r.Children.count(t.children),e=this.refs.list.getDOMNode().getBoundingClientRect().width,o=this.refs.track.getDOMNode().getBoundingClientRect().width,i=this.getDOMNode().getBoundingClientRect().width/t.slidesToShow;this.setState({slideCount:n,slideWidth:i,listWidth:e,trackWidth:o,currentSlide:0},function(){var t=this.getCSS(this.getLeft(0));this.setState({trackStyle:t})})},getDotCount:function(){var t;return t=Math.ceil(this.state.slideCount/this.props.slidesToScroll),t-1},getLeft:function(t){var n,e,r=0;if(this.props.infinite===!0&&(this.state.slideCount>this.props.slidesToShow&&(r=this.state.slideWidth*this.props.slidesToShow*-1),this.state.slideCount%this.props.slidesToScroll!==0&&t+this.props.slidesToScroll>this.state.slideCount&&this.state.slideCount>this.props.slidesToShow&&(r=t>this.state.slideCount?(this.props.slidesToShow-(t-this.state.slideCount))*this.state.slideWidth*-1:this.state.slideCount%this.props.slidesToScroll*this.state.slideWidth*-1)),this.props.centerMode===!0&&this.props.infinite===!0?r+=this.state.slideWidth*Math.floor(this.props.slidesToShow/2)-this.state.slideWidth:this.props.centerMode===!0&&(r=this.state.slideWidth*Math.floor(this.props.slidesToShow/2)),n=t*this.state.slideWidth*-1+r,this.props.variableWidth===!0){var o;this.state.slideCount<=this.props.slidesToShow||this.props.infinite===!1?e=this.refs.track.getDOMNode().childNodes[t]:(o=t+this.props.slidesToShow,e=this.refs.track.getDOMNode().childNodes[o]),n=e?-1*e.offsetLeft:0,this.props.centerMode===!0&&(e=this.props.infinite===!1?this.refs.track.getDOMNode().childNodes[t]:this.refs.track.getDOMNode().childNodes[t+this.props.slidesToShow+1],n=e?-1*e.offsetLeft:0,n+=(this.state.listWidth-e.offsetWidth)/2)}return n},getAnimateCSS:function(t){var n=this.getCSS(t);return n.transition="transform "+this.props.speed+"ms "+this.props.cssEase,n},getCSS:function(t){var n;n=this.props.variableWidth?(this.state.slideCount+2*this.props.slidesToShow)*this.state.slideWidth:this.props.centerMode?(this.state.slideCount+2*(this.props.slidesToShow+1))*this.state.slideWidth:(this.state.slideCount+2*this.props.slidesToShow)*this.state.slideWidth;var e={opacity:1,width:n,WebkitTransform:"translate3d("+t+"px, 0px, 0px)",transform:"translate3d("+t+"px, 0px, 0px)"};return e},getSlideStyle:function(){return{width:this.state.slideWidth}},getSlideClasses:function(t){var n,e,r,i,u,s,c,a=!1;return r=0>t||t>=this.state.slideCount,this.props.centerMode?(this.refs.track&&(s=this.refs.track.getDOMNode().childNodes.length),i=Math.floor(this.props.slidesToShow/2),u=this.state.currentSlide+this.props.slidesToShow,c=this.state.currentSlide+i,e=c-1===t,this.state.currentSlide>=i&&this.state.currentSlide<=this.props.slideCount-1-i&&(a=!0),a&&t>this.state.currentSlide-i&&t<=this.state.currentSlide+i+1&&(n=!0)):n=this.state.currentSlide===t,o({"slick-slide":!0,"slick-active":n,"slick-center":e,"slick-cloned":r})},getListStyle:function(){var t={};if(this.props.adaptiveHeight){var n='[data-index="'+this.state.currentSlide+'"]';this.refs.list&&(t.height=this.refs.list.getDOMNode().querySelector(n).offsetHeight)}return t},slideHandler:function(t){var n,e,r,o;this.state.animating!==!0&&(this.props.fade!==!0||this.state.currentSlide!==t)&&(this.state.slideCount<=this.props.slidesToShow||(n=t,e=0>n?this.state.slideCount%this.props.slidesToScroll!==0?this.state.slideCount-this.state.slideCount%this.props.slidesToScroll:this.state.slideCount+n:n>=this.state.slideCount?this.state.slideCount%this.props.slidesToScroll!==0?0:n-this.state.slideCount:n,r=this.getLeft(n,this.state),o=this.getLeft(e,this.state),this.props.infinite===!1&&(r=o),this.setState({animating:!0,currentSlide:e,currentLeft:o,trackStyle:this.getAnimateCSS(r)},function(){i.addEndEventListener(this.refs.track.getDOMNode(),function(){this.setState({animating:!1,trackStyle:this.getCSS(o),swipeLeft:null})}.bind(this))})))},swipeDirection:function(t){var n,e,r,o;return n=t.startX-t.curX,e=t.startY-t.curY,r=Math.atan2(e,n),o=Math.round(180*r/Math.PI),0>o&&(o=360-Math.abs(o)),45>=o&&o>=0?this.props.rtl===!1?"left":"right":360>=o&&o>=315?this.props.rtl===!1?"left":"right":o>=135&&225>=o?this.props.rtl===!1?"right":"left":"vertical"},autoPlay:function(){var t=function(){this.slideHandler(this.state.currentSlide+this.props.slidesToScroll)}.bind(this);this.props.autoplay&&window.setInterval(t,this.props.autoplaySpeed)}};t.exports=u},function(t){var n={animating:!1,dragging:!1,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,slideCount:null,slideWidth:null,swipeLeft:null,touchObject:{startX:0,startY:0,curX:0,curY:0},initialized:!1,trackStyle:{},trackWidth:0};t.exports=n},function(t){var n={className:"",adaptiveHeight:!1,arrows:!0,autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",fade:!1,focusOnSelect:!1,infinite:!0,initialSlide:0,responsive:null,rtl:!1,slide:"div",slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,variableWidth:!1,vertical:!1};t.exports=n},function(t,n,e){"use strict";function r(t,n){s(!t.ref,"You are calling cloneWithProps() on a child with a ref. This is dangerous because you're creating a new child which will not be added as a ref to its parent.");var e=i.mergeProps(n,t.props);return!e.hasOwnProperty(c)&&t.props.hasOwnProperty(c)&&(e.children=t.props.children),o.createElement(t.type,e)}var o=e(34),i=e(35),u=e(36),s=e(37),c=u({children:null});t.exports=r},function(t){function n(t){return"object"==typeof t?Object.keys(t).filter(function(n){return t[n]}).join(" "):Array.prototype.join.call(arguments," ")}t.exports=n},function(t,n,e){"use strict";function r(){var t=document.createElement("div"),n=t.style;"AnimationEvent"in window||delete s.animationend.animation,"TransitionEvent"in window||delete s.transitionend.transition;for(var e in s){var r=s[e];for(var o in r)if(o in n){c.push(r[o]);break}}}function o(t,n,e){t.addEventListener(n,e,!1)}function i(t,n,e){t.removeEventListener(n,e,!1)}var u=e(38),s={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},c=[];u.canUseDOM&&r();var a={addEndEventListener:function(t,n){return 0===c.length?void window.setTimeout(n,0):void c.forEach(function(e){o(t,e,n)})},removeEndEventListener:function(t,n){0!==c.length&&c.forEach(function(e){i(t,e,n)})}};t.exports=a},function(t){function n(t){return function(n){return null==n?void 0:n[t]}}t.exports=n},function(t,n,e){function r(t,n){var e=[];return s(t,function(t,r,o){e.push(n(t,r,o))}),e}function o(t,n,e){var o=c(t)?i:r;return n=u(n,e,3),o(t,n)}var i=e(39),u=e(40),s=e(41),c=e(42);t.exports=o},function(t,n,e){function r(t,n,e){var r=typeof t;return"function"==r?"undefined"!=typeof n?p(t,n,e):t:null==t?f:"object"==r?i(t):"undefined"==typeof n?s(t+""):u(t+"",n)}function o(t,n,e,r,o){var i=n.length;if(null==t)return!i;for(var u=-1,s=!o;++u<i;)if(s&&r[u]?e[u]!==t[n[u]]:!g.call(t,n[u]))return!1;for(u=-1;++u<i;){var c=n[u];if(s&&r[u])var a=g.call(t,c);else{var f=t[c],p=e[u];a=o?o(f,p,c):void 0,"undefined"==typeof a&&(a=l(p,f,o,!0))}if(!a)return!1}return!0}function i(t){var n=h(t),e=n.length;if(1==e){var r=n[0],i=t[r];if(c(i))return function(t){return null!=t&&t[r]===i&&g.call(t,r)}}for(var u=Array(e),s=Array(e);e--;)i=t[n[e]],u[e]=i,s[e]=c(i);return function(t){return o(t,n,u,s)}}function u(t,n){return c(n)?function(e){return null!=e&&e[t]===n}:function(e){return null!=e&&l(n,e[t],null,!0)}}function s(t){return function(n){return null==n?void 0:n[t]}}function c(t){return t===t&&(0===t?1/t>0:!a(t))}function a(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function f(t){return t}var l=e(43),p=e(44),h=e(45),d=Object.prototype,g=d.hasOwnProperty;t.exports=r},function(t){function n(t,n){if(t!==n){var e=t===t,r=n===n;if(t>n||!e||"undefined"==typeof t&&r)return 1;if(n>t||!r||"undefined"==typeof n&&e)return-1}return 0}t.exports=n},function(t,n,e){function r(t,n){var e=t?t.length:0;if(!u(e))return i(t,n);for(var r=-1,o=s(t);++r<e&&n(o[r],r,o)!==!1;);return t}function o(t,n,e){for(var r=-1,o=s(t),i=e(t),u=i.length;++r<u;){var c=i[r];if(n(o[c],c,o)===!1)break}return t}function i(t,n){return o(t,n,a)}function u(t){return"number"==typeof t&&t>-1&&t%1==0&&f>=t}function s(t){return c(t)?t:Object(t)}function c(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}var a=e(47),f=Math.pow(2,53)-1;t.exports=r},function(t){function n(t,n){var e=t.length;for(t.sort(n);e--;)t[e]=t[e].value;return t}t.exports=n},function(t){function n(t,n){return t=+t,n=null==n?i:n,t>-1&&t%1==0&&n>t}function e(t,e,i){if(!o(i))return!1;var u=typeof e;if("number"==u)var s=i.length,c=r(s)&&n(e,s);else c="string"==u&&e in i;return c&&i[e]===t}function r(t){return"number"==typeof t&&t>-1&&t%1==0&&i>=t}function o(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}var i=Math.pow(2,53)-1;t.exports=e},function(t){function n(t,n){for(var e=-1,r=t.length,o=-1,i=[];++e<r;){var u=t[e];n(u,e,t)&&(i[++o]=u)}return i}t.exports=n},function(t,n,e){function r(t,n,e){var r=typeof t;return"function"==r?"undefined"!=typeof n?p(t,n,e):t:null==t?f:"object"==r?i(t):"undefined"==typeof n?s(t+""):u(t+"",n)}function o(t,n,e,r,o){var i=n.length;if(null==t)return!i;for(var u=-1,s=!o;++u<i;)if(s&&r[u]?e[u]!==t[n[u]]:!g.call(t,n[u]))return!1;for(u=-1;++u<i;){var c=n[u];if(s&&r[u])var a=g.call(t,c);else{var f=t[c],p=e[u];a=o?o(f,p,c):void 0,"undefined"==typeof a&&(a=l(p,f,o,!0))}if(!a)return!1}return!0}function i(t){var n=h(t),e=n.length;if(1==e){var r=n[0],i=t[r];if(c(i))return function(t){return null!=t&&t[r]===i&&g.call(t,r)}}for(var u=Array(e),s=Array(e);e--;)i=t[n[e]],u[e]=i,s[e]=c(i);return function(t){return o(t,n,u,s)}}function u(t,n){return c(n)?function(e){return null!=e&&e[t]===n}:function(e){return null!=e&&l(n,e[t],null,!0)}}function s(t){return function(n){return null==n?void 0:n[t]}}function c(t){return t===t&&(0===t?1/t>0:!a(t))}function a(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function f(t){return t}var l=e(46),p=e(48),h=e(49),d=Object.prototype,g=d.hasOwnProperty;t.exports=r},function(t,n,e){function r(t,n){var e=[];return o(t,function(t,r,o){n(t,r,o)&&e.push(t)}),e}var o=e(50);t.exports=r},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return"number"==typeof t&&t>-1&&t%1==0&&y>=t}function o(t){return null==t?!1:h.call(t)==s?d.test(p.call(t)):e(t)&&c.test(t)||!1}function i(t){return t=n(t),t&&f.test(t)?t.replace(a,"\\$&"):t}var u="[object Array]",s="[object Function]",c=/^\[object .+?Constructor\]$/,a=/[.*+?^${}()|[\]\/\\]/g,f=RegExp(a.source),l=Object.prototype,p=Function.prototype.toString,h=l.toString,d=RegExp("^"+i(h).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),g=o(g=Array.isArray)&&g,y=Math.pow(2,53)-1,v=g||function(t){return e(t)&&r(t.length)&&h.call(t)==u||!1};t.exports=v},function(t,n,e){function r(t,n,e){var r=i(n);if(!e)return o(n,t,r);for(var u=-1,s=r.length;++u<s;){var c=r[u],a=t[c],f=e(a,n[c],c,t,n);(f===f?f===a:a!==a)&&("undefined"!=typeof a||c in t)||(t[c]=f)}return t}var o=e(52),i=e(51);t.exports=r},function(t,n,e){function r(t){return function(){var n=arguments.length,e=arguments[0];if(2>n||null==e)return e;if(n>3&&i(arguments[1],arguments[2],arguments[3])&&(n=2),n>3&&"function"==typeof arguments[n-2])var r=o(arguments[--n-1],arguments[n--],5);else n>2&&"function"==typeof arguments[n-1]&&(r=arguments[--n]);for(var u=0;++u<n;){var s=arguments[u];s&&t(e,s,r)}return e}}var o=e(53),i=e(54);t.exports=r},function(t){var n=!("undefined"==typeof window||!window.document||!window.document.createElement);t.exports=n},function(t){var n=function(t){return t.replace(/[A-Z]/g,function(t){return"-"+t.toLowerCase()}).toLowerCase()};t.exports=n},function(t,n,e){var r;!function(o,i,u){var s=window.matchMedia;"undefined"!=typeof t&&t.exports?t.exports=u(s):(r=function(){return i[o]=u(s)}.call(n,e,n,t),!(void 0!==r&&(t.exports=r)))}("enquire",this,function(t){"use strict";function n(t,n){var e,r=0,o=t.length;for(r;o>r&&(e=n(t[r],r),e!==!1);r++);}function e(t){return"[object Array]"===Object.prototype.toString.apply(t)}function r(t){return"function"==typeof t}function o(t){this.options=t,!t.deferSetup&&this.setup()}function i(n,e){this.query=n,this.isUnconditional=e,this.handlers=[],this.mql=t(n);var r=this;this.listener=function(t){r.mql=t,r.assess()},this.mql.addListener(this.listener)}function u(){if(!t)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!t("only all").matches}return o.prototype={setup:function(){this.options.setup&&this.options.setup(),this.initialised=!0},on:function(){!this.initialised&&this.setup(),this.options.match&&this.options.match()},off:function(){this.options.unmatch&&this.options.unmatch()},destroy:function(){this.options.destroy?this.options.destroy():this.off()},equals:function(t){return this.options===t||this.options.match===t}},i.prototype={addHandler:function(t){var n=new o(t);this.handlers.push(n),this.matches()&&n.on()},removeHandler:function(t){var e=this.handlers;n(e,function(n,r){return n.equals(t)?(n.destroy(),!e.splice(r,1)):void 0})},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){n(this.handlers,function(t){t.destroy()}),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var t=this.matches()?"on":"off";n(this.handlers,function(n){n[t]()})}},u.prototype={register:function(t,o,u){var s=this.queries,c=u&&this.browserIsIncapable;return s[t]||(s[t]=new i(t,c)),r(o)&&(o={match:o}),e(o)||(o=[o]),n(o,function(n){s[t].addHandler(n)}),this},unregister:function(t,n){var e=this.queries[t];return e&&(n?e.removeHandler(n):(e.clear(),delete this.queries[t])),this}},new u})},function(t){"use strict";function n(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}t.exports=Object.assign||function(t){for(var e,r,o=n(t),i=1;i<arguments.length;i++){e=arguments[i],r=Object.keys(Object(e));for(var u=0;u<r.length;u++)o[r[u]]=e[r[u]]}return o}},function(t,n,e){"use strict";function r(t,n){Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:function(){return this._store?this._store[n]:null},set:function(t){s(!1,"Don't set the "+n+" property of the component. Mutate the existing props object instead."),this._store[n]=t}})}function o(t){try{var n={props:!0};for(var e in n)r(t,e);a=!0}catch(o){}}var i=e(59),u=e(60),s=e(37),c={key:!0,ref:!0},a=!1,f=function(t,n,e,r,o,i){return this.type=t,this.key=n,this.ref=e,this._owner=r,this._context=o,this._store={validated:!1,props:i},a?void Object.freeze(this):void(this.props=i)};f.prototype={_isReactElement:!0},o(f.prototype),f.createElement=function(t,n,e){var r,o={},a=null,l=null;if(null!=n){l=void 0===n.ref?null:n.ref,s(null!==n.key,"createElement(...): Encountered component with a `key` of null. In a future version, this will be treated as equivalent to the string 'null'; instead, provide an explicit key or use undefined."),a=null==n.key?null:""+n.key;for(r in n)n.hasOwnProperty(r)&&!c.hasOwnProperty(r)&&(o[r]=n[r])}var p=arguments.length-2;if(1===p)o.children=e;else if(p>1){for(var h=Array(p),d=0;p>d;d++)h[d]=arguments[d+2];o.children=h}if(t&&t.defaultProps){var g=t.defaultProps;for(r in g)"undefined"==typeof o[r]&&(o[r]=g[r])}return new f(t,a,l,u.current,i.current,o)},f.createFactory=function(t){var n=f.createElement.bind(null,t);return n.type=t,n},f.cloneAndReplaceProps=function(t,n){var e=new f(t.type,t.key,t.ref,t._owner,t._context,n);return e._store.validated=t._store.validated,e},f.isValidElement=function(t){var n=!(!t||!t._isReactElement);return n},t.exports=f},function(t,n,e){"use strict";function r(t){return function(n,e,r){n[e]=n.hasOwnProperty(e)?t(n[e],r):r}}function o(t,n){for(var e in n)if(n.hasOwnProperty(e)){var r=p[e];r&&p.hasOwnProperty(e)?r(t,e,n[e]):t.hasOwnProperty(e)||(t[e]=n[e])}return t}var i=e(55),u=e(56),s=e(57),c=e(58),a=e(37),f=!1,l=r(function(t,n){return i({},n,t)}),p={children:u,className:r(c),style:l},h={TransferStrategies:p,mergeProps:function(t,n){return o(i({},t),n)},Mixin:{transferPropsTo:function(t){return s(t._owner===this,"%s: You can't call transferPropsTo() on a component that you don't own, %s. This usually means you are calling transferPropsTo() on a component passed in as props or children.",this.constructor.displayName,"string"==typeof t.type?t.type:t.type.displayName),f||(f=!0,a(!1,"transferPropsTo is deprecated. See http://fb.me/react-transferpropsto for more information.")),o(t.props,this.props),t}}};t.exports=h},function(t){var n=function(t){var n;for(n in t)if(t.hasOwnProperty(n))return n;return null};t.exports=n},function(t,n,e){"use strict";var r=e(56),o=r;o=function(t,n){for(var e=[],r=2,o=arguments.length;o>r;r++)e.push(arguments[r]);if(void 0===n)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(!t){var i=0;console.warn("Warning: "+n.replace(/%s/g,function(){return e[i++]}))}},t.exports=o},function(t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),e={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};t.exports=e},function(t){function n(t,n){for(var e=-1,r=t.length,o=Array(r);++e<r;)o[e]=n(t[e],e,t);return o}t.exports=n},function(t,n,e){function r(t,n,e){var r=typeof t;return"function"==r?"undefined"!=typeof n?p(t,n,e):t:null==t?f:"object"==r?i(t):"undefined"==typeof n?s(t+""):u(t+"",n)}function o(t,n,e,r,o){var i=n.length;if(null==t)return!i;for(var u=-1,s=!o;++u<i;)if(s&&r[u]?e[u]!==t[n[u]]:!g.call(t,n[u]))return!1;for(u=-1;++u<i;){var c=n[u];if(s&&r[u])var a=g.call(t,c);else{var f=t[c],p=e[u];a=o?o(f,p,c):void 0,"undefined"==typeof a&&(a=l(p,f,o,!0))}if(!a)return!1}return!0}function i(t){var n=h(t),e=n.length;if(1==e){var r=n[0],i=t[r];if(c(i))return function(t){return null!=t&&t[r]===i&&g.call(t,r)}}for(var u=Array(e),s=Array(e);e--;)i=t[n[e]],u[e]=i,s[e]=c(i);return function(t){return o(t,n,u,s)}}function u(t,n){return c(n)?function(e){return null!=e&&e[t]===n}:function(e){return null!=e&&l(n,e[t],null,!0)}}function s(t){return function(n){return null==n?void 0:n[t]}}function c(t){return t===t&&(0===t?1/t>0:!a(t))}function a(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function f(t){return t}var l=e(61),p=e(62),h=e(63),d=Object.prototype,g=d.hasOwnProperty;t.exports=r},function(t,n,e){function r(t,n){var e=t?t.length:0;if(!u(e))return i(t,n);for(var r=-1,o=s(t);++r<e&&n(o[r],r,o)!==!1;);return t}function o(t,n,e){for(var r=-1,o=s(t),i=e(t),u=i.length;++r<u;){var c=i[r];if(n(o[c],c,o)===!1)break}return t}function i(t,n){return o(t,n,a)}function u(t){return"number"==typeof t&&t>-1&&t%1==0&&f>=t}function s(t){return c(t)?t:Object(t)}function c(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}var a=e(64),f=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return"number"==typeof t&&t>-1&&t%1==0&&y>=t}function o(t){return null==t?!1:h.call(t)==s?d.test(p.call(t)):e(t)&&c.test(t)||!1}function i(t){return t=n(t),t&&f.test(t)?t.replace(a,"\\$&"):t}var u="[object Array]",s="[object Function]",c=/^\[object .+?Constructor\]$/,a=/[.*+?^${}()|[\]\/\\]/g,f=RegExp(a.source),l=Object.prototype,p=Function.prototype.toString,h=l.toString,d=RegExp("^"+i(h).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),g=o(g=Array.isArray)&&g,y=Math.pow(2,53)-1,v=g||function(t){return e(t)&&r(t.length)&&h.call(t)==u||!1};t.exports=v},function(t,n,e){function r(t,n,e,i,u,s){if(t===n)return 0!==t||1/t==1/n;var c=typeof t,a=typeof n;return"function"!=c&&"object"!=c&&"function"!=a&&"object"!=a||null==t||null==n?t!==t&&n!==n:o(t,n,r,e,i,u,s)}function o(t,n,e,r,o,f,h){var d=c(t),g=c(n),y=p,b=p;d||(y=w.call(t),y==l?y=v:y!=v&&(d=a(t))),g||(b=w.call(n),b==l?b=v:b!=v&&(g=a(n)));var m=y==v,j=b==v,x=y==b;if(x&&!d&&!m)return u(t,n,y);var E=m&&S.call(t,"__wrapped__"),A=j&&S.call(n,"__wrapped__");if(E||A)return e(E?t.value():t,A?n.value():n,r,o,f,h);if(!x)return!1;f||(f=[]),h||(h=[]);for(var O=f.length;O--;)if(f[O]==t)return h[O]==n;f.push(t),h.push(n);var M=(d?i:s)(t,n,e,r,o,f,h);return f.pop(),h.pop(),M}function i(t,n,e,r,o,i,u){var s=-1,c=t.length,a=n.length,f=!0;if(c!=a&&!(o&&a>c))return!1;for(;f&&++s<c;){var l=t[s],p=n[s];if(f=void 0,r&&(f=o?r(p,l,s):r(l,p,s)),"undefined"==typeof f)if(o)for(var h=a;h--&&(p=n[h],!(f=l&&l===p||e(l,p,r,o,i,u))););else f=l&&l===p||e(l,p,r,o,i,u)}return!!f}function u(t,n,e){switch(e){case h:case d:return+t==+n;case g:return t.name==n.name&&t.message==n.message;case y:return t!=+t?n!=+n:0==t?1/t==1/n:t==+n;case b:case m:return t==n+""}return!1}function s(t,n,e,r,o,i,u){var s=f(t),c=s.length,a=f(n),l=a.length;if(c!=l&&!o)return!1;for(var p,h=-1;++h<c;){var d=s[h],g=S.call(n,d);if(g){var y=t[d],v=n[d];g=void 0,r&&(g=o?r(v,y,d):r(y,v,d)),"undefined"==typeof g&&(g=y&&y===v||e(y,v,r,o,i,u))}if(!g)return!1;p||(p="constructor"==d)}if(!p){var b=t.constructor,m=n.constructor;if(b!=m&&"constructor"in t&&"constructor"in n&&!("function"==typeof b&&b instanceof b&&"function"==typeof m&&m instanceof m))return!1}return!0}var c=e(65),a=e(66),f=e(45),l="[object Arguments]",p="[object Array]",h="[object Boolean]",d="[object Date]",g="[object Error]",y="[object Number]",v="[object Object]",b="[object RegExp]",m="[object String]",j=Object.prototype,S=j.hasOwnProperty,w=j.toString;t.exports=r},function(t){function n(t,n,r){if("function"!=typeof t)return e;if("undefined"==typeof n)return t;switch(r){case 1:return function(e){return t.call(n,e)};case 3:return function(e,r,o){return t.call(n,e,r,o)};case 4:return function(e,r,o,i){return t.call(n,e,r,o,i)};case 5:return function(e,r,o,i,u){return t.call(n,e,r,o,i,u)}}return function(){return t.apply(n,arguments)}}function e(t){return t}t.exports=n},function(t,n,e){function r(t,n){return t=+t,n=null==n?g:n,t>-1&&t%1==0&&n>t}function o(t){return"number"==typeof t&&t>-1&&t%1==0&&g>=t}function i(t){for(var n=s(t),e=n.length,i=e&&t.length,u=i&&o(i)&&(a(t)||y.nonEnumArgs&&c(t)),f=-1,l=[];++f<e;){var h=n[f];(u&&r(h,i)||p.call(t,h))&&l.push(h)}return l}function u(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function s(t){if(null==t)return[];u(t)||(t=Object(t));var n=t.length;n=n&&o(n)&&(a(t)||y.nonEnumArgs&&c(t))&&n||0;for(var e=t.constructor,i=-1,s="function"==typeof e&&e.prototype===t,f=Array(n),l=n>0;++i<n;)f[i]=i+"";for(var h in t)l&&r(h,n)||"constructor"==h&&(s||!p.call(t,h))||f.push(h);return f}var c=e(67),a=e(68),f=e(69),l=Object.prototype,p=l.hasOwnProperty,h=l.propertyIsEnumerable,d=f(d=Object.keys)&&d,g=Math.pow(2,53)-1,y={};!function(){try{y.nonEnumArgs=!h.call(arguments,1)}catch(t){y.nonEnumArgs=!0}}(0,0);var v=d?function(t){if(t)var n=t.constructor,e=t.length;return"function"==typeof n&&n.prototype===t||"function"!=typeof t&&e&&o(e)?i(t):u(t)?d(t):[]}:i;t.exports=v},function(t,n,e){function r(t,n,e,i,u,s){if(t===n)return 0!==t||1/t==1/n;var c=typeof t,a=typeof n;return"function"!=c&&"object"!=c&&"function"!=a&&"object"!=a||null==t||null==n?t!==t&&n!==n:o(t,n,r,e,i,u,s)}function o(t,n,e,r,o,f,h){var d=c(t),g=c(n),y=p,b=p;d||(y=w.call(t),y==l?y=v:y!=v&&(d=a(t))),g||(b=w.call(n),b==l?b=v:b!=v&&(g=a(n)));var m=y==v,j=b==v,x=y==b;if(x&&!d&&!m)return u(t,n,y);var E=m&&S.call(t,"__wrapped__"),A=j&&S.call(n,"__wrapped__");if(E||A)return e(E?t.value():t,A?n.value():n,r,o,f,h);if(!x)return!1;f||(f=[]),h||(h=[]);for(var O=f.length;O--;)if(f[O]==t)return h[O]==n;f.push(t),h.push(n);var M=(d?i:s)(t,n,e,r,o,f,h);return f.pop(),h.pop(),M}function i(t,n,e,r,o,i,u){var s=-1,c=t.length,a=n.length,f=!0;if(c!=a&&!(o&&a>c))return!1;for(;f&&++s<c;){var l=t[s],p=n[s]; if(f=void 0,r&&(f=o?r(p,l,s):r(l,p,s)),"undefined"==typeof f)if(o)for(var h=a;h--&&(p=n[h],!(f=l&&l===p||e(l,p,r,o,i,u))););else f=l&&l===p||e(l,p,r,o,i,u)}return!!f}function u(t,n,e){switch(e){case h:case d:return+t==+n;case g:return t.name==n.name&&t.message==n.message;case y:return t!=+t?n!=+n:0==t?1/t==1/n:t==+n;case b:case m:return t==n+""}return!1}function s(t,n,e,r,o,i,u){var s=f(t),c=s.length,a=f(n),l=a.length;if(c!=l&&!o)return!1;for(var p,h=-1;++h<c;){var d=s[h],g=S.call(n,d);if(g){var y=t[d],v=n[d];g=void 0,r&&(g=o?r(v,y,d):r(y,v,d)),"undefined"==typeof g&&(g=y&&y===v||e(y,v,r,o,i,u))}if(!g)return!1;p||(p="constructor"==d)}if(!p){var b=t.constructor,m=n.constructor;if(b!=m&&"constructor"in t&&"constructor"in n&&!("function"==typeof b&&b instanceof b&&"function"==typeof m&&m instanceof m))return!1}return!0}var c=e(27),a=e(70),f=e(49),l="[object Arguments]",p="[object Array]",h="[object Boolean]",d="[object Date]",g="[object Error]",y="[object Number]",v="[object Object]",b="[object RegExp]",m="[object String]",j=Object.prototype,S=j.hasOwnProperty,w=j.toString;t.exports=r},function(t,n,e){function r(t,n){return t=+t,n=null==n?g:n,t>-1&&t%1==0&&n>t}function o(t){return"number"==typeof t&&t>-1&&t%1==0&&g>=t}function i(t){for(var n=s(t),e=n.length,i=e&&t.length,u=i&&o(i)&&(a(t)||y.nonEnumArgs&&c(t)),f=-1,l=[];++f<e;){var h=n[f];(u&&r(h,i)||p.call(t,h))&&l.push(h)}return l}function u(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function s(t){if(null==t)return[];u(t)||(t=Object(t));var n=t.length;n=n&&o(n)&&(a(t)||y.nonEnumArgs&&c(t))&&n||0;for(var e=t.constructor,i=-1,s="function"==typeof e&&e.prototype===t,f=Array(n),l=n>0;++i<n;)f[i]=i+"";for(var h in t)l&&r(h,n)||"constructor"==h&&(s||!p.call(t,h))||f.push(h);return f}var c=e(71),a=e(72),f=e(73),l=Object.prototype,p=l.hasOwnProperty,h=l.propertyIsEnumerable,d=f(d=Object.keys)&&d,g=Math.pow(2,53)-1,y={};!function(){try{y.nonEnumArgs=!h.call(arguments,1)}catch(t){y.nonEnumArgs=!0}}(0,0);var v=d?function(t){if(t)var n=t.constructor,e=t.length;return"function"==typeof n&&n.prototype===t||"function"!=typeof t&&e&&o(e)?i(t):u(t)?d(t):[]}:i;t.exports=v},function(t){function n(t,n,r){if("function"!=typeof t)return e;if("undefined"==typeof n)return t;switch(r){case 1:return function(e){return t.call(n,e)};case 3:return function(e,r,o){return t.call(n,e,r,o)};case 4:return function(e,r,o,i){return t.call(n,e,r,o,i)};case 5:return function(e,r,o,i,u){return t.call(n,e,r,o,i,u)}}return function(){return t.apply(n,arguments)}}function e(t){return t}t.exports=n},function(t,n,e){function r(t,n){return t=+t,n=null==n?g:n,t>-1&&t%1==0&&n>t}function o(t){return"number"==typeof t&&t>-1&&t%1==0&&g>=t}function i(t){for(var n=s(t),e=n.length,i=e&&t.length,u=i&&o(i)&&(a(t)||y.nonEnumArgs&&c(t)),f=-1,l=[];++f<e;){var h=n[f];(u&&r(h,i)||p.call(t,h))&&l.push(h)}return l}function u(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function s(t){if(null==t)return[];u(t)||(t=Object(t));var n=t.length;n=n&&o(n)&&(a(t)||y.nonEnumArgs&&c(t))&&n||0;for(var e=t.constructor,i=-1,s="function"==typeof e&&e.prototype===t,f=Array(n),l=n>0;++i<n;)f[i]=i+"";for(var h in t)l&&r(h,n)||"constructor"==h&&(s||!p.call(t,h))||f.push(h);return f}var c=e(74),a=e(27),f=e(75),l=Object.prototype,p=l.hasOwnProperty,h=l.propertyIsEnumerable,d=f(d=Object.keys)&&d,g=Math.pow(2,53)-1,y={};!function(){try{y.nonEnumArgs=!h.call(arguments,1)}catch(t){y.nonEnumArgs=!0}}(0,0);var v=d?function(t){if(t)var n=t.constructor,e=t.length;return"function"==typeof n&&n.prototype===t||"function"!=typeof t&&e&&o(e)?i(t):u(t)?d(t):[]}:i;t.exports=v},function(t,n,e){function r(t,n){var e=t?t.length:0;if(!u(e))return i(t,n);for(var r=-1,o=s(t);++r<e&&n(o[r],r,o)!==!1;);return t}function o(t,n,e){for(var r=-1,o=s(t),i=e(t),u=i.length;++r<u;){var c=i[r];if(n(o[c],c,o)===!1)break}return t}function i(t,n){return o(t,n,a)}function u(t){return"number"==typeof t&&t>-1&&t%1==0&&f>=t}function s(t){return c(t)?t:Object(t)}function c(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}var a=e(76),f=Math.pow(2,53)-1;t.exports=r},function(t,n,e){function r(t,n){return t=+t,n=null==n?g:n,t>-1&&t%1==0&&n>t}function o(t){return"number"==typeof t&&t>-1&&t%1==0&&g>=t}function i(t){for(var n=s(t),e=n.length,i=e&&t.length,u=i&&o(i)&&(a(t)||y.nonEnumArgs&&c(t)),f=-1,l=[];++f<e;){var h=n[f];(u&&r(h,i)||p.call(t,h))&&l.push(h)}return l}function u(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function s(t){if(null==t)return[];u(t)||(t=Object(t));var n=t.length;n=n&&o(n)&&(a(t)||y.nonEnumArgs&&c(t))&&n||0;for(var e=t.constructor,i=-1,s="function"==typeof e&&e.prototype===t,f=Array(n),l=n>0;++i<n;)f[i]=i+"";for(var h in t)l&&r(h,n)||"constructor"==h&&(s||!p.call(t,h))||f.push(h);return f}var c=e(77),a=e(78),f=e(79),l=Object.prototype,p=l.hasOwnProperty,h=l.propertyIsEnumerable,d=f(d=Object.keys)&&d,g=Math.pow(2,53)-1,y={};!function(){try{y.nonEnumArgs=!h.call(arguments,1)}catch(t){y.nonEnumArgs=!0}}(0,0);var v=d?function(t){if(t)var n=t.constructor,e=t.length;return"function"==typeof n&&n.prototype===t||"function"!=typeof t&&e&&o(e)?i(t):u(t)?d(t):[]}:i;t.exports=v},function(t){function n(t,n,e){e||(e=n,n={});for(var r=-1,o=e.length;++r<o;){var i=e[r];n[i]=t[i]}return n}t.exports=n},function(t){function n(t,n,r){if("function"!=typeof t)return e;if("undefined"==typeof n)return t;switch(r){case 1:return function(e){return t.call(n,e)};case 3:return function(e,r,o){return t.call(n,e,r,o)};case 4:return function(e,r,o,i){return t.call(n,e,r,o,i)};case 5:return function(e,r,o,i,u){return t.call(n,e,r,o,i,u)}}return function(){return t.apply(n,arguments)}}function e(t){return t}t.exports=n},function(t){function n(t,n){return t=+t,n=null==n?i:n,t>-1&&t%1==0&&n>t}function e(t,e,i){if(!o(i))return!1;var u=typeof e;if("number"==u)var s=i.length,c=r(s)&&n(e,s);else c="string"==u&&e in i;return c&&i[e]===t}function r(t){return"number"==typeof t&&t>-1&&t%1==0&&i>=t}function o(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}var i=Math.pow(2,53)-1;t.exports=e},function(t){function n(t){if(null==t)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(t),e=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var o=arguments[r];if(null!=o){var i=Object(o);for(var u in i)e.call(i,u)&&(n[u]=i[u])}}return n}t.exports=n},function(t){function n(t){return function(){return t}}function e(){}e.thatReturns=n,e.thatReturnsFalse=n(!1),e.thatReturnsTrue=n(!0),e.thatReturnsNull=n(null),e.thatReturnsThis=function(){return this},e.thatReturnsArgument=function(t){return t},t.exports=e},function(t){"use strict";var n=function(t,n,e,r,o,i,u,s){if(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 a=[e,r,o,i,u,s],f=0;c=new Error("Invariant Violation: "+n.replace(/%s/g,function(){return a[f++]}))}throw c.framesToPop=1,c}};t.exports=n},function(t){"use strict";function n(t){t||(t="");var n,e=arguments.length;if(e>1)for(var r=1;e>r;r++)n=arguments[r],n&&(t=(t?t+" ":"")+n);return t}t.exports=n},function(t,n,e){"use strict";var r=e(55),o={current:{},withContext:function(t,n){var e,i=o.current;o.current=r({},i,t);try{e=n()}finally{o.current=i}return e}};t.exports=o},function(t){"use strict";var n={current:null};t.exports=n},function(t,n,e){function r(t,n,e,i,u,s){if(t===n)return 0!==t||1/t==1/n;var c=typeof t,a=typeof n;return"function"!=c&&"object"!=c&&"function"!=a&&"object"!=a||null==t||null==n?t!==t&&n!==n:o(t,n,r,e,i,u,s)}function o(t,n,e,r,o,f,h){var d=c(t),g=c(n),y=p,b=p;d||(y=w.call(t),y==l?y=v:y!=v&&(d=a(t))),g||(b=w.call(n),b==l?b=v:b!=v&&(g=a(n)));var m=y==v,j=b==v,x=y==b;if(x&&!d&&!m)return u(t,n,y);var E=m&&S.call(t,"__wrapped__"),A=j&&S.call(n,"__wrapped__");if(E||A)return e(E?t.value():t,A?n.value():n,r,o,f,h);if(!x)return!1;f||(f=[]),h||(h=[]);for(var O=f.length;O--;)if(f[O]==t)return h[O]==n;f.push(t),h.push(n);var M=(d?i:s)(t,n,e,r,o,f,h);return f.pop(),h.pop(),M}function i(t,n,e,r,o,i,u){var s=-1,c=t.length,a=n.length,f=!0;if(c!=a&&!(o&&a>c))return!1;for(;f&&++s<c;){var l=t[s],p=n[s];if(f=void 0,r&&(f=o?r(p,l,s):r(l,p,s)),"undefined"==typeof f)if(o)for(var h=a;h--&&(p=n[h],!(f=l&&l===p||e(l,p,r,o,i,u))););else f=l&&l===p||e(l,p,r,o,i,u)}return!!f}function u(t,n,e){switch(e){case h:case d:return+t==+n;case g:return t.name==n.name&&t.message==n.message;case y:return t!=+t?n!=+n:0==t?1/t==1/n:t==+n;case b:case m:return t==n+""}return!1}function s(t,n,e,r,o,i,u){var s=f(t),c=s.length,a=f(n),l=a.length;if(c!=l&&!o)return!1;for(var p,h=-1;++h<c;){var d=s[h],g=S.call(n,d);if(g){var y=t[d],v=n[d];g=void 0,r&&(g=o?r(v,y,d):r(y,v,d)),"undefined"==typeof g&&(g=y&&y===v||e(y,v,r,o,i,u))}if(!g)return!1;p||(p="constructor"==d)}if(!p){var b=t.constructor,m=n.constructor;if(b!=m&&"constructor"in t&&"constructor"in n&&!("function"==typeof b&&b instanceof b&&"function"==typeof m&&m instanceof m))return!1}return!0}var c=e(42),a=e(85),f=e(63),l="[object Arguments]",p="[object Array]",h="[object Boolean]",d="[object Date]",g="[object Error]",y="[object Number]",v="[object Object]",b="[object RegExp]",m="[object String]",j=Object.prototype,S=j.hasOwnProperty,w=j.toString;t.exports=r},function(t){function n(t,n,r){if("function"!=typeof t)return e;if("undefined"==typeof n)return t;switch(r){case 1:return function(e){return t.call(n,e)};case 3:return function(e,r,o){return t.call(n,e,r,o)};case 4:return function(e,r,o,i){return t.call(n,e,r,o,i)};case 5:return function(e,r,o,i,u){return t.call(n,e,r,o,i,u)}}return function(){return t.apply(n,arguments)}}function e(t){return t}t.exports=n},function(t,n,e){function r(t,n){return t=+t,n=null==n?g:n,t>-1&&t%1==0&&n>t}function o(t){return"number"==typeof t&&t>-1&&t%1==0&&g>=t}function i(t){for(var n=s(t),e=n.length,i=e&&t.length,u=i&&o(i)&&(a(t)||y.nonEnumArgs&&c(t)),f=-1,l=[];++f<e;){var h=n[f];(u&&r(h,i)||p.call(t,h))&&l.push(h)}return l}function u(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function s(t){if(null==t)return[];u(t)||(t=Object(t));var n=t.length;n=n&&o(n)&&(a(t)||y.nonEnumArgs&&c(t))&&n||0;for(var e=t.constructor,i=-1,s="function"==typeof e&&e.prototype===t,f=Array(n),l=n>0;++i<n;)f[i]=i+"";for(var h in t)l&&r(h,n)||"constructor"==h&&(s||!p.call(t,h))||f.push(h);return f}var c=e(80),a=e(42),f=e(81),l=Object.prototype,p=l.hasOwnProperty,h=l.propertyIsEnumerable,d=f(d=Object.keys)&&d,g=Math.pow(2,53)-1,y={};!function(){try{y.nonEnumArgs=!h.call(arguments,1)}catch(t){y.nonEnumArgs=!0}}(0,0);var v=d?function(t){if(t)var n=t.constructor,e=t.length;return"function"==typeof n&&n.prototype===t||"function"!=typeof t&&e&&o(e)?i(t):u(t)?d(t):[]}:i;t.exports=v},function(t,n,e){function r(t,n){return t=+t,n=null==n?g:n,t>-1&&t%1==0&&n>t}function o(t){return"number"==typeof t&&t>-1&&t%1==0&&g>=t}function i(t){for(var n=s(t),e=n.length,i=e&&t.length,u=i&&o(i)&&(a(t)||y.nonEnumArgs&&c(t)),f=-1,l=[];++f<e;){var h=n[f];(u&&r(h,i)||p.call(t,h))&&l.push(h)}return l}function u(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function s(t){if(null==t)return[];u(t)||(t=Object(t));var n=t.length;n=n&&o(n)&&(a(t)||y.nonEnumArgs&&c(t))&&n||0;for(var e=t.constructor,i=-1,s="function"==typeof e&&e.prototype===t,f=Array(n),l=n>0;++i<n;)f[i]=i+"";for(var h in t)l&&r(h,n)||"constructor"==h&&(s||!p.call(t,h))||f.push(h);return f}var c=e(82),a=e(42),f=e(83),l=Object.prototype,p=l.hasOwnProperty,h=l.propertyIsEnumerable,d=f(d=Object.keys)&&d,g=Math.pow(2,53)-1,y={};!function(){try{y.nonEnumArgs=!h.call(arguments,1)}catch(t){y.nonEnumArgs=!0}}(0,0);var v=d?function(t){if(t)var n=t.constructor,e=t.length;return"function"==typeof n&&n.prototype===t||"function"!=typeof t&&e&&o(e)?i(t):u(t)?d(t):[]}:i;t.exports=v},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return"number"==typeof t&&t>-1&&t%1==0&&y>=t}function o(t){return null==t?!1:h.call(t)==s?d.test(p.call(t)):e(t)&&c.test(t)||!1}function i(t){return t=n(t),t&&f.test(t)?t.replace(a,"\\$&"):t}var u="[object Array]",s="[object Function]",c=/^\[object .+?Constructor\]$/,a=/[.*+?^${}()|[\]\/\\]/g,f=RegExp(a.source),l=Object.prototype,p=Function.prototype.toString,h=l.toString,d=RegExp("^"+i(h).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),g=o(g=Array.isArray)&&g,y=Math.pow(2,53)-1,v=g||function(t){return e(t)&&r(t.length)&&h.call(t)==u||!1};t.exports=v},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&T>=t}function r(t){return n(t)&&e(t.length)&&M[C.call(t)]||!1}var o="[object Arguments]",i="[object Array]",u="[object Boolean]",s="[object Date]",c="[object Error]",a="[object Function]",f="[object Map]",l="[object Number]",p="[object Object]",h="[object RegExp]",d="[object Set]",g="[object String]",y="[object WeakMap]",v="[object ArrayBuffer]",b="[object Float32Array]",m="[object Float64Array]",j="[object Int8Array]",S="[object Int16Array]",w="[object Int32Array]",x="[object Uint8Array]",E="[object Uint8ClampedArray]",A="[object Uint16Array]",O="[object Uint32Array]",M={};M[b]=M[m]=M[j]=M[S]=M[w]=M[x]=M[E]=M[A]=M[O]=!0,M[o]=M[i]=M[v]=M[u]=M[s]=M[c]=M[a]=M[f]=M[l]=M[p]=M[h]=M[d]=M[g]=M[y]=!1;var k=Object.prototype,C=k.toString,T=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&s>=t}function r(t){var r=n(t)?t.length:void 0;return e(r)&&u.call(t)==o||!1}var o="[object Arguments]",i=Object.prototype,u=i.toString,s=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return"number"==typeof t&&t>-1&&t%1==0&&y>=t}function o(t){return null==t?!1:h.call(t)==s?d.test(p.call(t)):e(t)&&c.test(t)||!1}function i(t){return t=n(t),t&&f.test(t)?t.replace(a,"\\$&"):t}var u="[object Array]",s="[object Function]",c=/^\[object .+?Constructor\]$/,a=/[.*+?^${}()|[\]\/\\]/g,f=RegExp(a.source),l=Object.prototype,p=Function.prototype.toString,h=l.toString,d=RegExp("^"+i(h).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),g=o(g=Array.isArray)&&g,y=Math.pow(2,53)-1,v=g||function(t){return e(t)&&r(t.length)&&h.call(t)==u||!1};t.exports=v},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return null==t?!1:l.call(t)==i?p.test(f.call(t)):e(t)&&u.test(t)||!1}function o(t){return t=n(t),t&&c.test(t)?t.replace(s,"\\$&"):t}var i="[object Function]",u=/^\[object .+?Constructor\]$/,s=/[.*+?^${}()|[\]\/\\]/g,c=RegExp(s.source),a=Object.prototype,f=Function.prototype.toString,l=a.toString,p=RegExp("^"+o(l).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=r},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&T>=t}function r(t){return n(t)&&e(t.length)&&M[C.call(t)]||!1}var o="[object Arguments]",i="[object Array]",u="[object Boolean]",s="[object Date]",c="[object Error]",a="[object Function]",f="[object Map]",l="[object Number]",p="[object Object]",h="[object RegExp]",d="[object Set]",g="[object String]",y="[object WeakMap]",v="[object ArrayBuffer]",b="[object Float32Array]",m="[object Float64Array]",j="[object Int8Array]",S="[object Int16Array]",w="[object Int32Array]",x="[object Uint8Array]",E="[object Uint8ClampedArray]",A="[object Uint16Array]",O="[object Uint32Array]",M={};M[b]=M[m]=M[j]=M[S]=M[w]=M[x]=M[E]=M[A]=M[O]=!0,M[o]=M[i]=M[v]=M[u]=M[s]=M[c]=M[a]=M[f]=M[l]=M[p]=M[h]=M[d]=M[g]=M[y]=!1;var k=Object.prototype,C=k.toString,T=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&s>=t}function r(t){var r=n(t)?t.length:void 0;return e(r)&&u.call(t)==o||!1}var o="[object Arguments]",i=Object.prototype,u=i.toString,s=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return"number"==typeof t&&t>-1&&t%1==0&&y>=t}function o(t){return null==t?!1:h.call(t)==s?d.test(p.call(t)):e(t)&&c.test(t)||!1}function i(t){return t=n(t),t&&f.test(t)?t.replace(a,"\\$&"):t}var u="[object Array]",s="[object Function]",c=/^\[object .+?Constructor\]$/,a=/[.*+?^${}()|[\]\/\\]/g,f=RegExp(a.source),l=Object.prototype,p=Function.prototype.toString,h=l.toString,d=RegExp("^"+i(h).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),g=o(g=Array.isArray)&&g,y=Math.pow(2,53)-1,v=g||function(t){return e(t)&&r(t.length)&&h.call(t)==u||!1};t.exports=v},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return null==t?!1:l.call(t)==i?p.test(f.call(t)):e(t)&&u.test(t)||!1}function o(t){return t=n(t),t&&c.test(t)?t.replace(s,"\\$&"):t}var i="[object Function]",u=/^\[object .+?Constructor\]$/,s=/[.*+?^${}()|[\]\/\\]/g,c=RegExp(s.source),a=Object.prototype,f=Function.prototype.toString,l=a.toString,p=RegExp("^"+o(l).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=r},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&s>=t}function r(t){var r=n(t)?t.length:void 0;return e(r)&&u.call(t)==o||!1}var o="[object Arguments]",i=Object.prototype,u=i.toString,s=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return null==t?!1:l.call(t)==i?p.test(f.call(t)):e(t)&&u.test(t)||!1}function o(t){return t=n(t),t&&c.test(t)?t.replace(s,"\\$&"):t}var i="[object Function]",u=/^\[object .+?Constructor\]$/,s=/[.*+?^${}()|[\]\/\\]/g,c=RegExp(s.source),a=Object.prototype,f=Function.prototype.toString,l=a.toString,p=RegExp("^"+o(l).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=r},function(t,n,e){function r(t,n){return t=+t,n=null==n?g:n,t>-1&&t%1==0&&n>t}function o(t){return"number"==typeof t&&t>-1&&t%1==0&&g>=t}function i(t){for(var n=s(t),e=n.length,i=e&&t.length,u=i&&o(i)&&(a(t)||y.nonEnumArgs&&c(t)),f=-1,l=[];++f<e;){var h=n[f];(u&&r(h,i)||p.call(t,h))&&l.push(h)}return l}function u(t){var n=typeof t;return"function"==n||t&&"object"==n||!1}function s(t){if(null==t)return[];u(t)||(t=Object(t));var n=t.length;n=n&&o(n)&&(a(t)||y.nonEnumArgs&&c(t))&&n||0;for(var e=t.constructor,i=-1,s="function"==typeof e&&e.prototype===t,f=Array(n),l=n>0;++i<n;)f[i]=i+"";for(var h in t)l&&r(h,n)||"constructor"==h&&(s||!p.call(t,h))||f.push(h);return f}var c=e(84),a=e(27),f=e(86),l=Object.prototype,p=l.hasOwnProperty,h=l.propertyIsEnumerable,d=f(d=Object.keys)&&d,g=Math.pow(2,53)-1,y={};!function(){try{y.nonEnumArgs=!h.call(arguments,1)}catch(t){y.nonEnumArgs=!0}}(0,0);var v=d?function(t){if(t)var n=t.constructor,e=t.length;return"function"==typeof n&&n.prototype===t||"function"!=typeof t&&e&&o(e)?i(t):u(t)?d(t):[]}:i;t.exports=v},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&s>=t}function r(t){var r=n(t)?t.length:void 0;return e(r)&&u.call(t)==o||!1}var o="[object Arguments]",i=Object.prototype,u=i.toString,s=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return"number"==typeof t&&t>-1&&t%1==0&&y>=t}function o(t){return null==t?!1:h.call(t)==s?d.test(p.call(t)):e(t)&&c.test(t)||!1}function i(t){return t=n(t),t&&f.test(t)?t.replace(a,"\\$&"):t}var u="[object Array]",s="[object Function]",c=/^\[object .+?Constructor\]$/,a=/[.*+?^${}()|[\]\/\\]/g,f=RegExp(a.source),l=Object.prototype,p=Function.prototype.toString,h=l.toString,d=RegExp("^"+i(h).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),g=o(g=Array.isArray)&&g,y=Math.pow(2,53)-1,v=g||function(t){return e(t)&&r(t.length)&&h.call(t)==u||!1};t.exports=v},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return null==t?!1:l.call(t)==i?p.test(f.call(t)):e(t)&&u.test(t)||!1}function o(t){return t=n(t),t&&c.test(t)?t.replace(s,"\\$&"):t}var i="[object Function]",u=/^\[object .+?Constructor\]$/,s=/[.*+?^${}()|[\]\/\\]/g,c=RegExp(s.source),a=Object.prototype,f=Function.prototype.toString,l=a.toString,p=RegExp("^"+o(l).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=r},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&s>=t}function r(t){var r=n(t)?t.length:void 0;return e(r)&&u.call(t)==o||!1}var o="[object Arguments]",i=Object.prototype,u=i.toString,s=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return null==t?!1:l.call(t)==i?p.test(f.call(t)):e(t)&&u.test(t)||!1}function o(t){return t=n(t),t&&c.test(t)?t.replace(s,"\\$&"):t}var i="[object Function]",u=/^\[object .+?Constructor\]$/,s=/[.*+?^${}()|[\]\/\\]/g,c=RegExp(s.source),a=Object.prototype,f=Function.prototype.toString,l=a.toString,p=RegExp("^"+o(l).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=r},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&s>=t}function r(t){var r=n(t)?t.length:void 0;return e(r)&&u.call(t)==o||!1}var o="[object Arguments]",i=Object.prototype,u=i.toString,s=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return null==t?!1:l.call(t)==i?p.test(f.call(t)):e(t)&&u.test(t)||!1}function o(t){return t=n(t),t&&c.test(t)?t.replace(s,"\\$&"):t}var i="[object Function]",u=/^\[object .+?Constructor\]$/,s=/[.*+?^${}()|[\]\/\\]/g,c=RegExp(s.source),a=Object.prototype,f=Function.prototype.toString,l=a.toString,p=RegExp("^"+o(l).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=r},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&s>=t}function r(t){var r=n(t)?t.length:void 0;return e(r)&&u.call(t)==o||!1}var o="[object Arguments]",i=Object.prototype,u=i.toString,s=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return t&&"object"==typeof t||!1}function e(t){return"number"==typeof t&&t>-1&&t%1==0&&T>=t}function r(t){return n(t)&&e(t.length)&&M[C.call(t)]||!1}var o="[object Arguments]",i="[object Array]",u="[object Boolean]",s="[object Date]",c="[object Error]",a="[object Function]",f="[object Map]",l="[object Number]",p="[object Object]",h="[object RegExp]",d="[object Set]",g="[object String]",y="[object WeakMap]",v="[object ArrayBuffer]",b="[object Float32Array]",m="[object Float64Array]",j="[object Int8Array]",S="[object Int16Array]",w="[object Int32Array]",x="[object Uint8Array]",E="[object Uint8ClampedArray]",A="[object Uint16Array]",O="[object Uint32Array]",M={};M[b]=M[m]=M[j]=M[S]=M[w]=M[x]=M[E]=M[A]=M[O]=!0,M[o]=M[i]=M[v]=M[u]=M[s]=M[c]=M[a]=M[f]=M[l]=M[p]=M[h]=M[d]=M[g]=M[y]=!1;var k=Object.prototype,C=k.toString,T=Math.pow(2,53)-1;t.exports=r},function(t){function n(t){return"string"==typeof t?t:null==t?"":t+""}function e(t){return t&&"object"==typeof t||!1}function r(t){return null==t?!1:l.call(t)==i?p.test(f.call(t)):e(t)&&u.test(t)||!1}function o(t){return t=n(t),t&&c.test(t)?t.replace(s,"\\$&"):t}var i="[object Function]",u=/^\[object .+?Constructor\]$/,s=/[.*+?^${}()|[\]\/\\]/g,c=RegExp(s.source),a=Object.prototype,f=Function.prototype.toString,l=a.toString,p=RegExp("^"+o(l).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=r}])});
ajax/libs/material-ui/4.9.3/esm/Dialog/Dialog.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; /* eslint-disable jsx-a11y/click-events-have-key-events */ import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import capitalize from '../utils/capitalize'; import Modal from '../Modal'; import Backdrop from '../Backdrop'; import Fade from '../Fade'; import { duration } from '../styles/transitions'; import Paper from '../Paper'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { '@media print': { // Use !important to override the Modal inline-style. position: 'absolute !important' } }, /* Styles applied to the container element if `scroll="paper"`. */ scrollPaper: { display: 'flex', justifyContent: 'center', alignItems: 'center' }, /* Styles applied to the container element if `scroll="body"`. */ scrollBody: { overflowY: 'auto', overflowX: 'hidden', textAlign: 'center', '&:after': { content: '""', display: 'inline-block', verticalAlign: 'middle', height: '100%', width: '0' } }, /* Styles applied to the container element. */ container: { height: '100%', '@media print': { height: 'auto' }, // We disable the focus ring for mouse, touch and keyboard users. outline: 0 }, /* Styles applied to the `Paper` component. */ paper: { margin: 32, position: 'relative', overflowY: 'auto', // Fix IE 11 issue, to remove at some point. '@media print': { overflowY: 'visible', boxShadow: 'none' } }, /* Styles applied to the `Paper` component if `scroll="paper"`. */ paperScrollPaper: { display: 'flex', flexDirection: 'column', maxHeight: 'calc(100% - 64px)' }, /* Styles applied to the `Paper` component if `scroll="body"`. */ paperScrollBody: { display: 'inline-block', verticalAlign: 'middle', textAlign: 'left' // 'initial' doesn't work on IE 11 }, /* Styles applied to the `Paper` component if `maxWidth=false`. */ paperWidthFalse: { maxWidth: 'calc(100% - 64px)' }, /* Styles applied to the `Paper` component if `maxWidth="xs"`. */ paperWidthXs: { maxWidth: Math.max(theme.breakpoints.values.xs, 444), '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(Math.max(theme.breakpoints.values.xs, 444) + 32 * 2), { maxWidth: 'calc(100% - 64px)' }) }, /* Styles applied to the `Paper` component if `maxWidth="sm"`. */ paperWidthSm: { maxWidth: theme.breakpoints.values.sm, '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.sm + 32 * 2), { maxWidth: 'calc(100% - 64px)' }) }, /* Styles applied to the `Paper` component if `maxWidth="md"`. */ paperWidthMd: { maxWidth: theme.breakpoints.values.md, '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.md + 32 * 2), { maxWidth: 'calc(100% - 64px)' }) }, /* Styles applied to the `Paper` component if `maxWidth="lg"`. */ paperWidthLg: { maxWidth: theme.breakpoints.values.lg, '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.lg + 32 * 2), { maxWidth: 'calc(100% - 64px)' }) }, /* Styles applied to the `Paper` component if `maxWidth="xl"`. */ paperWidthXl: { maxWidth: theme.breakpoints.values.xl, '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.xl + 32 * 2), { maxWidth: 'calc(100% - 64px)' }) }, /* Styles applied to the `Paper` component if `fullWidth={true}`. */ paperFullWidth: { width: 'calc(100% - 64px)' }, /* Styles applied to the `Paper` component if `fullScreen={true}`. */ paperFullScreen: { margin: 0, width: '100%', maxWidth: '100%', height: '100%', maxHeight: 'none', borderRadius: 0, '&$paperScrollBody': { margin: 0, maxWidth: '100%' } } }; }; var defaultTransitionDuration = { enter: duration.enteringScreen, exit: duration.leavingScreen }; /** * Dialogs are overlaid modal paper based components with a backdrop. */ var Dialog = React.forwardRef(function Dialog(props, ref) { var BackdropProps = props.BackdropProps, children = props.children, classes = props.classes, className = props.className, _props$disableBackdro = props.disableBackdropClick, disableBackdropClick = _props$disableBackdro === void 0 ? false : _props$disableBackdro, _props$disableEscapeK = props.disableEscapeKeyDown, disableEscapeKeyDown = _props$disableEscapeK === void 0 ? false : _props$disableEscapeK, _props$fullScreen = props.fullScreen, fullScreen = _props$fullScreen === void 0 ? false : _props$fullScreen, _props$fullWidth = props.fullWidth, fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth, _props$maxWidth = props.maxWidth, maxWidth = _props$maxWidth === void 0 ? 'sm' : _props$maxWidth, onBackdropClick = props.onBackdropClick, onClose = props.onClose, onEnter = props.onEnter, onEntered = props.onEntered, onEntering = props.onEntering, onEscapeKeyDown = props.onEscapeKeyDown, onExit = props.onExit, onExited = props.onExited, onExiting = props.onExiting, open = props.open, _props$PaperComponent = props.PaperComponent, PaperComponent = _props$PaperComponent === void 0 ? Paper : _props$PaperComponent, _props$PaperProps = props.PaperProps, PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps, _props$scroll = props.scroll, scroll = _props$scroll === void 0 ? 'paper' : _props$scroll, _props$TransitionComp = props.TransitionComponent, TransitionComponent = _props$TransitionComp === void 0 ? Fade : _props$TransitionComp, _props$transitionDura = props.transitionDuration, transitionDuration = _props$transitionDura === void 0 ? defaultTransitionDuration : _props$transitionDura, TransitionProps = props.TransitionProps, ariaDescribedby = props['aria-describedby'], ariaLabelledby = props['aria-labelledby'], other = _objectWithoutProperties(props, ["BackdropProps", "children", "classes", "className", "disableBackdropClick", "disableEscapeKeyDown", "fullScreen", "fullWidth", "maxWidth", "onBackdropClick", "onClose", "onEnter", "onEntered", "onEntering", "onEscapeKeyDown", "onExit", "onExited", "onExiting", "open", "PaperComponent", "PaperProps", "scroll", "TransitionComponent", "transitionDuration", "TransitionProps", "aria-describedby", "aria-labelledby"]); var mouseDownTarget = React.useRef(); var handleMouseDown = function handleMouseDown(event) { mouseDownTarget.current = event.target; }; var handleBackdropClick = function handleBackdropClick(event) { // Ignore the events not coming from the "backdrop" // We don't want to close the dialog when clicking the dialog content. if (event.target !== event.currentTarget) { return; } // Make sure the event starts and ends on the same DOM element. if (event.target !== mouseDownTarget.current) { return; } mouseDownTarget.current = null; if (onBackdropClick) { onBackdropClick(event); } if (!disableBackdropClick && onClose) { onClose(event, 'backdropClick'); } }; return React.createElement(Modal, _extends({ className: clsx(classes.root, className), BackdropComponent: Backdrop, BackdropProps: _extends({ transitionDuration: transitionDuration }, BackdropProps), closeAfterTransition: true, disableBackdropClick: disableBackdropClick, disableEscapeKeyDown: disableEscapeKeyDown, onEscapeKeyDown: onEscapeKeyDown, onClose: onClose, open: open, ref: ref }, other), React.createElement(TransitionComponent, _extends({ appear: true, in: open, timeout: transitionDuration, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: onExited, role: "none presentation" }, TransitionProps), React.createElement("div", { className: clsx(classes.container, classes["scroll".concat(capitalize(scroll))]), onClick: handleBackdropClick, onMouseDown: handleMouseDown }, React.createElement(PaperComponent, _extends({ elevation: 24, role: "dialog", "aria-describedby": ariaDescribedby, "aria-labelledby": ariaLabelledby }, PaperProps, { className: clsx(classes.paper, classes["paperScroll".concat(capitalize(scroll))], classes["paperWidth".concat(capitalize(String(maxWidth)))], PaperProps.className, fullScreen && classes.paperFullScreen, fullWidth && classes.paperFullWidth) }), children)))); }); process.env.NODE_ENV !== "production" ? Dialog.propTypes = { /** * The id(s) of the element(s) that describe the dialog. */ 'aria-describedby': PropTypes.string, /** * The id(s) of the element(s) that label the dialog. */ 'aria-labelledby': PropTypes.string, /** * @ignore */ BackdropProps: PropTypes.object, /** * Dialog children, usually the included sub-components. */ children: PropTypes.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * If `true`, clicking the backdrop will not fire the `onClose` callback. */ disableBackdropClick: PropTypes.bool, /** * If `true`, hitting escape will not fire the `onClose` callback. */ disableEscapeKeyDown: PropTypes.bool, /** * If `true`, the dialog will be full-screen */ fullScreen: PropTypes.bool, /** * If `true`, the dialog stretches to `maxWidth`. * * Notice that the dialog width grow is limited by the default margin. */ fullWidth: PropTypes.bool, /** * Determine the max-width of the dialog. * The dialog width grows with the size of the screen. * Set to `false` to disable `maxWidth`. */ maxWidth: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl', false]), /** * Callback fired when the backdrop is clicked. */ onBackdropClick: PropTypes.func, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback. * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`. */ onClose: PropTypes.func, /** * Callback fired before the dialog enters. */ onEnter: PropTypes.func, /** * Callback fired when the dialog has entered. */ onEntered: PropTypes.func, /** * Callback fired when the dialog is entering. */ onEntering: PropTypes.func, /** * Callback fired when the escape key is pressed, * `disableKeyboard` is false and the modal is in focus. */ onEscapeKeyDown: PropTypes.func, /** * Callback fired before the dialog exits. */ onExit: PropTypes.func, /** * Callback fired when the dialog has exited. */ onExited: PropTypes.func, /** * Callback fired when the dialog is exiting. */ onExiting: PropTypes.func, /** * If `true`, the Dialog is open. */ open: PropTypes.bool.isRequired, /** * The component used to render the body of the dialog. */ PaperComponent: PropTypes.elementType, /** * Props applied to the [`Paper`](/api/paper/) element. */ PaperProps: PropTypes.object, /** * Determine the container for scrolling the dialog. */ scroll: PropTypes.oneOf(['body', 'paper']), /** * 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, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number })]), /** * 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: 'MuiDialog' })(Dialog);
react/src/components/dashboard/exchangesTOSModal/exchangesTOSModal.render.js
pbca26/EasyDEX-GUI
import React from 'react'; import translate from '../../../translate/translate'; import Config from '../../../config'; const ExchangesTOSModalRender = function() { return ( <div onKeyDown={ (event) => this.handleKeydown(event) }> <div className={ `modal modal-3d-sign exchanges-tos-modal ${this.state.className}` } id="kmd_txid_info_mdl"> <div onClick={ this.close } className="modal-close-overlay"></div> <div className="modal-dialog modal-center modal-lg"> <div onClick={ this.close } className="modal-close-overlay"></div> <div className="modal-content"> <div className="modal-header bg-orange-a400 wallet-send-header"> <button type="button" className="close white" onClick={ this.close }> <span>×</span> </button> <h4 className="modal-title white"> { translate('EXCHANGES.EXCHANGE_TOS') } </h4> </div> <div className="modal-body modal-body-container"> <p>{ translate('EXCHANGES.TOS_P1') } <a onClick={ this.openCoinswitchTOS } className="pointer">{ translate('EXCHANGES.TOS_P2') }</a>. { translate('EXCHANGES.TOS_P3') } <a onClick={ this.openCoinswitchTOS } className="pointer">{ translate('EXCHANGES.TOS_P2') }</a>.</p> <p>{ translate('EXCHANGES.TOS_P4') }</p> </div> </div> </div> </div> <div className={ `modal-backdrop ${this.state.className}` }></div> </div> ); }; export default ExchangesTOSModalRender;
pages/api/list-item.js
Kagami/material-ui
import 'docs/src/modules/components/bootstrap'; // --- Post bootstrap ----- import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './list-item.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default Page;
ajax/libs/amcharts4/4.10.18/.internal/core/interaction/InteractionObject.js
cdnjs/cdnjs
/** * Interaction Object module */ import { __extends } from "tslib"; /** * ============================================================================ * IMPORTS * ============================================================================ * @hidden */ import { InteractionObjectEventDispatcher } from "./InteractionObjectEvents"; import { BaseObjectEvents } from "../Base"; import { List } from "../utils/List"; import { Dictionary, DictionaryDisposer } from "../utils/Dictionary"; import { getInteraction } from "./Interaction"; import * as $type from "../utils/Type"; /** * Re-exports */ export { InteractionObjectEventDispatcher }; /** * Interaction object represents an object that is subject for any kind of * interaction with it with any input devices: mouse, touch or keyboard. * * Any DOM element can be wrapped into an Internaction object which in turn * enables attaching various interaction events to it, such as: hit, drag, * swipe, etc. * * To create an [[InteractionObject]] out of a [[Sprite]], use: * `interaction.getInteractionFromSprite(sprite: Sprite)` * * To create an [[InteractionObject]] out of a a regular element: * `interaction.getInteraction(element: HTMLElement)` */ var InteractionObject = /** @class */ (function (_super) { __extends(InteractionObject, _super); /** * Constructor */ function InteractionObject(element) { var _this = _super.call(this) || this; /** * @ignore * An [[EventDispatcher]] instance which holds events for this object */ _this._eventDispatcher = new InteractionObjectEventDispatcher(_this); /** * Collection of Disposers for various events. (so that those get disposed * when the whole InteractionObject is disposed) * * @ignore Exclude from docs */ _this.eventDisposers = new Dictionary(); /** * A [[Dictionary]] that holds temporarily replaced original style values for * HTML element, so that they can be restored when the functionality that * replaced them is done. * * @ignore Exclude from docs */ _this.replacedStyles = new Dictionary(); _this._clickable = false; _this._contextMenuDisabled = false; _this._hoverable = false; _this._trackable = false; _this._draggable = false; _this._swipeable = false; _this._resizable = false; _this._wheelable = false; _this._inert = false; /** * Is element currently hovered? */ _this._isHover = false; /** * Was this element hovered via pointer or is it just "pretenting" to be * hovered. * * @ignore */ _this.isRealHover = false; /** * Is the element hovered by touch pointer? */ _this._isHoverByTouch = false; /** * Has element got any pointers currently pressing down on it? */ _this._isDown = false; /** * Does element have focus? */ _this._isFocused = false; /** * Is element currently protected from touch interactions? */ _this._isTouchProtected = false; /** * Options used for inertia functionality. */ _this._inertiaOptions = new Dictionary(); /** * A collection of different inertia types, currently playing out. * * @ignore Exclude from docs */ _this.inertias = new Dictionary(); /** * Click/tap options. */ _this._hitOptions = {}; /** * Hover options. */ _this._hoverOptions = {}; /** * Swipe gesture options. */ _this._swipeOptions = {}; /** * Keyboard options. */ _this._keyboardOptions = {}; /** * Mouse options. */ _this._mouseOptions = {}; /** * Cursor options. */ _this._cursorOptions = { "defaultStyle": [{ "property": "cursor", "value": "default" }] }; _this._disposers.push(_this._eventDispatcher); _this._element = element; _this.className = "InteractionObject"; _this._disposers.push(new DictionaryDisposer(_this.inertias)); _this._disposers.push(new DictionaryDisposer(_this.eventDisposers)); _this.applyTheme(); return _this; } ; Object.defineProperty(InteractionObject.prototype, "events", { /** * An [[EventDispatcher]] instance which holds events for this object */ get: function () { return this._eventDispatcher; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "isHover", { /** * @return Hovered? */ get: function () { return this._isHover; }, /** * Indicates if this element is currently hovered. * * @param value Hovered? */ set: function (value) { if (this.isHover != value) { this._isHover = value; if (value) { getInteraction().overObjects.moveValue(this); } else { this.isRealHover = false; getInteraction().overObjects.removeValue(this); } } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "isHoverByTouch", { /** * @return Hovered? */ get: function () { return this._isHoverByTouch; }, /** * Indicates if this element is currently hovered. * * @param value Hovered? */ set: function (value) { if (this.isHoverByTouch != value) { this._isHoverByTouch = value; } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "overPointers", { /** * A list of pointers currently over the element. * * @see {@link Pointer} * @return List if pointers currently hovering the element */ get: function () { if (!this._overPointers) { this._overPointers = new List(); } return this._overPointers; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "isDown", { /** * @return Has down pointers? */ get: function () { return this._isDown; }, /** * Indicates if this element has currently any pointers pressing on it. * * @param value Has down pointers? */ set: function (value) { if (this.isDown != value) { this._isDown = value; if (value) { getInteraction().downObjects.moveValue(this); } else { getInteraction().downObjects.removeValue(this); } } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "downPointers", { /** * A list of pointers currently pressing down on this element. * * @see {@link Pointer} * @return List of down pointers */ get: function () { if (!this._downPointers) { this._downPointers = new List(); } return this._downPointers; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "isFocused", { /** * @return Focused? */ get: function () { return this._isFocused; }, /** * Indicates if this element is currently focused. * * @param value Focused? */ set: function (value) { if (this.isFocused != value) { this._isFocused = value; if (value) { getInteraction().focusedObject = this; } else { getInteraction().focusedObject = undefined; } } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "isTouchProtected", { /** * @ignore * @return Touch protected? */ get: function () { return this._isTouchProtected; }, /** * Indicates if this element is currently being protected from touch actions. * * @ignore * @param value Touch protected? */ set: function (value) { if (this._isTouchProtected != value) { this._isTouchProtected = value; if (value) { getInteraction().unprepElement(this); } else if (this.draggable || this.swipeable || this.trackable || this.resizable) { getInteraction().prepElement(this); } } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "clickable", { /** * @return Clickable? */ get: function () { return this._clickable; }, /** * Is element clickable? Clickable elements will generate "hit" events when * clicked or tapped. * * @param value Clickable? */ set: function (value) { if (this._clickable !== value) { this._clickable = value; getInteraction().processClickable(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "contextMenuDisabled", { /** * @return Context menu disabled? */ get: function () { return this._contextMenuDisabled; }, /** * Should element prevent context menu to be displayed, e.g. when * right-clicked? * * @default false * @param value Context menu disabled? */ set: function (value) { if (this._contextMenuDisabled !== value) { this._contextMenuDisabled = value; getInteraction().processContextMenu(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "hoverable", { /** * @return Hoverable? */ get: function () { return this._hoverable; }, /** * Indicates if element should generate hover events. * * @param value Hoverable? */ set: function (value) { if (this._hoverable !== value) { this._hoverable = value; getInteraction().processHoverable(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "trackable", { /** * @return Track pointer? */ get: function () { return this._trackable; }, /** * Indicates if pointer movement over element should be tracked. * * @param value Track pointer? */ set: function (value) { if (this._trackable !== value) { this._trackable = value; getInteraction().processTrackable(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "draggable", { /** * @return Draggable? */ get: function () { return this._draggable; }, /** * Indicates if element can be dragged. (moved) * * @param value Draggable? */ set: function (value) { if (this._draggable !== value) { this._draggable = value; getInteraction().processDraggable(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "swipeable", { /** * @return Track swipe? */ get: function () { return this._swipeable; }, /** * Indicates whether element should react to swipe gesture. * * @param value Track swipe? */ set: function (value) { if (this._swipeable !== value) { this._swipeable = value; getInteraction().processSwipeable(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "resizable", { /** * @return Resizeble? */ get: function () { return this._resizable; }, /** * Indicates if element can be resized. * * @param value Resizeable? */ set: function (value) { if (this._resizable !== value) { this._resizable = value; getInteraction().processResizable(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "wheelable", { /** * @return Track wheel? */ get: function () { return this._wheelable; }, /** * Indicates whether track moouse wheel rotation over element. * * @param value Track wheel? */ set: function (value) { if (this._wheelable !== value) { this._wheelable = value; getInteraction().processWheelable(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "inert", { /** * @return Inert? */ get: function () { return this._inert; }, /** * Indicates if element is inert, i.e. if it should carry movement momentum * after it is dragged and released. * * @param value Inert? */ set: function (value) { if (this._inert !== value) { this._inert = value; } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "focusable", { /** * @return Focusable? */ get: function () { return this._focusable; }, /** * Indicates if element can gain focus. * * @param value Focusable? */ set: function (value) { if (this._focusable !== value) { this._focusable = value; if (this._focusable && this.tabindex == -1) { this._tabindex = 1; } getInteraction().processFocusable(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "tabindex", { /** * @return Tab index */ get: function () { return $type.getValueDefault(this._tabindex, -1); }, /** * Element's tab index. * * @param value Tab index */ set: function (value) { if (this._tabindex !== value) { this._tabindex = value; if (value > -1) { this.focusable = true; } getInteraction().processFocusable(this); } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "element", { /** * @return Element */ get: function () { return this._element; }, /** * A DOM element associated with this element. * * @param element Element */ set: function (element) { this._element = element; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "originalPosition", { /** * @ignore Exclude from docs * @return Position. */ get: function () { return this._originalPosition || { x: 0, y: 0 }; }, /** * Element's original position. * * @ignore Exclude from docs * @param value Position */ set: function (value) { this._originalPosition = value; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "originalScale", { /** * @return Scale */ get: function () { return $type.getValueDefault(this._originalScale, 1); }, /** * Element's original scale. * * @ignore Exclude from docs * @param value Scale */ set: function (value) { if (this._originalScale !== value) { this._originalScale = value; } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "originalAngle", { /** * @return Angle */ get: function () { return $type.getValueDefault(this._originalAngle, 0); }, /** * Element's original angle. * * @ignore Exclude from docs * @param value Angle */ set: function (value) { if (this._originalAngle !== value) { this._originalAngle = value; } }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "inertiaOptions", { /** * @return Options */ get: function () { if (this.sprite && this.sprite._adapterO) { return this.sprite._adapterO.apply("inertiaOptions", this._inertiaOptions); } else { return this._inertiaOptions; } }, /** * Inertia options. * * @param value Options */ set: function (value) { this._inertiaOptions = value; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "hitOptions", { /** * @return Options */ get: function () { if (this.sprite && this.sprite._adapterO) { return this.sprite._adapterO.apply("hitOptions", this._hitOptions); } else { return this._hitOptions; } }, /** * Hit options. * * @param value Options */ set: function (value) { this._hitOptions = value; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "hoverOptions", { /** * @return Options */ get: function () { if (this.sprite && this.sprite._adapterO) { return this.sprite._adapterO.apply("hoverOptions", this._hoverOptions); } else { return this._hoverOptions; } }, /** * Hover options. * * @param value Options */ set: function (value) { this._hoverOptions = value; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "swipeOptions", { /** * @return Options */ get: function () { if (this.sprite && this.sprite._adapterO) { return this.sprite._adapterO.apply("swipeOptions", this._swipeOptions); } else { return this._swipeOptions; } }, /** * Swipe options. * * @param value Options */ set: function (value) { this._swipeOptions = value; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "keyboardOptions", { /** * @return Options */ get: function () { if (this.sprite && this.sprite._adapterO) { return this.sprite._adapterO.apply("keyboardOptions", this._keyboardOptions); } else { return this._keyboardOptions; } }, /** * Keyboard options. * * @param value Options */ set: function (value) { this._keyboardOptions = value; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "mouseOptions", { /** * @return Options */ get: function () { if (this.sprite && this.sprite._adapterO) { return this.sprite._adapterO.apply("mouseOptions", this._mouseOptions); } else { return this._mouseOptions; } }, /** * Mouse options. * * Enables controlling options related to the mouse, for example sensitivity * of its mouse wheel. * * E.g. the below will reduce chart's wheel-zoom speed to half its default * speed: * * ```TypeScript * chart.plotContainer.mouseOptions.sensitivity = 0.5; * ``` * ```JavaScript * chart.plotContainer.mouseOptions.sensitivity = 0.5; * ``` * ```JSON * { * // ... * "plotContainer": { * "mouseOptions": { * "sensitivity": 0.5 * } * } * } * ``` * * @since 4.5.14 * @param value Options */ set: function (value) { this._mouseOptions = value; }, enumerable: true, configurable: true }); Object.defineProperty(InteractionObject.prototype, "cursorOptions", { /** * @return Options */ get: function () { if (this.sprite && this.sprite._adapterO) { return this.sprite._adapterO.apply("cursorOptions", this._cursorOptions); } else { return this._cursorOptions; } }, /** * Cursor options. * * @param value Options */ set: function (value) { this._cursorOptions = value; }, enumerable: true, configurable: true }); /** * Copies all properties and related assets from another object of the same * type. * * @param source Source object */ InteractionObject.prototype.copyFrom = function (source) { _super.prototype.copyFrom.call(this, source); this.inertiaOptions = source.inertiaOptions; this.hitOptions = source.hitOptions; this.hoverOptions = source.hoverOptions; this.swipeOptions = source.swipeOptions; this.keyboardOptions = source.keyboardOptions; this.cursorOptions = source.cursorOptions; this.contextMenuDisabled = source.contextMenuDisabled; getInteraction().applyCursorOverStyle(this); }; /** * @ignore Exclude from docs */ InteractionObject.prototype.setEventDisposer = function (key, value, f) { var disposer = this.eventDisposers.getKey(key); if (value) { if (disposer == null) { this.eventDisposers.setKey(key, f()); } } else { if (disposer != null) { disposer.dispose(); this.eventDisposers.removeKey(key); } } }; /** * Disposes object. */ InteractionObject.prototype.dispose = function () { _super.prototype.dispose.call(this); // Remove from all interaction registries var interaction = getInteraction(); interaction.overObjects.removeValue(this); interaction.downObjects.removeValue(this); interaction.trackedObjects.removeValue(this); interaction.transformedObjects.removeValue(this); // Unlock document wheel if (this.isHover && this.wheelable) { interaction.unlockWheel(); } if (interaction.focusedObject === this) { interaction.focusedObject = undefined; } }; return InteractionObject; }(BaseObjectEvents)); export { InteractionObject }; //# sourceMappingURL=InteractionObject.js.map
assets/jsautocomplete/js/jquery-1.5.2.min.js
taoann/kopsyar
/*! * 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);
app/javascript/mastodon/components/status_list.js
ambition-vietnam/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import StatusContainer from '../containers/status_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ScrollableList from './scrollable_list'; import { FormattedMessage } from 'react-intl'; export default class StatusList extends ImmutablePureComponent { static propTypes = { scrollKey: PropTypes.string.isRequired, statusIds: ImmutablePropTypes.list.isRequired, featuredStatusIds: ImmutablePropTypes.list, onLoadMore: PropTypes.func, onScrollToTop: PropTypes.func, onScroll: PropTypes.func, trackScroll: PropTypes.bool, shouldUpdateScroll: PropTypes.func, isLoading: PropTypes.bool, isPartial: PropTypes.bool, hasMore: PropTypes.bool, prepend: PropTypes.node, emptyMessage: PropTypes.node, }; static defaultProps = { trackScroll: true, }; handleMoveUp = id => { const elementIndex = this.props.statusIds.indexOf(id) - 1; this._selectChild(elementIndex); } handleMoveDown = id => { const elementIndex = this.props.statusIds.indexOf(id) + 1; this._selectChild(elementIndex); } _selectChild (index) { const element = this.node.node.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { element.focus(); } } setRef = c => { this.node = c; } render () { const { statusIds, featuredStatusIds, ...other } = this.props; const { isLoading, isPartial } = other; if (isPartial) { return ( <div className='regeneration-indicator'> <div> <div className='regeneration-indicator__figure' /> <div className='regeneration-indicator__label'> <FormattedMessage id='regeneration_indicator.label' tagName='strong' defaultMessage='Loading&hellip;' /> <FormattedMessage id='regeneration_indicator.sublabel' defaultMessage='Your home feed is being prepared!' /> </div> </div> </div> ); } let scrollableContent = (isLoading || statusIds.size > 0) ? ( statusIds.map(statusId => ( <StatusContainer key={statusId} id={statusId} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} /> )) ) : null; if (scrollableContent && featuredStatusIds) { scrollableContent = featuredStatusIds.map(statusId => ( <StatusContainer key={`f-${statusId}`} id={statusId} featured onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} /> )).concat(scrollableContent); } return ( <ScrollableList {...other} ref={this.setRef}> {scrollableContent} </ScrollableList> ); } }
packages/retabulate-react/src/components/Axis.js
jasonphillips/retabulate
import React from 'react'; import gatherChildConfig from '../utils/gatherChildConfig'; import makeRenderers from '../utils/makeRenderers'; class Axis extends React.Component { static serialize(props, index, context) { const {position, children} = props; const descendents = gatherChildConfig(children, context); return { queryFragment: `${position} { ${descendents.query.toString()} }`, renderers: descendents.renderers, labels: descendents.labels, } } render() { return <span />; } } export default Axis;
client/index.js
liors/wix-chat
import './main.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import App from './components/App'; import startChat, { chatMiddleware } from './chat'; import reducers from './reducers'; const initialState = { userId: '1', currentMessage: '', messages: [] }; const createStoreWithMiddleware = applyMiddleware(chatMiddleware)(createStore); const store = createStoreWithMiddleware(reducers(initialState)); startChat(store); ReactDOM.render( <Provider store={store}> <App /> </Provider> , document.getElementById('app'));
docs/Stats.js
jxnblk/cxs
import React from 'react' import cxs from 'cxs' import { format } from 'bytes' import Pre from './Pre' class Stats extends React.Component { render () { const css = cxs.css() return ( <Pre f={0} wrap title={css}> cxs generated {format(css.length)} of CSS to render this page. </Pre> ) } } export default Stats
app/containers/FeaturePage/index.js
huahuaxiong/console
/* * FeaturePage * * List all the features */ import React from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import Helmet from 'react-helmet'; import messages from './messages'; import { FormattedMessage } from 'react-intl'; import Button from 'components/Button'; import H1 from 'components/H1'; import styles from './styles.css'; export class FeaturePage extends React.Component { openHomePage = () => { this.props.dispatch(push('/')); }; render() { return ( <div> <Helmet title="Feature Page" meta={[ { name: 'description', content: 'Feature page of React.js Boilerplate application' }, ]} /> <H1> <FormattedMessage {...messages.header} /> </H1> <ul className={styles.list}> <li className={styles.listItem}> <p className={styles.listItemTitle}> <FormattedMessage {...messages.scaffoldingHeader} /> </p> <p> <FormattedMessage {...messages.scaffoldingMessage} /> </p> </li> <li className={styles.listItem}> <p className={styles.listItemTitle}> <FormattedMessage {...messages.feedbackHeader} /> </p> <p> <FormattedMessage {...messages.feedbackMessage} /> </p> </li> <li className={styles.listItem}> <p className={styles.listItemTitle}> <FormattedMessage {...messages.routingHeader} /> </p> <p> <FormattedMessage {...messages.routingMessage} /> </p> </li> <li className={styles.listItem}> <p className={styles.listItemTitle}> <FormattedMessage {...messages.networkHeader} /> </p> <p> <FormattedMessage {...messages.networkMessage} /> </p> </li> <li className={styles.listItem}> <p className={styles.listItemTitle}> <FormattedMessage {...messages.intlHeader} /> </p> <p> <FormattedMessage {...messages.intlMessage} /> </p> </li> </ul> <Button handleRoute={this.openHomePage}> <FormattedMessage {...messages.homeButton} /> </Button> </div> ); } } FeaturePage.propTypes = { dispatch: React.PropTypes.func, }; export default connect()(FeaturePage);
src/components/ui.js
tonyxiao/segment-debugger
import React from 'react' import CSSModules from 'react-css-modules' import styles from 'styles/shared.scss' export const JsonBlock = ({json}) => { if (!json) { return null } const prettyJsonString = JSON.stringify(json, null, 4) return ( <pre>Response: {prettyJsonString}</pre> ) }
src/examples/example-toolbox-fixed/example-toolbox-fixed.js
smollweide/react-speed-dial
import React from 'react'; import PropTypes from 'prop-types'; import { blue500, white } from 'material-ui/styles/colors'; import IconShare from 'material-ui/svg-icons/social/share'; import IconMail from 'material-ui/svg-icons/communication/email'; import IconCopy from 'material-ui/svg-icons/content/content-copy'; import IconAccount from 'material-ui/svg-icons/action/account-circle'; import IconUploadCloud from 'material-ui/svg-icons/file/cloud-upload'; import { BottomNavigation, BottomNavigationItem } from 'material-ui/BottomNavigation'; import { SpeedDial } from '../../speed-dial'; import ExampleContent from '../example-content/example-content'; const list = { items: [ { icon: <IconUploadCloud color={white} />, }, { icon: <IconAccount color={white} />, }, { icon: <IconCopy color={white} />, }, { icon: <IconMail color={white} />, }, ], }; const Toolbox = ({ onClickCloseToolbox }) => ( <div style={{ position: 'relative' }}> <BottomNavigation style={{ background: blue500 }}> {[] .concat(list.items) .reverse() .map((item, index) => { return <BottomNavigationItem key={index} onClick={onClickCloseToolbox} {...item} />; })} </BottomNavigation> </div> ); Toolbox.propTypes = { onClickCloseToolbox: PropTypes.func, }; const ExampleToolbox = () => { return ( <section style={{ maxWidth: 1024, margin: '0 auto' }}> <ExampleContent /> <SpeedDial closeOnScrollDown closeOnScrollUp floatingActionButtonProps={{ backgroundColor: blue500, }} icon={<IconShare />} toolbox={{ className: 'toolbox', height: 56, }} > <Toolbox /> </SpeedDial> </section> ); }; ExampleToolbox.displayName = 'ExampleToolbox'; export default ExampleToolbox;
src/TagsInput.js
ccoloma/react-simple-tags-input
import React from 'react'; function isEmpty(value) { return !value || !value.length; } export default class TagsInput extends React.Component { constructor(props) { super(props); this.state = { currentTag: '', tags: props.tags || [] } this.onChange = this.onChange.bind(this); this.handleKeyPress = this.handleKeyPress.bind(this); this.onRemove = this.onRemove.bind(this); } handleKeyPress(e) { if (e.key == 'Enter') { e.preventDefault(); const tag = this.state.currentTag.trim(); if (!isEmpty(tag)) { const tags = this.state.tags; tags.push(tag); this.setState({ currentTag: '', tags }) this.props.onAdd(tags, tag); } } } onRemove(e) { const { tags } = this.state; const index = e.target.dataset.index; const tag = tags[index]; tags.splice(index, 1); this.setState({ tags: tags }) this.props.onRemove(tags, tag); } onChange(e) { this.setState({ currentTag: e.target.value }) } render() { const { currentTag } = this.state; const { onClick, onAdd, onRemove, className, tags, ...props } = this.props; return ( <div className={`sit-wrapper ${className}`}> <input value={currentTag} type="text" {...props} onChange={this.onChange} onKeyPress={this.handleKeyPress} className="sit-input" /> <div className="sit-tags"> { this.state.tags.map((tag, index) => <span className="sit-tag-wrapper" key={index}> <span className="sit-tag">{tag}</span> <span className="sit-close" data-index={index} onClick={this.onRemove} /> </span> ) } </div> </div> ) } } TagsInput.defaultProps = { onRemove: () => {}, onAdd: () => {} }
ajax/libs/F2/1.3.3/f2.js
Rbeuque74/cdnjs
;(function(exports) { if (exports.F2 && !exports.F2_TESTING_MODE) { return; } /*! JSON.org requires the following notice to accompany json2: Copyright (c) 2002 JSON.org http://json.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. 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. */ /* This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); /*! * jQuery JavaScript Library v1.8.3 * The jQuery Foundation and other contributors require the following notice to accompany jQuery: * * Copyright (c) 2013 jQuery Foundation and other contributors * * http://jquery.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.3", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.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%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, 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( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** 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( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.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( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) return (cache[ key + " " ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem, context ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); j++ ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + groups[i].join(""); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { 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, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( e ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, false, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window ); /*! ========================================================= * bootstrap-modal.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Twitter, Inc. require the following notice to accompany Bootstrap: * * Copyright (c) 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work * except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or 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 ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element .show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function (that) { this.$element .hide() .trigger('hidden') this.backdrop() } , removeBackdrop: function () { this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) : this.removeBackdrop() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); /*! * This file creates $ and jQuery variables within the F2 closure scope */ var $, jQuery = $ = window.jQuery.noConflict(true); /*! * Hij1nx requires the following notice to accompany EventEmitter: * * Copyright (c) 2011 hij1nx * * http://www.twitter.com/hij1nx * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the 'Software'), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ !function(exports, undefined) { var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; var defaultMaxListeners = 10; function init() { this._events = new Object; } function configure(conf) { if (conf) { conf.delimiter && (this.delimiter = conf.delimiter); conf.wildcard && (this.wildcard = conf.wildcard); if (this.wildcard) { this.listenerTree = new Object; } } } function EventEmitter(conf) { this._events = new Object; configure.call(this, conf); } // // Attention, function return type now is array, always ! // It has zero elements if no any matches found and one or more // elements (leafs) if there are matches // function searchListenerTree(handlers, type, tree, i) { if (!tree) { return []; } var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, typeLength = type.length, currentType = type[i], nextType = type[i+1]; if (i === typeLength && tree._listeners) { // // If at the end of the event(s) list and the tree has listeners // invoke those listeners. // if (typeof tree._listeners === 'function') { handlers && handlers.push(tree._listeners); return [tree]; } else { for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { handlers && handlers.push(tree._listeners[leaf]); } return [tree]; } } if ((currentType === '*' || currentType === '**') || tree[currentType]) { // // If the event emitted is '*' at this part // or there is a concrete match at this patch // if (currentType === '*') { for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); } } return listeners; } else if(currentType === '**') { endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); if(endReached && tree._listeners) { // The next element has a _listeners, add it to the handlers. listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); } for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { if(branch === '*' || branch === '**') { if(tree[branch]._listeners && !endReached) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); } listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } else if(branch === nextType) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); } else { // No match on this one, shift into the tree but not in the type array. listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } } } return listeners; } listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); } xTree = tree['*']; if (xTree) { // // If the listener tree will allow any match for this part, // then recursively explore all branches of the tree // searchListenerTree(handlers, type, xTree, i+1); } xxTree = tree['**']; if(xxTree) { if(i < typeLength) { if(xxTree._listeners) { // If we have a listener on a '**', it will catch all, so add its handler. searchListenerTree(handlers, type, xxTree, typeLength); } // Build arrays of matching next branches and others. for(branch in xxTree) { if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { if(branch === nextType) { // We know the next element will match, so jump twice. searchListenerTree(handlers, type, xxTree[branch], i+2); } else if(branch === currentType) { // Current node matches, move into the tree. searchListenerTree(handlers, type, xxTree[branch], i+1); } else { isolatedBranch = {}; isolatedBranch[branch] = xxTree[branch]; searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); } } } } else if(xxTree._listeners) { // We have reached the end and still on a '**' searchListenerTree(handlers, type, xxTree, typeLength); } else if(xxTree['*'] && xxTree['*']._listeners) { searchListenerTree(handlers, type, xxTree['*'], typeLength); } } return listeners; } function growListenerTree(type, listener) { type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); // // Looks for two consecutive '**', if so, don't add the event at all. // for(var i = 0, len = type.length; i+1 < len; i++) { if(type[i] === '**' && type[i+1] === '**') { return; } } var tree = this.listenerTree; var name = type.shift(); while (name) { if (!tree[name]) { tree[name] = new Object; } tree = tree[name]; if (type.length === 0) { if (!tree._listeners) { tree._listeners = listener; } else if(typeof tree._listeners === 'function') { tree._listeners = [tree._listeners, listener]; } else if (isArray(tree._listeners)) { tree._listeners.push(listener); if (!tree._listeners.warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && tree._listeners.length > m) { tree._listeners.warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', tree._listeners.length); console.trace(); } } } return true; } name = type.shift(); } return true; }; // By default EventEmitters will print a warning if more than // 10 listeners are added to it. This is a useful default which // helps finding memory leaks. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.delimiter = '.'; EventEmitter.prototype.setMaxListeners = function(n) { this._events || init.call(this); this._events.maxListeners = n; }; EventEmitter.prototype.event = ''; EventEmitter.prototype.once = function(event, fn) { this.many(event, 1, fn); return this; }; EventEmitter.prototype.many = function(event, ttl, fn) { var self = this; if (typeof fn !== 'function') { throw new Error('many only accepts instances of Function'); } function listener() { if (--ttl === 0) { self.off(event, listener); } fn.apply(this, arguments); }; listener._origin = fn; this.on(event, listener); return self; }; EventEmitter.prototype.emit = function() { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener') { if (!this._events.newListener) { return false; } } // Loop through the *_all* functions and invoke them. if (this._all) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; for (i = 0, l = this._all.length; i < l; i++) { this.event = type; this._all[i].apply(this, args); } } // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._all && !this._events.error && !(this.wildcard && this.listenerTree.error)) { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } } var handler; if(this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; } if (typeof handler === 'function') { this.event = type; if (arguments.length === 1) { handler.call(this); } else if (arguments.length > 1) switch (arguments.length) { case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } return true; } else if (handler) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { this.event = type; listeners[i].apply(this, args); } return (listeners.length > 0) || this._all; } else { return this._all; } }; EventEmitter.prototype.on = function(type, listener) { if (typeof type === 'function') { this.onAny(type); return this; } if (typeof listener !== 'function') { throw new Error('on only accepts instances of Function'); } this._events || init.call(this); // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". this.emit('newListener', type, listener); if(this.wildcard) { growListenerTree.call(this, type, listener); return this; } if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else if(typeof this._events[type] === 'function') { // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; } else if (isArray(this._events[type])) { // If we've already got an array, just append. this._events[type].push(listener); // Check for listener leak if (!this._events[type].warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } } return this; }; EventEmitter.prototype.onAny = function(fn) { if(!this._all) { this._all = []; } if (typeof fn !== 'function') { throw new Error('onAny only accepts instances of Function'); } // Add the function to the event listener collection. this._all.push(fn); return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prototype.off = function(type, listener) { if (typeof listener !== 'function') { throw new Error('removeListener only takes instances of Function'); } var handlers,leafs=[]; if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); } else { // does not use listeners(), so no side effect of creating _events[type] if (!this._events[type]) return this; handlers = this._events[type]; leafs.push({_listeners:handlers}); } for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; handlers = leaf._listeners; if (isArray(handlers)) { var position = -1; for (var i = 0, length = handlers.length; i < length; i++) { if (handlers[i] === listener || (handlers[i].listener && handlers[i].listener === listener) || (handlers[i]._origin && handlers[i]._origin === listener)) { position = i; break; } } if (position < 0) { return this; } if(this.wildcard) { leaf._listeners.splice(position, 1) } else { this._events[type].splice(position, 1); } if (handlers.length === 0) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } else if (handlers === listener || (handlers.listener && handlers.listener === listener) || (handlers._origin && handlers._origin === listener)) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } return this; }; EventEmitter.prototype.offAny = function(fn) { var i = 0, l = 0, fns; if (fn && this._all && this._all.length > 0) { fns = this._all; for(i = 0, l = fns.length; i < l; i++) { if(fn === fns[i]) { fns.splice(i, 1); return this; } } } else { this._all = []; } return this; }; EventEmitter.prototype.removeListener = EventEmitter.prototype.off; EventEmitter.prototype.removeAllListeners = function(type) { if (arguments.length === 0) { !this._events || init.call(this); return this; } if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; leaf._listeners = null; } } else { if (!this._events[type]) return this; this._events[type] = null; } return this; }; EventEmitter.prototype.listeners = function(type) { if(this.wildcard) { var handlers = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); return handlers; } this._events || init.call(this); if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; }; EventEmitter.prototype.listenersAny = function() { if(this._all) { return this._all; } else { return []; } }; // if (typeof define === 'function' && define.amd) { // define('EventEmitter2', [], function() { // return EventEmitter; // }); // } else { exports.EventEmitter2 = EventEmitter; // } }(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window); /*! * Øyvind Sean Kinsey and others require the following notice to accompany easyXDM: * * http://easyxdm.net/ * Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) { /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */ var global = this; var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded var emptyFn = Function.prototype; var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4) var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global) var easyXDM = {}; var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite var IFRAME_PREFIX = "easyXDM_"; var HAS_NAME_PROPERTY_BUG; var useHash = false; // whether to use the hash over the query var flashVersion; // will be set if using flash var HAS_FLASH_THROTTLED_BUG; // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting function isHostMethod(object, property){ var t = typeof object[property]; return t == 'function' || (!!(t == 'object' && object[property])) || t == 'unknown'; } function isHostObject(object, property){ return !!(typeof(object[property]) == 'object' && object[property]); } // end // http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ function isArray(o){ return Object.prototype.toString.call(o) === '[object Array]'; } // end function hasFlash(){ try { var activeX = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); flashVersion = Array.prototype.slice.call(activeX.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1); HAS_FLASH_THROTTLED_BUG = parseInt(flashVersion[0], 10) > 9 && parseInt(flashVersion[1], 10) > 0; activeX = null; return true; } catch (notSupportedException) { return false; } } /* * Cross Browser implementation for adding and removing event listeners. */ var on, un; if (isHostMethod(window, "addEventListener")) { on = function(target, type, listener){ target.addEventListener(type, listener, false); }; un = function(target, type, listener){ target.removeEventListener(type, listener, false); }; } else if (isHostMethod(window, "attachEvent")) { on = function(object, sEvent, fpNotify){ object.attachEvent("on" + sEvent, fpNotify); }; un = function(object, sEvent, fpNotify){ object.detachEvent("on" + sEvent, fpNotify); }; } else { throw new Error("Browser not supported"); } /* * Cross Browser implementation of DOMContentLoaded. */ var domIsReady = false, domReadyQueue = [], readyState; if ("readyState" in document) { // If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and // 'interactive' (HTML5 specs, recent WebKit builds) states. // https://bugs.webkit.org/show_bug.cgi?id=45119 readyState = document.readyState; domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive")); } else { // If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately // when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not. // We only need a body to add elements to, so the existence of document.body is enough for us. domIsReady = !!document.body; } function dom_onReady(){ if (domIsReady) { return; } domIsReady = true; for (var i = 0; i < domReadyQueue.length; i++) { domReadyQueue[i](); } domReadyQueue.length = 0; } if (!domIsReady) { if (isHostMethod(window, "addEventListener")) { on(document, "DOMContentLoaded", dom_onReady); } else { on(document, "readystatechange", function(){ if (document.readyState == "complete") { dom_onReady(); } }); if (document.documentElement.doScroll && window === top) { var doScrollCheck = function(){ if (domIsReady) { return; } // http://javascript.nwbox.com/IEContentLoaded/ try { document.documentElement.doScroll("left"); } catch (e) { setTimeout(doScrollCheck, 1); return; } dom_onReady(); }; doScrollCheck(); } } // A fallback to window.onload, that will always work on(window, "load", dom_onReady); } /** * This will add a function to the queue of functions to be run once the DOM reaches a ready state. * If functions are added after this event then they will be executed immediately. * @param {function} fn The function to add * @param {Object} scope An optional scope for the function to be called with. */ function whenReady(fn, scope){ if (domIsReady) { fn.call(scope); return; } domReadyQueue.push(function(){ fn.call(scope); }); } /** * Returns an instance of easyXDM from the parent window with * respect to the namespace. * * @return An instance of easyXDM (in the parent window) */ function getParentObject(){ var obj = parent; if (namespace !== "") { for (var i = 0, ii = namespace.split("."); i < ii.length; i++) { obj = obj[ii[i]]; } } return obj.easyXDM; } /** * Removes easyXDM variable from the global scope. It also returns control * of the easyXDM variable to whatever code used it before. * * @param {String} ns A string representation of an object that will hold * an instance of easyXDM. * @return An instance of easyXDM */ function noConflict(ns){ window.easyXDM = _easyXDM; namespace = ns; if (namespace) { IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_"; } return easyXDM; } /* * Methods for working with URLs */ /** * Get the domain name from a url. * @param {String} url The url to extract the domain from. * @return The domain part of the url. * @type {String} */ function getDomainName(url){ return url.match(reURI)[3]; } /** * Get the port for a given URL, or "" if none * @param {String} url The url to extract the port from. * @return The port part of the url. * @type {String} */ function getPort(url){ return url.match(reURI)[4] || ""; } /** * Returns a string containing the schema, domain and if present the port * @param {String} url The url to extract the location from * @return {String} The location part of the url */ function getLocation(url){ var m = url.toLowerCase().match(reURI); var proto = m[2], domain = m[3], port = m[4] || ""; if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) { port = ""; } return proto + "//" + domain + port; } /** * Resolves a relative url into an absolute one. * @param {String} url The path to resolve. * @return {String} The resolved url. */ function resolveUrl(url){ // replace all // except the one in proto with / url = url.replace(reDoubleSlash, "$1/"); // If the url is a valid url we do nothing if (!url.match(/^(http||https):\/\//)) { // If this is a relative path var path = (url.substring(0, 1) === "/") ? "" : location.pathname; if (path.substring(path.length - 1) !== "/") { path = path.substring(0, path.lastIndexOf("/") + 1); } url = location.protocol + "//" + location.host + path + url; } // reduce all 'xyz/../' to just '' while (reParent.test(url)) { url = url.replace(reParent, ""); } return url; } /** * Appends the parameters to the given url.<br/> * The base url can contain existing query parameters. * @param {String} url The base url. * @param {Object} parameters The parameters to add. * @return {String} A new valid url with the parameters appended. */ function appendQueryParameters(url, parameters){ var hash = "", indexOf = url.indexOf("#"); if (indexOf !== -1) { hash = url.substring(indexOf); url = url.substring(0, indexOf); } var q = []; for (var key in parameters) { if (parameters.hasOwnProperty(key)) { q.push(key + "=" + encodeURIComponent(parameters[key])); } } return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash; } // build the query object either from location.query, if it contains the xdm_e argument, or from location.hash var query = (function(input){ input = input.substring(1).split("&"); var data = {}, pair, i = input.length; while (i--) { pair = input[i].split("="); data[pair[0]] = decodeURIComponent(pair[1]); } return data; }(/xdm_e=/.test(location.search) ? location.search : location.hash)); /* * Helper methods */ /** * Helper for checking if a variable/property is undefined * @param {Object} v The variable to test * @return {Boolean} True if the passed variable is undefined */ function undef(v){ return typeof v === "undefined"; } /** * A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works. * @return {JSON} A valid JSON conforming object, or null if not found. */ var getJSON = function(){ var cached = {}; var obj = { a: [1, 2, 3] }, json = "{\"a\":[1,2,3]}"; if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) { // this is a working JSON instance return JSON; } if (Object.toJSON) { if (Object.toJSON(obj).replace((/\s/g), "") === json) { // this is a working stringify method cached.stringify = Object.toJSON; } } if (typeof String.prototype.evalJSON === "function") { obj = json.evalJSON(); if (obj.a && obj.a.length === 3 && obj.a[2] === 3) { // this is a working parse method cached.parse = function(str){ return str.evalJSON(); }; } } if (cached.stringify && cached.parse) { // Only memoize the result if we have valid instance getJSON = function(){ return cached; }; return cached; } return null; }; /** * Applies properties from the source object to the target object.<br/> * @param {Object} target The target of the properties. * @param {Object} source The source of the properties. * @param {Boolean} noOverwrite Set to True to only set non-existing properties. */ function apply(destination, source, noOverwrite){ var member; for (var prop in source) { if (source.hasOwnProperty(prop)) { if (prop in destination) { member = source[prop]; if (typeof member === "object") { apply(destination[prop], member, noOverwrite); } else if (!noOverwrite) { destination[prop] = source[prop]; } } else { destination[prop] = source[prop]; } } } return destination; } // This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName]. function testForNamePropertyBug(){ var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input")); input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name]; document.body.removeChild(form); } /** * Creates a frame and appends it to the DOM. * @param config {object} This object can have the following properties * <ul> * <li> {object} prop The properties that should be set on the frame. This should include the 'src' property.</li> * <li> {object} attr The attributes that should be set on the frame.</li> * <li> {DOMElement} container Its parent element (Optional).</li> * <li> {function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)</li> * </ul> * @return The frames DOMElement * @type DOMElement */ function createFrame(config){ if (undef(HAS_NAME_PROPERTY_BUG)) { testForNamePropertyBug(); } var frame; // This is to work around the problems in IE6/7 with setting the name property. // Internally this is set as 'submitName' instead when using 'iframe.name = ...' // This is not required by easyXDM itself, but is to facilitate other use cases if (HAS_NAME_PROPERTY_BUG) { frame = document.createElement("<iframe name=\"" + config.props.name + "\"/>"); } else { frame = document.createElement("IFRAME"); frame.name = config.props.name; } frame.id = frame.name = config.props.name; delete config.props.name; if (config.onLoad) { on(frame, "load", config.onLoad); } if (typeof config.container == "string") { config.container = document.getElementById(config.container); } if (!config.container) { // This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers. apply(frame.style, { position: "absolute", top: "-2000px" }); config.container = document.body; } // HACK for some reason, IE needs the source set // after the frame has been appended into the DOM // so remove the src, and set it afterwards var src = config.props.src; delete config.props.src; // transfer properties to the frame apply(frame, config.props); frame.border = frame.frameBorder = 0; frame.allowTransparency = true; config.container.appendChild(frame); // HACK see above frame.src = src; config.props.src = src; return frame; } /** * Check whether a domain is allowed using an Access Control List. * The ACL can contain * and ? as wildcards, or can be regular expressions. * If regular expressions they need to begin with ^ and end with $. * @param {Array/String} acl The list of allowed domains * @param {String} domain The domain to test. * @return {Boolean} True if the domain is allowed, false if not. */ function checkAcl(acl, domain){ // normalize into an array if (typeof acl == "string") { acl = [acl]; } var re, i = acl.length; while (i--) { re = acl[i]; re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$")); if (re.test(domain)) { return true; } } return false; } /* * Functions related to stacks */ /** * Prepares an array of stack-elements suitable for the current configuration * @param {Object} config The Transports configuration. See easyXDM.Socket for more. * @return {Array} An array of stack-elements with the TransportElement at index 0. */ function prepareTransportStack(config){ var protocol = config.protocol, stackEls; config.isHost = config.isHost || undef(query.xdm_p); useHash = config.hash || false; if (!config.props) { config.props = {}; } if (!config.isHost) { config.channel = query.xdm_c; config.secret = query.xdm_s; config.remote = query.xdm_e; protocol = query.xdm_p; if (config.acl && !checkAcl(config.acl, config.remote)) { throw new Error("Access denied for " + config.remote); } } else { config.remote = resolveUrl(config.remote); config.channel = config.channel || "default" + channelId++; config.secret = Math.random().toString(16).substring(2); if (undef(protocol)) { if (getLocation(location.href) == getLocation(config.remote)) { /* * Both documents has the same origin, lets use direct access. */ protocol = "4"; } else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) { /* * This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+ */ protocol = "1"; } else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) { /* * The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS */ protocol = "6"; } else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) { /* * This is supported in Gecko (Firefox 1+) */ protocol = "5"; } else if (config.remoteHelper) { /* * This is supported in all browsers that retains the value of window.name when * navigating from one domain to another, and where parent.frames[foo] can be used * to get access to a frame from the same domain */ config.remoteHelper = resolveUrl(config.remoteHelper); protocol = "2"; } else { /* * This is supported in all browsers where [window].location is writable for all * The resize event will be used if resize is supported and the iframe is not put * into a container, else polling will be used. */ protocol = "0"; } } } config.protocol = protocol; // for conditional branching switch (protocol) { case "0":// 0 = HashTransport apply(config, { interval: 100, delay: 2000, useResize: true, useParent: false, usePolling: false }, true); if (config.isHost) { if (!config.local) { // If no local is set then we need to find an image hosted on the current domain var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image; var i = images.length; while (i--) { image = images[i]; if (image.src.substring(0, domain.length) === domain) { config.local = image.src; break; } } if (!config.local) { // If no local was set, and we are unable to find a suitable file, then we resort to using the current window config.local = window; } } var parameters = { xdm_c: config.channel, xdm_p: 0 }; if (config.local === window) { // We are using the current window to listen to config.usePolling = true; config.useParent = true; config.local = location.protocol + "//" + location.host + location.pathname + location.search; parameters.xdm_e = config.local; parameters.xdm_pa = 1; // use parent } else { parameters.xdm_e = resolveUrl(config.local); } if (config.container) { config.useResize = false; parameters.xdm_po = 1; // use polling } config.remote = appendQueryParameters(config.remote, parameters); } else { apply(config, { channel: query.xdm_c, remote: query.xdm_e, useParent: !undef(query.xdm_pa), usePolling: !undef(query.xdm_po), useResize: config.useParent ? false : config.useResize }); } stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({ encode: true, maxLength: 4000 - config.remote.length }), new easyXDM.stack.VerifyBehavior({ initiate: config.isHost })]; break; case "1": stackEls = [new easyXDM.stack.PostMessageTransport(config)]; break; case "2": stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({ initiate: config.isHost })]; break; case "3": stackEls = [new easyXDM.stack.NixTransport(config)]; break; case "4": stackEls = [new easyXDM.stack.SameOriginTransport(config)]; break; case "5": stackEls = [new easyXDM.stack.FrameElementTransport(config)]; break; case "6": if (!flashVersion) { hasFlash(); } stackEls = [new easyXDM.stack.FlashTransport(config)]; break; } // this behavior is responsible for buffering outgoing messages, and for performing lazy initialization stackEls.push(new easyXDM.stack.QueueBehavior({ lazy: config.lazy, remove: true })); return stackEls; } /** * Chains all the separate stack elements into a single usable stack.<br/> * If an element is missing a necessary method then it will have a pass-through method applied. * @param {Array} stackElements An array of stack elements to be linked. * @return {easyXDM.stack.StackElement} The last element in the chain. */ function chainStack(stackElements){ var stackEl, defaults = { incoming: function(message, origin){ this.up.incoming(message, origin); }, outgoing: function(message, recipient){ this.down.outgoing(message, recipient); }, callback: function(success){ this.up.callback(success); }, init: function(){ this.down.init(); }, destroy: function(){ this.down.destroy(); } }; for (var i = 0, len = stackElements.length; i < len; i++) { stackEl = stackElements[i]; apply(stackEl, defaults, true); if (i !== 0) { stackEl.down = stackElements[i - 1]; } if (i !== len - 1) { stackEl.up = stackElements[i + 1]; } } return stackEl; } /** * This will remove a stackelement from its stack while leaving the stack functional. * @param {Object} element The elment to remove from the stack. */ function removeFromStack(element){ element.up.down = element.down; element.down.up = element.up; element.up = element.down = null; } /* * Export the main object and any other methods applicable */ /** * @class easyXDM * A javascript library providing cross-browser, cross-domain messaging/RPC. * @version 2.4.15.118 * @singleton */ apply(easyXDM, { /** * The version of the library * @type {string} */ version: "2.4.15.118", /** * This is a map containing all the query parameters passed to the document. * All the values has been decoded using decodeURIComponent. * @type {object} */ query: query, /** * @private */ stack: {}, /** * Applies properties from the source object to the target object.<br/> * @param {object} target The target of the properties. * @param {object} source The source of the properties. * @param {boolean} noOverwrite Set to True to only set non-existing properties. */ apply: apply, /** * A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works. * @return {JSON} A valid JSON conforming object, or null if not found. */ getJSONObject: getJSON, /** * This will add a function to the queue of functions to be run once the DOM reaches a ready state. * If functions are added after this event then they will be executed immediately. * @param {function} fn The function to add * @param {object} scope An optional scope for the function to be called with. */ whenReady: whenReady, /** * Removes easyXDM variable from the global scope. It also returns control * of the easyXDM variable to whatever code used it before. * * @param {String} ns A string representation of an object that will hold * an instance of easyXDM. * @return An instance of easyXDM */ noConflict: noConflict }); /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.DomHelper * Contains methods for dealing with the DOM * @singleton */ easyXDM.DomHelper = { /** * Provides a consistent interface for adding eventhandlers * @param {Object} target The target to add the event to * @param {String} type The name of the event * @param {Function} listener The listener */ on: on, /** * Provides a consistent interface for removing eventhandlers * @param {Object} target The target to remove the event from * @param {String} type The name of the event * @param {Function} listener The listener */ un: un, /** * Checks for the presence of the JSON object. * If it is not present it will use the supplied path to load the JSON2 library. * This should be called in the documents head right after the easyXDM script tag. * http://json.org/json2.js * @param {String} path A valid path to json2.js */ requiresJSON: function(path){ if (!isHostObject(window, "JSON")) { // we need to encode the < in order to avoid an illegal token error // when the script is inlined in a document. document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>'); } } }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // (function(){ // The map containing the stored functions var _map = {}; /** * @class easyXDM.Fn * This contains methods related to function handling, such as storing callbacks. * @singleton * @namespace easyXDM */ easyXDM.Fn = { /** * Stores a function using the given name for reference * @param {String} name The name that the function should be referred by * @param {Function} fn The function to store * @namespace easyXDM.fn */ set: function(name, fn){ _map[name] = fn; }, /** * Retrieves the function referred to by the given name * @param {String} name The name of the function to retrieve * @param {Boolean} del If the function should be deleted after retrieval * @return {Function} The stored function * @namespace easyXDM.fn */ get: function(name, del){ var fn = _map[name]; if (del) { delete _map[name]; } return fn; } }; }()); /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.Socket * This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.<br/> * The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.<br/> * Internally different stacks will be used depending on the browsers features and the available parameters. * <h2>How to set up</h2> * Setting up the provider: * <pre><code> * var socket = new easyXDM.Socket({ * &nbsp; local: "name.html", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the socket * &nbsp; &nbsp; socket.postMessage("foo-message"); * &nbsp; }, * &nbsp; onMessage: function(message, origin) { * &nbsp;&nbsp; alert("received " + message + " from " + origin); * &nbsp; } * }); * </code></pre> * Setting up the consumer: * <pre><code> * var socket = new easyXDM.Socket({ * &nbsp; remote: "http:&#47;&#47;remotedomain/page.html", * &nbsp; remoteHelper: "http:&#47;&#47;remotedomain/name.html", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the socket * &nbsp; &nbsp; socket.postMessage("foo-message"); * &nbsp; }, * &nbsp; onMessage: function(message, origin) { * &nbsp;&nbsp; alert("received " + message + " from " + origin); * &nbsp; } * }); * </code></pre> * If you are unable to upload the <code>name.html</code> file to the consumers domain then remove the <code>remoteHelper</code> property * and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports. * @namespace easyXDM * @constructor * @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window. * @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed. * @cfg {String} remote (Consumer only) The url to the providers document. * @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional. * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000. * @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300. * @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional. * @cfg {Function} onMessage The method that should handle incoming messages.<br/> This method should accept two arguments, the message as a string, and the origin as a string. Optional. * @cfg {Function} onReady A method that should be called when the transport is ready. Optional. * @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional. * @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.<br/> * This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $. * If none of the patterns match an Error will be thrown. * @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: <code>{style:{width:"100px", height:"100px"}}</code>. * Properties such as 'name' and 'src' will be overrided. Optional. */ easyXDM.Socket = function(config){ // create the stack var stack = chainStack(prepareTransportStack(config).concat([{ incoming: function(message, origin){ config.onMessage(message, origin); }, callback: function(success){ if (config.onReady) { config.onReady(success); } } }])), recipient = getLocation(config.remote); // set the origin this.origin = getLocation(config.remote); /** * Initiates the destruction of the stack. */ this.destroy = function(){ stack.destroy(); }; /** * Posts a message to the remote end of the channel * @param {String} message The message to send */ this.postMessage = function(message){ stack.outgoing(message, recipient); }; stack.init(); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.Rpc * Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation * of methods to be called from the remote end.<br/> * The instantiated object will have methods matching those specified in <code>config.remote</code>.<br/> * This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods. * <h2>How to set up</h2> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; &#47;&#47; this configuration is equal to that used by the Socket. * &nbsp; remote: "http:&#47;&#47;remotedomain/...", * &nbsp; onReady: function(){ * &nbsp; &nbsp; &#47;&#47; you need to wait for the onReady callback before using the proxy * &nbsp; &nbsp; rpc.foo(... * &nbsp; } * },{ * &nbsp; local: {..}, * &nbsp; remote: {..} * }); * </code></pre> * * <h2>Exposing functions (procedures)</h2> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: { * &nbsp; &nbsp; nameOfMethod: { * &nbsp; &nbsp; &nbsp; method: function(arg1, arg2, success, error){ * &nbsp; &nbsp; &nbsp; &nbsp; ... * &nbsp; &nbsp; &nbsp; } * &nbsp; &nbsp; }, * &nbsp; &nbsp; &#47;&#47; with shorthand notation * &nbsp; &nbsp; nameOfAnotherMethod: function(arg1, arg2, success, error){ * &nbsp; &nbsp; } * &nbsp; }, * &nbsp; remote: {...} * }); * </code></pre> * The function referenced by [method] will receive the passed arguments followed by the callback functions <code>success</code> and <code>error</code>.<br/> * To send a successfull result back you can use * <pre><code> * return foo; * </pre></code> * or * <pre><code> * success(foo); * </pre></code> * To return an error you can use * <pre><code> * throw new Error("foo error"); * </code></pre> * or * <pre><code> * error("foo error"); * </code></pre> * * <h2>Defining remotely exposed methods (procedures/notifications)</h2> * The definition of the remote end is quite similar: * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: {...}, * &nbsp; remote: { * &nbsp; &nbsp; nameOfMethod: {} * &nbsp; } * }); * </code></pre> * To call a remote method use * <pre><code> * rpc.nameOfMethod("arg1", "arg2", function(value) { * &nbsp; alert("success: " + value); * }, function(message) { * &nbsp; alert("error: " + message + ); * }); * </code></pre> * Both the <code>success</code> and <code>errror</code> callbacks are optional.<br/> * When called with no callback a JSON-RPC 2.0 notification will be executed. * Be aware that you will not be notified of any errors with this method. * <br/> * <h2>Specifying a custom serializer</h2> * If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library * then you can specify a custom serializer using <code>serializer: foo</code> * <pre><code> * var rpc = new easyXDM.Rpc({ * &nbsp; ... * },{ * &nbsp; local: {...}, * &nbsp; remote: {...}, * &nbsp; serializer : { * &nbsp; &nbsp; parse: function(string){ ... }, * &nbsp; &nbsp; stringify: function(object) {...} * &nbsp; } * }); * </code></pre> * If <code>serializer</code> is set then the class will not attempt to use the native implementation. * @namespace easyXDM * @constructor * @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters. * @param {Object} jsonRpcConfig The description of the interface to implement. */ easyXDM.Rpc = function(config, jsonRpcConfig){ // expand shorthand notation if (jsonRpcConfig.local) { for (var method in jsonRpcConfig.local) { if (jsonRpcConfig.local.hasOwnProperty(method)) { var member = jsonRpcConfig.local[method]; if (typeof member === "function") { jsonRpcConfig.local[method] = { method: member }; } } } } // create the stack var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), { callback: function(success){ if (config.onReady) { config.onReady(success); } } }])); // set the origin this.origin = getLocation(config.remote); /** * Initiates the destruction of the stack. */ this.destroy = function(){ stack.destroy(); }; stack.init(); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.SameOriginTransport * SameOriginTransport is a transport class that can be used when both domains have the same origin.<br/> * This can be useful for testing and for when the main application supports both internal and external sources. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote document to communicate with. */ easyXDM.stack.SameOriginTransport = function(config){ var pub, frame, send, targetOrigin; return (pub = { outgoing: function(message, domain, fn){ send(message); if (fn) { fn(); } }, destroy: function(){ if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: location.protocol + "//" + location.host + location.pathname, xdm_c: config.channel, xdm_p: 4 // 4 = SameOriginTransport }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); easyXDM.Fn.set(config.channel, function(sendFn){ send = sendFn; setTimeout(function(){ pub.up.callback(true); }, 0); return function(msg){ pub.up.incoming(msg, targetOrigin); }; }); } else { send = getParentObject().Fn.get(config.channel, true)(function(msg){ pub.up.incoming(msg, targetOrigin); }); setTimeout(function(){ pub.up.callback(true); }, 0); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.FlashTransport * FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote domain to communicate with. * @cfg {String} secret the pre-shared secret used to secure the communication. * @cfg {String} swf The path to the swf file * @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden. * @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed */ easyXDM.stack.FlashTransport = function(config){ var pub, // the public interface frame, send, targetOrigin, swf, swfContainer; function onMessage(message, origin){ setTimeout(function(){ pub.up.incoming(message, targetOrigin); }, 0); } /** * This method adds the SWF to the DOM and prepares the initialization of the channel */ function addSwf(domain){ // the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error. var url = config.swf + "?host=" + config.isHost; var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000); // prepare the init function that will fire once the swf is ready easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){ easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild; var queue = easyXDM.stack.FlashTransport[domain].queue; for (var i = 0; i < queue.length; i++) { queue[i](); } queue.length = 0; }); if (config.swfContainer) { swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer; } else { // create the container that will hold the swf swfContainer = document.createElement('div'); // http://bugs.adobe.com/jira/browse/FP-4796 // http://tech.groups.yahoo.com/group/flexcoders/message/162365 // https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? { height: "20px", width: "20px", position: "fixed", right: 0, top: 0 } : { height: "1px", width: "1px", position: "absolute", overflow: "hidden", right: 0, top: 0 }); document.body.appendChild(swfContainer); } // create the object/embed var flashVars = "callback=flash_loaded" + domain.replace(/[\-.]/g, "_") + "&proto=" + global.location.protocol + "&domain=" + getDomainName(global.location.href) + "&port=" + getPort(global.location.href) + "&ns=" + namespace; swfContainer.innerHTML = "<object height='20' width='20' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" + "<param name='allowScriptAccess' value='always'></param>" + "<param name='wmode' value='transparent'>" + "<param name='movie' value='" + url + "'></param>" + "<param name='flashvars' value='" + flashVars + "'></param>" + "<embed type='application/x-shockwave-flash' FlashVars='" + flashVars + "' allowScriptAccess='always' wmode='transparent' src='" + url + "' height='1' width='1'></embed>" + "</object>"; } return (pub = { outgoing: function(message, domain, fn){ swf.postMessage(config.channel, message.toString()); if (fn) { fn(); } }, destroy: function(){ try { swf.destroyChannel(config.channel); } catch (e) { } swf = null; if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = config.remote; // Prepare the code that will be run after the swf has been intialized easyXDM.Fn.set("flash_" + config.channel + "_init", function(){ setTimeout(function(){ pub.up.callback(true); }); }); // set up the omMessage handler easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage); config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths var swfdomain = getDomainName(config.swf); var fn = function(){ // set init to true in case the fn was called was invoked from a separate instance easyXDM.stack.FlashTransport[swfdomain].init = true; swf = easyXDM.stack.FlashTransport[swfdomain].swf; // create the channel swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost); if (config.isHost) { // if Flash is going to be throttled and we want to avoid this if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) { apply(config.props, { position: "fixed", right: 0, top: 0, height: "20px", width: "20px" }); } // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 6, // 6 = FlashTransport xdm_s: config.secret }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); } }; if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) { // if the swf is in place and we are the consumer fn(); } else { // if the swf does not yet exist if (!easyXDM.stack.FlashTransport[swfdomain]) { // add the queue to hold the init fn's easyXDM.stack.FlashTransport[swfdomain] = { queue: [fn] }; addSwf(swfdomain); } else { easyXDM.stack.FlashTransport[swfdomain].queue.push(fn); } } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.PostMessageTransport * PostMessageTransport is a transport class that uses HTML5 postMessage for communication.<br/> * <a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx</a><br/> * <a href="https://developer.mozilla.org/en/DOM/window.postMessage">https://developer.mozilla.org/en/DOM/window.postMessage</a> * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote domain to communicate with. */ easyXDM.stack.PostMessageTransport = function(config){ var pub, // the public interface frame, // the remote frame, if any callerWindow, // the window that we will call with targetOrigin; // the domain to communicate with /** * Resolves the origin from the event object * @private * @param {Object} event The messageevent * @return {String} The scheme, host and port of the origin */ function _getOrigin(event){ if (event.origin) { // This is the HTML5 property return getLocation(event.origin); } if (event.uri) { // From earlier implementations return getLocation(event.uri); } if (event.domain) { // This is the last option and will fail if the // origin is not using the same schema as we are return location.protocol + "//" + event.domain; } throw "Unable to retrieve the origin of the event"; } /** * This is the main implementation for the onMessage event.<br/> * It checks the validity of the origin and passes the message on if appropriate. * @private * @param {Object} event The messageevent */ function _window_onMessage(event){ var origin = _getOrigin(event); if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") { pub.up.incoming(event.data.substring(config.channel.length + 1), origin); } } return (pub = { outgoing: function(message, domain, fn){ callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin); if (fn) { fn(); } }, destroy: function(){ un(window, "message", _window_onMessage); if (frame) { callerWindow = null; frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // add the event handler for listening var waitForReady = function(event){ if (event.data == config.channel + "-ready") { // replace the eventlistener callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document; un(window, "message", waitForReady); on(window, "message", _window_onMessage); setTimeout(function(){ pub.up.callback(true); }, 0); } }; on(window, "message", waitForReady); // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 1 // 1 = PostMessage }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); } else { // add the event handler for listening on(window, "message", _window_onMessage); callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document; callerWindow.postMessage(config.channel + "-ready", targetOrigin); setTimeout(function(){ pub.up.callback(true); }, 0); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.FrameElementTransport * FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.<br/> * Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running. * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String} remote The remote document to communicate with. */ easyXDM.stack.FrameElementTransport = function(config){ var pub, frame, send, targetOrigin; return (pub = { outgoing: function(message, domain, fn){ send.call(this, message); if (fn) { fn(); } }, destroy: function(){ if (frame) { frame.parentNode.removeChild(frame); frame = null; } }, onDOMReady: function(){ targetOrigin = getLocation(config.remote); if (config.isHost) { // set up the iframe apply(config.props, { src: appendQueryParameters(config.remote, { xdm_e: getLocation(location.href), xdm_c: config.channel, xdm_p: 5 // 5 = FrameElementTransport }), name: IFRAME_PREFIX + config.channel + "_provider" }); frame = createFrame(config); frame.fn = function(sendFn){ delete frame.fn; send = sendFn; setTimeout(function(){ pub.up.callback(true); }, 0); // remove the function so that it cannot be used to overwrite the send function later on return function(msg){ pub.up.incoming(msg, targetOrigin); }; }; } else { // This is to mitigate origin-spoofing if (document.referrer && getLocation(document.referrer) != query.xdm_e) { window.top.location = query.xdm_e; } send = window.frameElement.fn(function(msg){ pub.up.incoming(msg, targetOrigin); }); pub.up.callback(true); } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.NameTransport * NameTransport uses the window.name property to relay data. * The <code>local</code> parameter needs to be set on both the consumer and provider,<br/> * and the <code>remoteHelper</code> parameter needs to be set on the consumer. * @constructor * @param {Object} config The transports configuration. * @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host. * @namespace easyXDM.stack */ easyXDM.stack.NameTransport = function(config){ var pub; // the public interface var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl; function _sendMessage(message){ var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel; callerWindow.contentWindow.sendMessage(message, url); } function _onReady(){ if (isHost) { if (++readyCount === 2 || !isHost) { pub.up.callback(true); } } else { _sendMessage("ready"); pub.up.callback(true); } } function _onMessage(message){ pub.up.incoming(message, remoteOrigin); } function _onLoad(){ if (callback) { setTimeout(function(){ callback(true); }, 0); } } return (pub = { outgoing: function(message, domain, fn){ callback = fn; _sendMessage(message); }, destroy: function(){ callerWindow.parentNode.removeChild(callerWindow); callerWindow = null; if (isHost) { remoteWindow.parentNode.removeChild(remoteWindow); remoteWindow = null; } }, onDOMReady: function(){ isHost = config.isHost; readyCount = 0; remoteOrigin = getLocation(config.remote); config.local = resolveUrl(config.local); if (isHost) { // Register the callback easyXDM.Fn.set(config.channel, function(message){ if (isHost && message === "ready") { // Replace the handler easyXDM.Fn.set(config.channel, _onMessage); _onReady(); } }); // Set up the frame that points to the remote instance remoteUrl = appendQueryParameters(config.remote, { xdm_e: config.local, xdm_c: config.channel, xdm_p: 2 }); apply(config.props, { src: remoteUrl + '#' + config.channel, name: IFRAME_PREFIX + config.channel + "_provider" }); remoteWindow = createFrame(config); } else { config.remoteHelper = config.remote; easyXDM.Fn.set(config.channel, _onMessage); } // Set up the iframe that will be used for the transport callerWindow = createFrame({ props: { src: config.local + "#_4" + config.channel }, onLoad: function onLoad(){ // Remove the handler var w = callerWindow || this; un(w, "load", onLoad); easyXDM.Fn.set(config.channel + "_load", _onLoad); (function test(){ if (typeof w.contentWindow.sendMessage == "function") { _onReady(); } else { setTimeout(test, 50); } }()); } }); }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.HashTransport * HashTransport is a transport class that uses the IFrame URL Technique for communication.<br/> * <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">http://msdn.microsoft.com/en-us/library/bb735305.aspx</a><br/> * @namespace easyXDM.stack * @constructor * @param {Object} config The transports configuration. * @cfg {String/Window} local The url to the local file used for proxying messages, or the local window. * @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. * @cfg {Number} interval The interval used when polling for messages. */ easyXDM.stack.HashTransport = function(config){ var pub; var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow; var useParent, _remoteOrigin; function _sendMessage(message){ if (!_callerWindow) { return; } var url = config.remote + "#" + (_msgNr++) + "_" + message; ((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url; } function _handleHash(hash){ _lastMsg = hash; pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin); } /** * Checks location.hash for a new message and relays this to the receiver. * @private */ function _pollHash(){ if (!_listenerWindow) { return; } var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#"); if (indexOf != -1) { hash = href.substring(indexOf); } if (hash && hash != _lastMsg) { _handleHash(hash); } } function _attachListeners(){ _timer = setInterval(_pollHash, pollInterval); } return (pub = { outgoing: function(message, domain){ _sendMessage(message); }, destroy: function(){ window.clearInterval(_timer); if (isHost || !useParent) { _callerWindow.parentNode.removeChild(_callerWindow); } _callerWindow = null; }, onDOMReady: function(){ isHost = config.isHost; pollInterval = config.interval; _lastMsg = "#" + config.channel; _msgNr = 0; useParent = config.useParent; _remoteOrigin = getLocation(config.remote); if (isHost) { config.props = { src: config.remote, name: IFRAME_PREFIX + config.channel + "_provider" }; if (useParent) { config.onLoad = function(){ _listenerWindow = window; _attachListeners(); pub.up.callback(true); }; } else { var tries = 0, max = config.delay / 50; (function getRef(){ if (++tries > max) { throw new Error("Unable to reference listenerwindow"); } try { _listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"]; } catch (ex) { } if (_listenerWindow) { _attachListeners(); pub.up.callback(true); } else { setTimeout(getRef, 50); } }()); } _callerWindow = createFrame(config); } else { _listenerWindow = window; _attachListeners(); if (useParent) { _callerWindow = parent; pub.up.callback(true); } else { apply(config, { props: { src: config.remote + "#" + config.channel + new Date(), name: IFRAME_PREFIX + config.channel + "_consumer" }, onLoad: function(){ pub.up.callback(true); } }); _callerWindow = createFrame(config); } } }, init: function(){ whenReady(pub.onDOMReady, pub); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.ReliableBehavior * This is a behavior that tries to make the underlying transport reliable by using acknowledgements. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. */ easyXDM.stack.ReliableBehavior = function(config){ var pub, // the public interface callback; // the callback to execute when we have a confirmed success/failure var idOut = 0, idIn = 0, currentMessage = ""; return (pub = { incoming: function(message, origin){ var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(","); message = message.substring(indexOf + 1); if (ack[0] == idOut) { currentMessage = ""; if (callback) { callback(true); } } if (message.length > 0) { pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin); if (idIn != ack[1]) { idIn = ack[1]; pub.up.incoming(message, origin); } } }, outgoing: function(message, origin, fn){ currentMessage = message; callback = fn; pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.QueueBehavior * This is a behavior that enables queueing of messages. <br/> * It will buffer incoming messages and dispach these as fast as the underlying transport allows. * This will also fragment/defragment messages so that the outgoing message is never bigger than the * set length. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. Optional. * @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation. */ easyXDM.stack.QueueBehavior = function(config){ var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false; function dispatch(){ if (config.remove && queue.length === 0) { removeFromStack(pub); return; } if (waiting || queue.length === 0 || destroying) { return; } waiting = true; var message = queue.shift(); pub.down.outgoing(message.data, message.origin, function(success){ waiting = false; if (message.callback) { setTimeout(function(){ message.callback(success); }, 0); } dispatch(); }); } return (pub = { init: function(){ if (undef(config)) { config = {}; } if (config.maxLength) { maxLength = config.maxLength; doFragment = true; } if (config.lazy) { lazy = true; } else { pub.down.init(); } }, callback: function(success){ waiting = false; var up = pub.up; // in case dispatch calls removeFromStack dispatch(); up.callback(success); }, incoming: function(message, origin){ if (doFragment) { var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10); incoming += message.substring(indexOf + 1); if (seq === 0) { if (config.encode) { incoming = decodeURIComponent(incoming); } pub.up.incoming(incoming, origin); incoming = ""; } } else { pub.up.incoming(message, origin); } }, outgoing: function(message, origin, fn){ if (config.encode) { message = encodeURIComponent(message); } var fragments = [], fragment; if (doFragment) { // fragment into chunks while (message.length !== 0) { fragment = message.substring(0, maxLength); message = message.substring(fragment.length); fragments.push(fragment); } // enqueue the chunks while ((fragment = fragments.shift())) { queue.push({ data: fragments.length + "_" + fragment, origin: origin, callback: fragments.length === 0 ? fn : null }); } } else { queue.push({ data: message, origin: origin, callback: fn }); } if (lazy) { pub.down.init(); } else { dispatch(); } }, destroy: function(){ destroying = true; pub.down.destroy(); } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, debug */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.VerifyBehavior * This behavior will verify that communication with the remote end is possible, and will also sign all outgoing, * and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages. * @namespace easyXDM.stack * @constructor * @param {Object} config The behaviors configuration. * @cfg {Boolean} initiate If the verification should be initiated from this end. */ easyXDM.stack.VerifyBehavior = function(config){ var pub, mySecret, theirSecret, verified = false; function startVerification(){ mySecret = Math.random().toString(16).substring(2); pub.down.outgoing(mySecret); } return (pub = { incoming: function(message, origin){ var indexOf = message.indexOf("_"); if (indexOf === -1) { if (message === mySecret) { pub.up.callback(true); } else if (!theirSecret) { theirSecret = message; if (!config.initiate) { startVerification(); } pub.down.outgoing(message); } } else { if (message.substring(0, indexOf) === theirSecret) { pub.up.incoming(message.substring(indexOf + 1), origin); } } }, outgoing: function(message, origin, fn){ pub.down.outgoing(mySecret + "_" + message, origin, fn); }, callback: function(success){ if (config.initiate) { startVerification(); } } }); }; /*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/ /*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */ // // easyXDM // http://easyxdm.net/ // Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no. // // 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. // /** * @class easyXDM.stack.RpcBehavior * This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.<br/> * Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything. * @namespace easyXDM.stack * @constructor * @param {Object} proxy The object to apply the methods to. * @param {Object} config The definition of the local and remote interface to implement. * @cfg {Object} local The local interface to expose. * @cfg {Object} remote The remote methods to expose through the proxy. * @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON. */ easyXDM.stack.RpcBehavior = function(proxy, config){ var pub, serializer = config.serializer || getJSON(); var _callbackCounter = 0, _callbacks = {}; /** * Serializes and sends the message * @private * @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added. */ function _send(data){ data.jsonrpc = "2.0"; pub.down.outgoing(serializer.stringify(data)); } /** * Creates a method that implements the given definition * @private * @param {Object} The method configuration * @param {String} method The name of the method * @return {Function} A stub capable of proxying the requested method call */ function _createMethod(definition, method){ var slice = Array.prototype.slice; return function(){ var l = arguments.length, callback, message = { method: method }; if (l > 0 && typeof arguments[l - 1] === "function") { //with callback, procedure if (l > 1 && typeof arguments[l - 2] === "function") { // two callbacks, success and error callback = { success: arguments[l - 2], error: arguments[l - 1] }; message.params = slice.call(arguments, 0, l - 2); } else { // single callback, success callback = { success: arguments[l - 1] }; message.params = slice.call(arguments, 0, l - 1); } _callbacks["" + (++_callbackCounter)] = callback; message.id = _callbackCounter; } else { // no callbacks, a notification message.params = slice.call(arguments, 0); } if (definition.namedParams && message.params.length === 1) { message.params = message.params[0]; } // Send the method request _send(message); }; } /** * Executes the exposed method * @private * @param {String} method The name of the method * @param {Number} id The callback id to use * @param {Function} method The exposed implementation * @param {Array} params The parameters supplied by the remote end */ function _executeMethod(method, id, fn, params){ if (!fn) { if (id) { _send({ id: id, error: { code: -32601, message: "Procedure not found." } }); } return; } var success, error; if (id) { success = function(result){ success = emptyFn; _send({ id: id, result: result }); }; error = function(message, data){ error = emptyFn; var msg = { id: id, error: { code: -32099, message: message } }; if (data) { msg.error.data = data; } _send(msg); }; } else { success = error = emptyFn; } // Call local method if (!isArray(params)) { params = [params]; } try { var result = fn.method.apply(fn.scope, params.concat([success, error])); if (!undef(result)) { success(result); } } catch (ex1) { error(ex1.message); } } return (pub = { incoming: function(message, origin){ var data = serializer.parse(message); if (data.method) { // A method call from the remote end if (config.handle) { config.handle(data, _send); } else { _executeMethod(data.method, data.id, config.local[data.method], data.params); } } else { // A method response from the other end var callback = _callbacks[data.id]; if (data.error) { if (callback.error) { callback.error(data.error); } } else if (callback.success) { callback.success(data.result); } delete _callbacks[data.id]; } }, init: function(){ if (config.remote) { // Implement the remote sides exposed methods for (var method in config.remote) { if (config.remote.hasOwnProperty(method)) { proxy[method] = _createMethod(config.remote[method], method); } } } pub.down.init(); }, destroy: function(){ for (var method in config.remote) { if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) { delete proxy[method]; } } pub.down.destroy(); } }); }; global.easyXDM = easyXDM; })(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent); /*! * F2 v1.3.3 04-07-2014 * Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org * * "F2" is 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. * * Please note that F2 ("Software") may contain third party material that Markit * On Demand Inc. has a license to use and include within the Software (the * "Third Party Material"). A list of the software comprising the Third Party Material * and the terms and conditions under which such Third Party Material is distributed * are reproduced in the ThirdPartyMaterial.md file available at: * * https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md * * The inclusion of the Third Party Material in the Software does not grant, provide * nor result in you having acquiring any rights whatsoever, other than as stipulated * in the terms and conditions related to the specific Third Party Material, if any. * */ var F2; /** * Open F2 * @module f2 * @main f2 */ F2 = (function() { /** * Abosolutizes a relative URL * @method _absolutizeURI * @private * @param {e.g., location.href} base * @param {URL to absolutize} href * @returns {string} URL * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _absolutizeURI = function(base, href) {// RFC 3986 function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '') .replace(/\/(\.(\/|$))+/g, '/') .replace(/\/\.\.$/, '/../') .replace(/\/?[^\/]*/g, function (p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = _parseURI(href || ''); base = _parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) + (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) + href.hash; }; /** * Parses URI * @method _parseURI * @private * @param {The URL to parse} url * @returns {Parsed URL} string * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _parseURI = function(url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', host : m[3] || '', hostname : m[4] || '', port : m[5] || '', pathname : m[6] || '', search : m[7] || '', hash : m[8] || '' } : null); }; return { /** * A function to pass into F2.stringify which will prevent circular * reference errors when serializing objects * @method appConfigReplacer */ appConfigReplacer: function(key, value) { if (key == 'root' || key == 'ui' || key == 'height') { return undefined; } else { return value; } }, /** * The apps namespace is a place for app developers to put the javascript * class that is used to initialize their app. The javascript classes should * be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId. * It is recommended that the code be placed in a closure to help keep the * global namespace clean. * * If the class has an 'init' function, that function will be called * automatically by F2. * @property Apps * @type object * @example * F2.Apps["com_example_helloworld"] = (function() { * var App_Class = function(appConfig, appContent, root) { * this._app = appConfig; // the F2.AppConfig object * this._appContent = appContent // the F2.AppManifest.AppContent object * this.$root = $(root); // the root DOM Element that contains this app * } * * App_Class.prototype.init = function() { * // perform init actions * } * * return App_Class; * })(); * @example * F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) { * return { * init:function() { * // perform init actions * } * }; * }; * @for F2 */ Apps: {}, /** * Creates a namespace on F2 and copies the contents of an object into * that namespace optionally overwriting existing properties. * @method extend * @param {string} ns The namespace to create. Pass a falsy value to * add properties to the F2 namespace directly. * @param {object} obj The object to copy into the namespace. * @param {bool} overwrite True if object properties should be overwritten * @return {object} The created object */ extend: function (ns, obj, overwrite) { var isFunc = typeof obj === 'function'; var parts = ns ? ns.split('.') : []; var parent = this; obj = obj || {}; // ignore leading global if (parts[0] === 'F2') { parts = parts.slice(1); } // create namespaces for (var i = 0, len = parts.length; i < len; i++) { if (!parent[parts[i]]) { parent[parts[i]] = isFunc && i + 1 == len ? obj : {}; } parent = parent[parts[i]]; } // copy object into namespace if (!isFunc) { for (var prop in obj) { if (typeof parent[prop] === 'undefined' || overwrite) { parent[prop] = obj[prop]; } } } return parent; }, /** * Generates a somewhat random id * @method guid * @return {string} A random id * @for F2 */ guid: function() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4()); }, /** * Search for a value within an array. * @method inArray * @param {object} value The value to search for * @param {Array} array The array to search * @return {bool} True if the item is in the array */ inArray: function(value, array) { return jQuery.inArray(value, array) > -1; }, /** * Tests a URL to see if it's on the same domain (local) or not * @method isLocalRequest * @param {URL to test} url * @returns {bool} Whether the URL is local or not * Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js */ isLocalRequest: function(url){ var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, urlLower = url.toLowerCase(), parts = rurl.exec( urlLower ), ajaxLocation, ajaxLocParts; try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement('a'); ajaxLocation.href = ''; ajaxLocation = ajaxLocation.href; } ajaxLocation = ajaxLocation.toLowerCase(); // uh oh, the url must be relative // make it fully qualified and re-regex url if (!parts){ urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase(); parts = rurl.exec( urlLower ); } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation ) || []; // do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain) var matched = !(parts && (parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || (parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !== (ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443')))); return matched; }, /** * Utility method to determine whether or not the argument passed in is or is not a native dom node. * @method isNativeDOMNode * @param {object} testObject The object you want to check as native dom node. * @return {bool} Returns true if the object passed is a native dom node. */ isNativeDOMNode: function(testObject) { var bIsNode = ( typeof Node === 'object' ? testObject instanceof Node : testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string' ); var bIsElement = ( typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2 testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string' ); return (bIsNode || bIsElement); }, /** * A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console). * @method log * @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api). * @param {object} [obj2]* An object to be logged * @example //Pass any object (string, int, array, object, bool) to .log() F2.log('foo'); F2.log(myArray); //Use a console method name as the first argument. F2.log('error', err); F2.log('info', 'The session ID is ' + sessionId); * Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js) */ log: function() { var _log; var _logMethod = 'log'; var method; var noop = function () { }; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); var args; while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } //if first arg is a console function, use it. //defaults to console.log() if (arguments && arguments.length > 1 && arguments[0] == method){ _logMethod = method; //remove console func from args args = Array.prototype.slice.call(arguments, 1); } } if (Function.prototype.bind) { _log = Function.prototype.bind.call(console[_logMethod], console); } else { _log = function() { Function.prototype.apply.call(console[_logMethod], console, (args || arguments)); }; } _log.apply(this, (args || arguments)); }, /** * Wrapper to convert a JSON string to an object * @method parse * @param {string} str The JSON string to convert * @return {object} The parsed object */ parse: function(str) { return JSON.parse(str); }, /** * Wrapper to convert an object to JSON * * **Note: When using F2.stringify on an F2.AppConfig object, it is * recommended to pass F2.appConfigReplacer as the replacer function in * order to prevent circular serialization errors.** * @method stringify * @param {object} value The object to convert * @param {function|Array} replacer An optional parameter that determines * how object values are stringified for objects. It can be a function or an * array of strings. * @param {int|string} space An optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will be * packed without extra whitespace. If it is a number, it will specify the * number of spaces to indent at each level. If it is a string (such as '\t' * or '&nbsp;'), it contains the characters used to indent at each level. * @return {string} The JSON string */ stringify: function(value, replacer, space) { return JSON.stringify(value, replacer, space); }, /** * Function to get the F2 version number * @method version * @return {string} F2 version number */ version: function() { return '1.3.3'; } }; })(); /** * The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction. * *<p class="alert alert-block alert-warning"> *The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated&mdash;but not removed&mdash;in version 1.2. They will be permanently removed in a future version of F2. *</p> * *<p class="alert alert-block alert-info"> *Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout. *</p> * * ### Order of Execution * * **App Rendering** * * 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed. * 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached. * 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached. * 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired. * 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached. * 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached. * * * **App Removal** * 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run. * 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached. * 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached. * 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached. * * **Error Handling** * 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached. * * @class F2.AppHandlers */ F2.extend('AppHandlers', (function() { // the hidden token that we will check against every time someone tries to add, remove, fire handler var _ct = F2.guid(); var _f2t = F2.guid(); var _handlerCollection = { appCreateRoot: [], appRenderBefore: [], appDestroyBefore: [], appRenderAfter: [], appDestroyAfter: [], appRender: [], appDestroy: [], appScriptLoadFailed: [] }; var _defaultMethods = { appRender: function(appConfig, appHtml) { var $root = null; // if no app root is defined use the app's outer most node if(!F2.isNativeDOMNode(appConfig.root)) { appConfig.root = jQuery(appHtml).get(0); // get a handle on the root in jQuery $root = jQuery(appConfig.root); } else { // get a handle on the root in jQuery $root = jQuery(appConfig.root); // append the app html to the root $root.append(appHtml); } // append the root to the body by default. jQuery('body').append($root); }, appDestroy: function(appInstance) { // call the apps destroy method, if it has one if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') { appInstance.app.destroy(); } // warn the Container and App Developer that even though they have a destroy method it hasn't been else if(appInstance && appInstance.app && appInstance.app.destroy) { F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); } // fade out and remove the root jQuery(appInstance.config.root).fadeOut(500, function() { jQuery(this).remove(); }); } }; var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate) { // will throw an exception and stop execution if the token is invalid _validateToken(token); // create handler structure. Not all arguments properties will be populated/used. var handler = { func: (typeof(func_or_element)) ? func_or_element : null, namespace: sNamespace, domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null }; if(!handler.func && !handler.domNode) { throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.'); } if(handler.domNode && !bDomNodeAppropriate) { throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.'); } return handler; }; var _validateToken = function(sToken) { // check token against F2 and container if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); } }; var _removeHandler = function(sToken, eventKey, sNamespace) { // will throw an exception and stop execution if the token is invalid _validateToken(sToken); if(!sNamespace && !eventKey) { return; } // remove by event key else if(!sNamespace && eventKey) { _handlerCollection[eventKey] = []; } // remove by namespace only else if(sNamespace && !eventKey) { sNamespace = sNamespace.toLowerCase(); for(var currentEventKey in _handlerCollection) { var eventCollection = _handlerCollection[currentEventKey]; var newEvents = []; for(var i = 0, ec = eventCollection.length; i < ec; i++) { var currentEventHandler = eventCollection[i]; if(currentEventHandler) { if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace) { newEvents.push(currentEventHandler); } } } eventCollection = newEvents; } } else if(sNamespace && _handlerCollection[eventKey]) { sNamespace = sNamespace.toLowerCase(); var newHandlerCollection = []; for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++) { var currentHandler = _handlerCollection[eventKey][iCounter]; if(currentHandler) { if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace) { newHandlerCollection.push(currentHandler); } } } _handlerCollection[eventKey] = newHandlerCollection; } }; return { /** * Allows Container Developer to retrieve a unique token which must be passed to * all `on` and `off` methods. This function will self destruct and can only be called * one time. Container Developers must store the return value inside of a closure. * @method getToken **/ getToken: function() { // delete this method for security that way only the container has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.getToken; // return the token, which we validate against. return _ct; }, /** * Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}. * This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}} * and additional internal methods. * @method __f2GetToken * @private **/ __f2GetToken: function() { // delete this method for security that way only the F2 internally has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.__f2GetToken; // return the token, which we validate against. return _f2t; }, /** * Allows F2 to trigger specific events internally. * @method __trigger * @private * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}. * @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. **/ __trigger: function(token, eventKey) // additional arguments will likely be passed { // will throw an exception and stop execution if the token is invalid if(token != _f2t) { throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().'); } if(_handlerCollection && _handlerCollection[eventKey]) { // create a collection of arguments that are safe to pass to the callback. var passableArgs = []; // populate that collection with all arguments except token and eventKey for(var i = 2, j = arguments.length; i < j; i++) { passableArgs.push(arguments[i]); } if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey]) { _defaultMethods[eventKey].apply(F2, passableArgs); return this; } else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey]) { return this; } // fire all event listeners in the order that they were added. for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++) { var handler = _handlerCollection[eventKey][iCounter]; // appRender where root is already defined if (handler.domNode && arguments[2] && arguments[2].root && arguments[3]) { var $appRoot = jQuery(arguments[2].root).append(arguments[3]); jQuery(handler.domNode).append($appRoot); } else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3]) { // set the root to the actual HTML of the app arguments[2].root = jQuery(arguments[3]).get(0); // appends the root to the dom node specified jQuery(handler.domNode).append(arguments[2].root); } else { handler.func.apply(F2, passableArgs); } } } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {HTMLElement} element Specific DOM element to which app gets appended. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRender', * document.getElementById('my_app') * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRender.myNamespace', * document.getElementById('my_app') * ); **/ /** * Allows Container Developer to add listener method that will be triggered when a specific event occurs. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRenderBefore' * function() { F2.log('before app rendered!'); } * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRenderBefore.myNamespace', * function() { F2.log('before app rendered!'); } * ); **/ on: function(token, eventKey, func_or_element) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _handlerCollection[eventKey].push( _createHandler( token, sNamespace, func_or_element, (eventKey == 'appRender') ) ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to remove listener methods for specific events * @method off * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all * listeners for the specified event type will be removed. * Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.off(_token,'appRenderBefore'); * **/ off: function(token, eventKey) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _removeHandler( token, eventKey, sNamespace ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; } }; })()); F2.extend('Constants', { /** * A convenient collection of all available appHandler events. * @class F2.Constants.AppHandlers **/ AppHandlers: (function() { return { /** * Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_CREATE_ROOT * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_CREATE_ROOT, * function(appConfig) * { * // If you want to create a custom root. By default F2 uses the app's outermost HTML element. * // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER * appConfig.root = jQuery('<section></section>').get(0); * } * ); */ APP_CREATE_ROOT: 'appCreateRoot', /** * Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_BEFORE, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_BEFORE: 'appRenderBefore', /** * Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) ) * @property APP_RENDER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER, * function(appConfig, appHtml) * { * var $root = null; * * // if no app root is defined use the app's outer most node * if(!F2.isNativeDOMNode(appConfig.root)) * { * appConfig.root = jQuery(appHtml).get(0); * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * } * else * { * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * * // append the app html to the root * $root.append(appHtml); * } * * // append the root to the body by default. * jQuery('body').append($root); * } * ); */ APP_RENDER: 'appRender', /** * Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_AFTER, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_AFTER: 'appRenderAfter', /** * Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_BEFORE, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_BEFORE: 'appDestroyBefore', /** * Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY, * function(appInstance) * { * // call the apps destroy method, if it has one * if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') * { * appInstance.app.destroy(); * } * else if(appInstance && appInstance.app && appInstance.app.destroy) * { * F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); * } * * // fade out and remove the root * jQuery(appInstance.config.root).fadeOut(500, function() { * jQuery(this).remove(); * }); * } * ); */ APP_DESTROY: 'appDestroy', /** * Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_AFTER, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_AFTER: 'appDestroyAfter', /** * Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo ) * @property APP_SCRIPT_LOAD_FAILED * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, * function(appConfig, scriptInfo) * { * F2.log(appConfig.appId); * } * ); */ APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed' }; })() }); /** * Class stubs for documentation purposes * @main F2 */ F2.extend('', { /** * The App Class is an optional class that can be namespaced onto the * {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The * [F2 Docs](../../app-development.html#app-class) * has more information on the usage of the App Class. * @class F2.App * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object for the app * @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent * object * @param {Element} root The root DOM Element for the app */ App: function(appConfig, appContent, root) { return { /** * An optional init function that will automatically be called when * F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called. * @method init * @optional */ init:function() {} }; }, /** * The AppConfig object represents an app's meta data * @class F2.AppConfig */ AppConfig: { /** * The unique ID of the app. More information can be found * [here](../../app-development.html#f2-appid) * @property appId * @type string * @required */ appId: '', /** * An object that represents the context of an app * @property context * @type object */ context: {}, /** * True if the app should be requested in a single request with other apps. * @property enableBatchRequests * @type bool * @default false */ enableBatchRequests: false, /** * The height of the app. The initial height will be pulled from * the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later * modified by calling * F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used * for secure apps to be able to set the initial height of the iframe. * @property height * @type int */ height: 0, /** * The unique runtime ID of the app. * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property instanceId * @type string */ instanceId: '', /** * True if the app will be loaded in an iframe. This property * will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object * sets isSecure = true. It will also be true if the * [container](../../container-development.html) has made the decision to * run apps in iframes. * @property isSecure * @type bool * @default false */ isSecure: false, /** * The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}} * object. * @property manifestUrl * @type string * @required */ manifestUrl: '', /** * The recommended maximum width in pixels that this app should be run. * **It is up to the [container](../../container-development.html) to * implement the logic to prevent an app from being run when the maxWidth * requirements are not met.** * @property maxWidth * @type int */ maxWidth: 0, /** * The recommended minimum grid size that this app should be run. This * value corresponds to the 12-grid system that is used by the * [container](../../container-development.html). This property should be * set by apps that require a certain number of columns in their layout. * @property minGridSize * @type int * @default 4 */ minGridSize: 4, /** * The recommended minimum width in pixels that this app should be run. **It * is up to the [container](../../container-development.html) to implement * the logic to prevent an app from being run when the minWidth requirements * are not met. * @property minWidth * @type int * @default 300 */ minWidth: 300, /** * The name of the app * @property name * @type string * @required */ name: '', /** * The root DOM element that contains the app * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property root * @type Element */ root: undefined, /** * The instance of F2.UI providing easy access to F2.UI methods * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property ui * @type F2.UI */ ui: undefined, /** * The views that this app supports. Available views * are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The * presence of a view can be checked via * F2.{{#crossLink "F2/inArray"}}{{/crossLink}}: * * F2.inArray(F2.Constants.Views.SETTINGS, app.views) * * @property views * @type Array */ views: [] }, /** * The assets needed to render an app on the page * @class F2.AppManifest */ AppManifest: { /** * The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}} * objects * @property apps * @type Array * @required */ apps: [], /** * Any inline javascript tha should initially be run * @property inlineScripts * @type Array * @optional */ inlineScripts: [], /** * Urls to javascript files required by the app * @property scripts * @type Array * @optional */ scripts: [], /** * Urls to CSS files required by the app * @property styles * @type Array * @optional */ styles: [] }, /** * The AppContent object * @class F2.AppManifest.AppContent **/ AppContent: { /** * Arbitrary data to be passed along with the app * @property data * @type object * @optional */ data: {}, /** * The string of HTML representing the app * @property html * @type string * @required */ html: '', /** * A status message * @property status * @type string * @optional */ status: '' }, /** * An object containing configuration information for the * [container](../../container-development.html) * @class F2.ContainerConfig */ ContainerConfig: { /** * Allows the [container](../../container-development.html) to override how * an app's html is inserted into the page. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html * @method afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app * @return {Element} The DOM Element surrounding the app */ afterAppRender: function(appConfig, html) {}, /** * Allows the [container](../../container-development.html) to wrap an app * in extra html. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html. The extra html can provide links to edit app settings and remove an * app from the container. See * {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that * should be applied to elements. * @method appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app */ appRender: function(appConfig, html) {}, /** * Allows the container to render html for an app before the AppManifest for * an app has loaded. This can be useful if the design calls for loading * icons to appear for each app before each app is loaded and rendered to * the page. * @method beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ beforeAppRender: function(appConfig) {}, /** * True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc. * @property debugMode * @type bool * @default false */ debugMode: false, /** * Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire. * @property scriptErrorTimeout * @type milliseconds * @default 7000 (7 seconds) */ scriptErrorTimeout: 7000, /** * Tells the container that it is currently running within * a secure app page * @property isSecureAppPage * @type bool */ isSecureAppPage: false, /** * Allows the container to specify which page is used when * loading a secure app. The page must reside on a different domain than the * container * @property secureAppPagePath * @type string * @for F2.ContainerConfig */ secureAppPagePath: '', /** * Specifies what views a container will provide buttons * or links to. Generally, the views will be switched via buttons or links * in the app's header. * @property supportedViews * @type Array * @required */ supportedViews: [], /** * An object containing configuration defaults for F2.UI * @class F2.ContainerConfig.UI */ UI: { /** * An object containing configuration defaults for the * F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and * F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods. * @class F2.ContainerConfig.UI.Mask */ Mask: { /** * The backround color of the overlay * @property backgroundColor * @type string * @default #FFF */ backgroundColor: '#FFF', /** * The path to the loading icon * @property loadingIcon * @type string */ loadingIcon: '', /** * The opacity of the background overlay * @property opacity * @type int * @default 0.6 */ opacity: 0.6, /** * Do not use inline styles for mask functinality. Instead classes will * be applied to the elements and it is up to the container provider to * implement the class definitions. * @property useClasses * @type bool * @default false */ useClasses: false, /** * The z-index to use for the overlay * @property zIndex * @type int * @default 2 */ zIndex: 2 } }, /** * Allows the container to fully override how the AppManifest request is * made inside of F2. * * @method xhr * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {function} success The function to be called if the request * succeeds * @param {function} error The function to be called if the request fails * @param {function} complete The function to be called when the request * finishes (after success and error callbacks have been executed) * @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has * an `abort` function (such as the jqXHR object in jQuery) to abort the * request) * * @example * F2.init({ * xhr: function(url, appConfigs, success, error, complete) { * $.ajax({ * url: url, * type: 'POST', * data: { * params: F2.stringify(appConfigs, F2.appConfigReplacer) * }, * jsonp: false, // do not put 'callback=' in the query string * jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name * dataType: 'json', * success: function(appManifest) { * // custom success logic * success(appManifest); // fire success callback * }, * error: function() { * // custom error logic * error(); // fire error callback * }, * complete: function() { * // custom complete logic * complete(); // fire complete callback * } * }); * } * }); * * @for F2.ContainerConfig */ //xhr: function(url, appConfigs, success, error, complete) {}, /** * Allows the container to override individual parts of the AppManifest * request. See properties and methods with the `xhr.` prefix. * @property xhr * @type Object * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ xhr: { /** * Allows the container to override the request data type (JSON or JSONP) * that is used for the request * @method xhr.dataType * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request data type that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ dataType: function(url, appConfigs) {}, /** * Allows the container to override the request method that is used (just * like the `type` parameter to `jQuery.ajax()`. * @method xhr.type * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request method that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ type: function(url, appConfigs) {}, /** * Allows the container to override the url that is used to request an * app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}} * @method xhr.url * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The url that should be used for the request * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ url: function(url, appConfigs) {} }, /** * Allows the container to override the script loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadScripts * @type function * * @example * F2.init({ * loadScripts: function(scripts,inlines,callback){ * //load scripts using $.load() for each script or require(scripts) * callback(); * } * }); */ loadScripts: function(scripts,inlines,callback){}, /** * Allows the container to override the stylesheet loader which requests * dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}. * @property loadStyles * @type function * * @example * F2.init({ * loadStyles: function(styles,callback){ * //load styles using $.load() for each stylesheet or another method * callback(); * } * }); */ loadStyles: function(styles,callback){} } }); /** * Constants used throughout the Open Financial Framework * @class F2.Constants * @static */ F2.extend('Constants', { /** * CSS class constants * @class F2.Constants.Css */ Css: (function() { /** @private */ var _PREFIX = 'f2-'; return { /** * The APP class should be applied to the DOM Element that surrounds the * entire app, including any extra html that surrounds the APP\_CONTAINER * that is inserted by the container. See the * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object. * @property APP * @type string * @static * @final */ APP: _PREFIX + 'app', /** * The APP\_CONTAINER class should be applied to the outermost DOM Element * of the app. * @property APP_CONTAINER * @type string * @static * @final */ APP_CONTAINER: _PREFIX + 'app-container', /** * The APP\_TITLE class should be applied to the DOM Element that contains * the title for an app. If this class is not present, then * F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function. * @property APP_TITLE * @type string * @static * @final */ APP_TITLE: _PREFIX + 'app-title', /** * The APP\_VIEW class should be applied to the DOM Element that contains * a view for an app. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is. * @property APP_VIEW * @type string * @static * @final */ APP_VIEW: _PREFIX + 'app-view', /** * APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that * trigger an * {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE * event. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger. * @property APP_VIEW_TRIGGER * @type string * @static * @final */ APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger', /** * The MASK class is applied to the overlay element that is created * when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is * fired. * @property MASK * @type string * @static * @final */ MASK: _PREFIX + 'mask', /** * The MASK_CONTAINER class is applied to the Element that is passed into * the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method. * @property MASK_CONTAINER * @type string * @static * @final */ MASK_CONTAINER: _PREFIX + 'mask-container' }; })(), /** * Events constants * @class F2.Constants.Events */ Events: (function() { /** @private */ var _APP_EVENT_PREFIX = 'App.'; /** @private */ var _CONTAINER_EVENT_PREFIX = 'Container.'; return { /** * The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an * app. It is up to the app developer to fire this event. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property APP_SYMBOL_CHANGE * @type string * @static * @final */ APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange', /** * The APP\_WIDTH\_CHANGE event will be fired by the container when the * width of an app is changed. The app's instanceId should be concatenated * to this constant. * Returns an object with the gridSize and width in pixels: * * { gridSize:8, width:620 } * * @property APP_WIDTH_CHANGE * @type string * @static * @final */ APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.', /** * The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed * at the container level. This event should only be fired by the * container or container provider. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property CONTAINER_SYMBOL_CHANGE * @type string * @static * @final */ CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange', /** * The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when * the width of the container has changed. * @property CONTAINER_WIDTH_CHANGE * @type string * @static * @final */ CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange' }; })(), JSONP_CALLBACK: 'F2_jsonpCallback_', /** * Constants for use with cross-domain sockets * @class F2.Constants.Sockets * @protected */ Sockets: { /** * The EVENT message is sent whenever * F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired * @property EVENT * @type string * @static * @final */ EVENT: '__event__', /** * The LOAD message is sent when an iframe socket initially loads. * Returns a JSON string that represents: * * [ App, AppManifest] * * @property LOAD * @type string * @static * @final */ LOAD: '__socketLoad__', /** * The RPC message is sent when a method is passed up from within a secure * app page. * @property RPC * @type string * @static * @final */ RPC: '__rpc__', /** * The RPC\_CALLBACK message is sent when a call back from an RPC method is * fired. * @property RPC_CALLBACK * @type string * @static * @final */ RPC_CALLBACK: '__rpcCallback__', /** * The UI\_RPC message is sent when a UI method called. * @property UI_RPC * @type string * @static * @final */ UI_RPC: '__uiRpc__' }, /** * The available view types to apps. The view should be specified by applying * the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the * containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the * Element as well which defines what view type is represented. * The `hide` class can be applied to views that should be hidden by default. * @class F2.Constants.Views */ Views: { /** * The DATA_ATTRIBUTE should be placed on the DOM Element that contains the * view. * @property DATA_ATTRIBUTE * @type string * @static * @final */ DATA_ATTRIBUTE: 'data-f2-view', /** * The ABOUT view gives details about the app. * @property ABOUT * @type string * @static * @final */ ABOUT: 'about', /** * The HELP view provides users with help information for using an app. * @property HELP * @type string * @static * @final */ HELP: 'help', /** * The HOME view is the main view for an app. This view should always * be provided by an app. * @property HOME * @type string * @static * @final */ HOME: 'home', /** * The REMOVE view is a special view that handles the removal of an app * from the container. * @property REMOVE * @type string * @static * @final */ REMOVE: 'remove', /** * The SETTINGS view provides users the ability to modify advanced settings * for an app. * @property SETTINGS * @type string * @static * @final */ SETTINGS: 'settings' } }); /** * Handles [Context](../../app-development.html#context) passing from * containers to apps and apps to apps. * @class F2.Events */ F2.extend('Events', (function() { // init EventEmitter var _events = new EventEmitter2({ wildcard:true }); // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); return { /** * Same as F2.Events.emit except that it will not send the event * to all sockets. * @method _socketEmit * @private * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ _socketEmit: function() { return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Execute each of the listeners that may be listening for the specified * event name in order with the list of arguments. * @method emit * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ emit: function() { F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments)); return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Adds a listener that will execute n times for the event before being * removed. The listener is invoked only the first time the event is * fired, after which it is removed. * @method many * @param {string} event The event name * @param {int} timesToListen The number of times to execute the event * before being removed * @param {function} listener The function to be fired when the event is * emitted */ many: function(event, timesToListen, listener) { return _events.many(event, timesToListen, listener); }, /** * Remove a listener for the specified event. * @method off * @param {string} event The event name * @param {function} listener The function that will be removed */ off: function(event, listener) { return _events.off(event, listener); }, /** * Adds a listener for the specified event * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ on: function(event, listener){ return _events.on(event, listener); }, /** * Adds a one time listener for the event. The listener is invoked only * the first time the event is fired, after which it is removed. * @method once * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ once: function(event, listener) { return _events.once(event, listener); } }; })()); /** * Handles socket communication between the container and secure apps * @class F2.Rpc */ F2.extend('Rpc', (function(){ var _callbacks = {}; var _secureAppPagePath = ''; var _apps = {}; var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT); var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC); var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK); var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD); var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC); /** * Creates a socket connection from the app to the container using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createAppToContainerSocket * @private */ var _createAppToContainerSocket = function() { var appConfig; // socket closure var isLoaded = false; // its possible for messages to be received before the socket load event has // happened. We'll save off these messages and replay them once the socket // is ready var messagePlayback = []; var socket = new easyXDM.Socket({ onMessage: function(message, origin){ // handle Socket Load if (!isLoaded && _rSocketLoad.test(message)) { message = message.replace(_rSocketLoad, ''); var appParts = F2.parse(message); // make sure we have the AppConfig and AppManifest if (appParts.length == 2) { appConfig = appParts[0]; // save socket _apps[appConfig.instanceId] = { config:appConfig, socket:socket }; // register app F2.registerApps([appConfig], [appParts[1]]); // socket message playback jQuery.each(messagePlayback, function(i, e) { _onMessage(appConfig, message, origin); }); isLoaded = true; } } else if (isLoaded) { // pass everyting else to _onMessage _onMessage(appConfig, message, origin); } else { //F2.log('socket not ready, queuing message', message); messagePlayback.push(message); } } }); }; /** * Creates a socket connection from the container to the app using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createContainerToAppSocket * @private * @param {appConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The F2.AppManifest object */ var _createContainerToAppSocket = function(appConfig, appManifest) { var container = jQuery(appConfig.root); if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) { container.find('.' + F2.Constants.Css.APP_CONTAINER); } if (!container.length) { F2.log('Unable to locate app in order to establish secure connection.'); return; } var iframeProps = { scrolling:'no', style:{ width:'100%' } }; if (appConfig.height) { iframeProps.style.height = appConfig.height + 'px'; } var socket = new easyXDM.Socket({ remote: _secureAppPagePath, container: container.get(0), props:iframeProps, onMessage: function(message, origin) { // pass everything to _onMessage _onMessage(appConfig, message, origin); }, onReady: function() { socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer)); } }); return socket; }; /** * @method _createRpcCallback * @private * @param {string} instanceId The app's Instance ID * @param {function} callbackId The callback ID * @return {function} A function to make the RPC call */ var _createRpcCallback = function(instanceId, callbackId) { return function() { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC_CALLBACK, callbackId, [].slice.call(arguments).slice(2) ); }; }; /** * Handles messages that come across the sockets * @method _onMessage * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} message The socket message * @param {string} origin The originator */ var _onMessage = function(appConfig, message, origin) { var obj, func; function parseFunction(parent, functionName) { var path = String(functionName).split('.'); for (var i = 0; i < path.length; i++) { if (parent[path[i]] === undefined) { parent = undefined; break; } parent = parent[path[i]]; } return parent; } function parseMessage(regEx, message, instanceId) { var o = F2.parse(message.replace(regEx, '')); // if obj.callbacks // for each callback // for each params // if callback matches param // replace param with _createRpcCallback(app.instanceId, callback) if (o.params && o.params.length && o.callbacks && o.callbacks.length) { jQuery.each(o.callbacks, function(i, c) { jQuery.each(o.params, function(i, p) { if (c == p) { o.params[i] = _createRpcCallback(instanceId, c); } }); }); } return o; } // handle UI Call if (_rUiCall.test(message)) { obj = parseMessage(_rUiCall, message, appConfig.instanceId); func = parseFunction(appConfig.ui, obj.functionName); // if we found the function, call it if (func !== undefined) { func.apply(appConfig.ui, obj.params); } else { F2.log('Unable to locate UI RPC function: ' + obj.functionName); } // handle RPC } else if (_rRpc.test(message)) { obj = parseMessage(_rRpc, message, appConfig.instanceId); func = parseFunction(window, obj.functionName); if (func !== undefined) { func.apply(func, obj.params); } else { F2.log('Unable to locate RPC function: ' + obj.functionName); } // handle RPC Callback } else if (_rRpcCallback.test(message)) { obj = parseMessage(_rRpcCallback, message, appConfig.instanceId); if (_callbacks[obj.functionName] !== undefined) { _callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params); delete _callbacks[obj.functionName]; } // handle Events } else if (_rEvents.test(message)) { obj = parseMessage(_rEvents, message, appConfig.instanceId); F2.Events._socketEmit.apply(F2.Events, obj); } }; /** * Registers a callback function * @method _registerCallback * @private * @param {function} callback The callback function * @return {string} The callback ID */ var _registerCallback = function(callback) { var callbackId = F2.guid(); _callbacks[callbackId] = callback; return callbackId; }; return { /** * Broadcast an RPC function to all sockets * @method broadcast * @param {string} messageType The message type * @param {Array} params The parameters to broadcast */ broadcast: function(messageType, params) { // check valid messageType var message = messageType + F2.stringify(params); jQuery.each(_apps, function(i, a) { a.socket.postMessage(message); }); }, /** * Calls a remote function * @method call * @param {string} instanceId The app's Instance ID * @param {string} messageType The message type * @param {string} functionName The name of the remote function * @param {Array} params An array of parameters to pass to the remote * function. Any functions found within the params will be treated as a * callback function. */ call: function(instanceId, messageType, functionName, params) { // loop through params and find functions and convert them to callbacks var callbacks = []; jQuery.each(params, function(i, e) { if (typeof e === 'function') { var cid = _registerCallback(e); params[i] = cid; callbacks.push(cid); } }); // check valid messageType _apps[instanceId].socket.postMessage( messageType + F2.stringify({ functionName:functionName, params:params, callbacks:callbacks }) ); }, /** * Init function which tells F2.Rpc whether it is running at the container- * level or the app-level. This method is generally called by * F2.{{#crossLink "F2/init"}}{{/crossLink}} * @method init * @param {string} [secureAppPagePath] The * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath * property */ init: function(secureAppPagePath) { _secureAppPagePath = secureAppPagePath; if (!_secureAppPagePath) { _createAppToContainerSocket(); } }, /** * Determines whether the Instance ID is considered to be 'remote'. This is * determined by checking if 1) the app has an open socket and 2) whether * F2.Rpc is running inside of an iframe * @method isRemote * @param {string} instanceId The Instance ID * @return {bool} True if there is an open socket */ isRemote: function(instanceId) { return ( // we have an app _apps[instanceId] !== undefined && // the app is secure _apps[instanceId].config.isSecure && // we can't access the iframe jQuery(_apps[instanceId].config.root).find('iframe').length === 0 ); }, /** * Creates a container-to-app or app-to-container socket for communication * @method register * @param {F2.AppConfig} [appConfig] The F2.AppConfig object * @param {F2.AppManifest} [appManifest] The F2.AppManifest object */ register: function(appConfig, appManifest) { if (!!appConfig && !!appManifest) { _apps[appConfig.instanceId] = { config:appConfig, socket:_createContainerToAppSocket(appConfig, appManifest) }; } else { F2.log('Unable to register socket connection. Please check container configuration.'); } } }; })()); F2.extend('UI', (function(){ var _containerConfig; /** * UI helper methods * @class F2.UI * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object */ var UI_Class = function(appConfig) { var _appConfig = appConfig; var $root = jQuery(appConfig.root); var _updateHeight = function(height) { height = height || jQuery(_appConfig.root).outerHeight(); if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'updateHeight', [ height ] ); } else { _appConfig.height = height; $root.find('iframe').height(_appConfig.height); } }; return { /** * Removes a overlay from an Element on the page * @method hideMask * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader */ hideMask: function(selector) { F2.UI.hideMask(_appConfig.instanceId, selector); }, /** * Helper methods for creating and using Modals * @class F2.UI.Modals * @for F2.UI */ Modals: (function(){ var _renderAlert = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Alert!</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button class="btn btn-primary btn-ok">OK</button>', '</div>', '</div>' ].join(''); }; var _renderConfirm = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Confirm</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button type="button" class="btn btn-primary btn-ok">OK</button>', '<button type="button" class="btn btn-cancel">Cancel</button">', '</div>', '</div>' ].join(''); }; return { /** * Display an alert message on the page * @method alert * @param {string} message The message to be displayed * @param {function} [callback] The callback to be fired when the user * closes the dialog * @for F2.UI.Modals */ alert: function(message, callback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.alert()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.alert', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderAlert(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-primary').on('click', function() { jQuery(modal).modal('hide').remove(); (callback || jQuery.noop)(); }); }) .modal({backdrop:true}); } }, /** * Display a confirm message on the page * @method confirm * @param {string} message The message to be displayed * @param {function} okCallback The function that will be called when the OK * button is pressed * @param {function} cancelCallback The function that will be called when * the Cancel button is pressed * @for F2.UI.Modals */ confirm: function(message, okCallback, cancelCallback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.confirm()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.confirm', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderConfirm(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-ok').on('click', function() { jQuery(modal).modal('hide').remove(); (okCallback || jQuery.noop)(); }); jQuery(modal).find('.btn-cancel').on('click', function() { jQuery(modal).modal('hide').remove(); (cancelCallback || jQuery.noop)(); }); }) .modal({backdrop:true}); } } }; })(), /** * Sets the title of the app as shown in the browser. Depending on the * container HTML, this method may do nothing if the container has not been * configured properly or else the container provider does not allow Title's * to be set. * @method setTitle * @params {string} title The title of the app * @for F2.UI */ setTitle: function(title) { if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'setTitle', [ title ] ); } else { jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title); } }, /** * Display an ovarlay over an Element on the page * @method showMask * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ showMask: function(selector, showLoader) { F2.UI.showMask(_appConfig.instanceId, selector, showLoader); }, /** * For secure apps, this method updates the size of the iframe that * contains the app. **Note: It is recommended that app developers call * this method anytime Elements are added or removed from the DOM** * @method updateHeight * @params {int} height The height of the app */ updateHeight: _updateHeight, /** * Helper methods for creating and using Views * @class F2.UI.Views * @for F2.UI */ Views: (function(){ var _events = new EventEmitter2(); var _rValidEvents = /change/i; // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); var _isValid = function(eventName) { if (_rValidEvents.test(eventName)) { return true; } else { F2.log('"' + eventName + '" is not a valid F2.UI.Views event name'); return false; } }; return { /** * Change the current view for the app or add an event listener * @method change * @param {string|function} [input] If a string is passed in, the view * will be changed for the app. If a function is passed in, a change * event listener will be added. * @for F2.UI.Views */ change: function(input) { if (typeof input === 'function') { this.on('change', input); } else if (typeof input === 'string') { if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Views.change', [].slice.call(arguments) ); } else if (F2.inArray(input, _appConfig.views)) { jQuery('.' + F2.Constants.Css.APP_VIEW, $root) .addClass('hide') .filter('[data-f2-view="' + input + '"]', $root) .removeClass('hide'); _updateHeight(); _events.emit('change', input); } } }, /** * Removes a view event listener * @method off * @param {string} event The event name * @param {function} listener The function that will be removed * @for F2.UI.Views */ off: function(event, listener) { if (_isValid(event)) { _events.off(event, listener); } }, /** * Adds a view event listener * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted * @for F2.UI.Views */ on: function(event, listener) { if (_isValid(event)) { _events.on(event, listener); } } }; })() }; }; /** * Removes a overlay from an Element on the page * @method hideMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader * @for F2.UI */ UI_Class.hideMask = function(instanceId, selector) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.hideMask()'); return; } if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.hideMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector ] ); } else { var container = jQuery(selector); container.find('> .' + F2.Constants.Css.MASK).remove(); container.removeClass(F2.Constants.Css.MASK_CONTAINER); // if the element contains this data property, we need to reset static // position if (container.data(F2.Constants.Css.MASK_CONTAINER)) { container.css({'position':'static'}); } } }; /** * * @method init * @static * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ UI_Class.init = function(containerConfig) { _containerConfig = containerConfig; // set defaults _containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {}); }; /** * Display an ovarlay over an Element on the page * @method showMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ UI_Class.showMask = function(instanceId, selector, showLoading) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.showMask()'); return; } if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.showMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector, showLoading ] ); } else { if (showLoading && !_containerConfig.UI.Mask.loadingIcon) { F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();'); } var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER); var mask = jQuery('<div>') .height('100%' /*container.outerHeight()*/) .width('100%' /*container.outerWidth()*/) .addClass(F2.Constants.Css.MASK); // set inline styles if useClasses is false if (!_containerConfig.UI.Mask.useClasses) { mask.css({ 'background-color':_containerConfig.UI.Mask.backgroundColor, 'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '', 'background-position':'50% 50%', 'background-repeat':'no-repeat', 'display':'block', 'left':0, 'min-height':30, 'padding':0, 'position':'absolute', 'top':0, 'z-index':_containerConfig.UI.Mask.zIndex, 'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')', 'opacity':_containerConfig.UI.Mask.opacity }); } // only set the position if the container is currently static if (container.css('position') === 'static') { container.css({'position':'relative'}); // setting this data property tells hideMask to set the position // back to static container.data(F2.Constants.Css.MASK_CONTAINER, true); } // add the mask to the container container.append(mask); } }; return UI_Class; })()); /** * Root namespace of the F2 SDK * @module f2 * @class F2 */ F2.extend('', (function() { var _apps = {}; var _config = false; var _bUsesAppHandlers = false; var _sAppHandlerToken = F2.AppHandlers.__f2GetToken(); /** * Appends the app's html to the DOM * @method _afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html * @return {Element} The DOM Element that contains the app */ var _afterAppRender = function(appConfig, html) { var handler = _config.afterAppRender || function(appConfig, html) { return jQuery(html).appendTo('body'); }; var appContainer = handler(appConfig, html); if ( !! _config.afterAppRender && !appContainer) { F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app'); return; } else { // apply APP class and Instance ID jQuery(appContainer).addClass(F2.Constants.Css.APP); return appContainer.get(0); } }; /** * Renders the html for an app. * @method _appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html */ var _appRender = function(appConfig, html) { // apply APP_CONTAINER class html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId)); // optionally apply wrapper html if (_config.appRender) { html = _config.appRender(appConfig, html); } // apply APP class and instanceId return _outerHtml(html); }; /** * Rendering hook to allow containers to render some html prior to an app * loading * @method _beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ var _beforeAppRender = function(appConfig) { var handler = _config.beforeAppRender || jQuery.noop; return handler(appConfig); }; /** * Handler to inform the container that a script failed to load * @method _onScriptLoadFailure * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param scriptInfo The path of the script that failed to load or the exception info * for the inline script that failed to execute */ var _appScriptLoadFailed = function(appConfig, scriptInfo) { var handler = _config.appScriptLoadFailed || jQuery.noop; return handler(appConfig, scriptInfo); }; /** * Adds properties to the AppConfig object * @method _createAppConfig * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with * necessary properties */ var _createAppConfig = function(appConfig) { // make a copy of the app config to ensure that the original is not modified appConfig = jQuery.extend(true, {}, appConfig); // create the instanceId for the app appConfig.instanceId = appConfig.instanceId || F2.guid(); // default the views if not provided appConfig.views = appConfig.views || []; if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) { appConfig.views.push(F2.Constants.Views.HOME); } return appConfig; }; /** * Adds properties to the ContainerConfig object to take advantage of defaults * @method _hydrateContainerConfig * @private * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ var _hydrateContainerConfig = function(containerConfig) { if (!containerConfig.scriptErrorTimeout) { containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout; } if (containerConfig.debugMode !== true) { containerConfig.debugMode = F2.ContainerConfig.debugMode; } }; /** * Attach app events * @method _initAppEvents * @private */ var _initAppEvents = function(appConfig) { jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) { event.preventDefault(); var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase(); // handle the special REMOVE view if (view == F2.Constants.Views.REMOVE) { F2.removeApp(appConfig.instanceId); } else { appConfig.ui.Views.change(view); } }); }; /** * Attach container Events * @method _initContainerEvents * @private */ var _initContainerEvents = function() { var resizeTimeout; var resizeHandler = function() { F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE); }; jQuery(window).on('resize', function() { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(resizeHandler, 100); }); }; /** * Has the container been init? * @method _isInit * @private * @return {bool} True if the container has been init */ var _isInit = function() { return !!_config; }; /** * Instantiates each app from it's appConfig and stores that in a local private collection * @method _createAppInstance * @private * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects */ var _createAppInstance = function(appConfig, appContent) { // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // instantiate F2.App if (F2.Apps[appConfig.appId] !== undefined) { if (typeof F2.Apps[appConfig.appId] === 'function') { // IE setTimeout(function() { _apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root); if (_apps[appConfig.instanceId].app['init'] !== undefined) { _apps[appConfig.instanceId].app.init(); } }, 0); } else { F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')'); } } }; /** * Loads the app's html/css/javascript * @method loadApp * @private * @param {Array} appConfigs An array of * {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects * @param {F2.AppManifest} [appManifest] The AppManifest object */ var _loadApps = function(appConfigs, appManifest) { appConfigs = [].concat(appConfigs); // check for secure app if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) { _loadSecureApp(appConfigs[0], appManifest); return; } // check that the number of apps in manifest matches the number requested if (appConfigs.length != appManifest.apps.length) { F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest); return; } // Fn for loading manifest Styles var _loadStyles = function(styles, cb) { // Attempt to use the user provided method if (_config.loadStyles) { _config.loadStyles(styles, cb); } else { // load styles, see #101 var stylesFragment = null, useCreateStyleSheet = !! document.createStyleSheet; jQuery.each(styles, function(i, e) { if (useCreateStyleSheet) { document.createStyleSheet(e); } else { stylesFragment = stylesFragment || []; stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>'); } }); if (stylesFragment) { jQuery('head').append(stylesFragment.join('')); } cb(); } }; // Fn for loading manifest Scripts var _loadScripts = function(scripts, cb) { // Attempt to use the user provided method if (_config.loadScripts) { _config.loadScripts(scripts, cb); } else { if (scripts.length) { var scriptCount = scripts.length; var scriptsLoaded = 0; // Check for IE10+ so that we don't rely on onreadystatechange var readyStates = ('addEventListener' in window) ? {} : { 'loaded': true, 'complete': true }; // Log and emit event for the failed (400,500) scripts var _error = function(e) { setTimeout(function() { var evtData = { src: e.target.src, appId: appConfigs[0].appId }; // Send error to console F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\''); // Emit event F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], evtData.src); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], evtData.src ); } }, _config.scriptErrorTimeout); // Defaults to 7000 }; // Load scripts and eval inlines once complete jQuery.each(scripts, function(i, e) { var doc = document, script = doc.createElement('script'), resourceUrl = e; // If in debugMode, add cache buster to each script URL if (_config.debugMode) { resourceUrl += '?cachebuster=' + new Date().getTime(); } // Scripts needed to be loaded in order they're defined in the AppManifest script.async = false; // Add other attrs script.src = resourceUrl; script.type = 'text/javascript'; script.charset = 'utf-8'; script.onerror = _error; // Use a closure for the load event so that we can dereference the original script script.onload = script.onreadystatechange = function(e) { e = e || window.event; // For older IE if (e.type == 'load' || readyStates[script.readyState]) { // Done, cleanup script.onload = script.onreadystatechange = script.onerror = null; // Dereference script script = null; // Are we done loading all scripts for this app? if (++scriptsLoaded === scriptCount) { cb(); } } }; doc.body.appendChild(script); }); } else { cb(); } } }; var _loadInlineScripts = function(inlines, cb) { // Attempt to use the user provided method if (_config.loadInlineScripts) { _config.loadInlineScripts(inlines, cb); } else { for (var i = 0, len = inlines.length; i < len; i++) { try { eval(inlines[i]); } catch (exception) { F2.log('Error loading inline script: ' + exception + '\n\n' + inlines[i]); if (!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0], exception); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], exception ); } } } cb(); } }; // Determine whether an element has been added to the page var elementInDocument = function(element) { if (element) { while (element.parentNode) { element = element.parentNode; if (element === document) { return true; } } } return false; }; // Fn for loading manifest app html var _loadHtml = function(apps) { jQuery.each(apps, function(i, a) { if (!_bUsesAppHandlers) { // load html and save the root node appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html)); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfigs[i], // the app config _outerHtml(a.html) ); var appId = appConfigs[i].appId; var root = appConfigs[i].root; if (!root) { throw ('Root for ' + appId + ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.'); } if (!elementInDocument(root)) { throw ('App root for ' + appId + ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfigs[i] // the app config ); if (!F2.isNativeDOMNode(root)) { throw ('App root for ' + appId + ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.'); } $(root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId); } // init events _initAppEvents(appConfigs[i]); }); }; // Pull out the manifest data var scripts = appManifest.scripts || []; var styles = appManifest.styles || []; var inlines = appManifest.inlineScripts || []; var apps = appManifest.apps || []; // Finally, load the styles, html, and scripts _loadStyles(styles, function() { // Put the html on the page _loadHtml(apps); // Add the script content to the page _loadScripts(scripts, function() { // Load any inline scripts _loadInlineScripts(inlines, function() { // Create the apps jQuery.each(appConfigs, function(i, a) { _createAppInstance(a, appManifest.apps[i]); }); }); }); }); }; /** * Loads the app's html/css/javascript into an iframe * @method loadSecureApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the * page. */ var _loadSecureApp = function(appConfig, appManifest) { // make sure the container is configured for secure apps if (_config.secureAppPagePath) { if (!_bUsesAppHandlers) { // create the html container for the iframe appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>')); } else { var $root = jQuery(appConfig.root); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfig, // the app config appManifest.html ); if ($root.parents('body:first').length === 0) { throw ('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfig // the app config ); if (!appConfig.root) { throw ('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } if (!F2.isNativeDOMNode(appConfig.root)) { throw ('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId); } // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // init events _initAppEvents(appConfig); // create RPC socket F2.Rpc.register(appConfig, appManifest); } else { F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.'); } }; var _outerHtml = function(html) { return jQuery('<div></div>').append(html).html(); }; /** * Checks if the app is valid * @method _validateApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @returns {bool} True if the app is valid */ var _validateApp = function(appConfig) { // check for valid app configurations if (!appConfig.appId) { F2.log('"appId" missing from app object'); return false; } else if (!appConfig.root && !appConfig.manifestUrl) { F2.log('"manifestUrl" missing from app object'); return false; } return true; }; /** * Checks if the ContainerConfig is valid * @method _validateContainerConfig * @private * @returns {bool} True if the config is valid */ var _validateContainerConfig = function() { if (_config) { if (_config.xhr) { if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) { throw ('ContainerConfig.xhr should be a function or an object'); } if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') { throw ('ContainerConfig.xhr.dataType should be a function'); } if (_config.xhr.type && typeof _config.xhr.type !== 'function') { throw ('ContainerConfig.xhr.type should be a function'); } if (_config.xhr.url && typeof _config.xhr.url !== 'function') { throw ('ContainerConfig.xhr.url should be a function'); } } } return true; }; return { /** * Gets the current list of apps in the container * @method getContainerState * @returns {Array} An array of objects containing the appId */ getContainerState: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.getContainerState()'); return; } return jQuery.map(_apps, function(app) { return { appId: app.config.appId }; }); }, /** * Initializes the container. This method must be called before performing * any other actions in the container. * @method init * @param {F2.ContainerConfig} config The configuration object */ init: function(config) { _config = config || {}; _validateContainerConfig(); _hydrateContainerConfig(_config); // dictates whether we use the old logic or the new logic. // TODO: Remove in v2.0 _bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed); // only establish RPC connection if the container supports the secure app page if ( !! _config.secureAppPagePath || _config.isSecureAppPage) { F2.Rpc.init( !! _config.secureAppPagePath ? _config.secureAppPagePath : false); } F2.UI.init(_config); if (!_config.isSecureAppPage) { _initContainerEvents(); } }, /** * Has the container been init? * @method isInit * @return {bool} True if the container has been init */ isInit: _isInit, /** * Begins the loading process for all apps and/or initialization process for pre-loaded apps. * The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will * contain the app's unique instanceId within the container. If the * {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered * to be a pre-loaded app and will be handled accordingly. Optionally, the * {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those * assets will be used instead of making a request. * @method registerApps * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {Array} [appManifests] An array of * {{#crossLink "F2.AppManifest"}}{{/crossLink}} * objects. This array must be the same length as the apps array that is * objects. This array must be the same length as the apps array that is * passed in. This can be useful if apps are loaded on the server-side and * passed down to the client. * @example * Traditional App requests. * * // Traditional f2 app configs * var arConfigs = [ * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app2', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Pre-loaded and tradition apps mixed. * * // Pre-loaded apps and traditional f2 app configs * // you can preload the same app multiple times as long as you have a unique root for each * var arConfigs = [ * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-1', * manifestUrl: '' * }, * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-2', * manifestUrl: '' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Apps with predefined manifests. * * // Traditional f2 app configs * var arConfigs = [ * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app2', context: {}} * ]; * * // Pre requested manifest responses * var arManifests = [ * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App 2!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/App2Class.js'], * styles: ['http://www.domain.com/css/App2Styles.css'] * } * ]; * * F2.init(); * F2.registerApps(arConfigs, arManifests); */ registerApps: function(appConfigs, appManifests) { if (!_isInit()) { F2.log('F2.init() must be called before F2.registerApps()'); return; } else if (!appConfigs) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; } var appStack = []; var batches = {}; var callbackStack = {}; var haveManifests = false; appConfigs = [].concat(appConfigs); appManifests = [].concat(appManifests || []); haveManifests = !! appManifests.length; // appConfigs must have a length if (!appConfigs.length) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; // ensure that the array of apps and manifests are qual } else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) { F2.log('The length of "apps" does not equal the length of "appManifests"'); return; } // validate each app and assign it an instanceId // then determine which apps can be batched together jQuery.each(appConfigs, function(i, a) { // add properties and methods a = _createAppConfig(a); // Will set to itself, for preloaded apps, or set to null for apps that aren't already // on the page. a.root = a.root || null; // we validate the app after setting the root property because pre-load apps do no require // manifest url if (!_validateApp(a)) { return; // move to the next app } // save app _apps[a.instanceId] = { config: a }; // If the root property is defined then this app is considered to be preloaded and we will // run it through that logic. if (a.root) { if ((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) { F2.log('AppConfig invalid for pre-load, not a valid string and not dom node'); F2.log('AppConfig instance:', a); throw ('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.'); } else if (jQuery(a.root).length != 1) { F2.log('AppConfig invalid for pre-load, root not unique'); F2.log('AppConfig instance:', a); F2.log('Number of dom node instances:', jQuery(a.root).length); throw ('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.'); } // instantiate F2.App _createAppInstance(a); // init events _initAppEvents(a); // Continue on in the .each loop, no need to continue because the app is on the page // the js in initialized, and it is ready to role. return; // equivalent to continue in .each } if (!_bUsesAppHandlers) { // fire beforeAppRender a.root = _beforeAppRender(a); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_CREATE_ROOT, a // the app config ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_BEFORE, a // the app config ); } // if we have the manifest, go ahead and load the app if (haveManifests) { _loadApps(a, appManifests[i]); } else { // check if this app can be batched if (a.enableBatchRequests && !a.isSecure) { batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || []; batches[a.manifestUrl.toLowerCase()].push(a); } else { appStack.push({ apps: [a], url: a.manifestUrl }); } } }); // we don't have the manifests, go ahead and load them if (!haveManifests) { // add the batches to the appStack jQuery.each(batches, function(i, b) { appStack.push({ url: i, apps: b }); }); // if an app is being loaded more than once on the page, there is the // potential that the jsonp callback will be clobbered if the request // for the AppManifest for the app comes back at the same time as // another request for the same app. We'll create a callbackStack // that will ensure that requests for the same app are loaded in order // rather than at the same time jQuery.each(appStack, function(i, req) { // define the callback function based on the first app's App ID var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId; // push the request onto the callback stack callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || []; callbackStack[jsonpCallback].push(req); }); // loop through each item in the callback stack and make the request // for the AppManifest. When the request is complete, pop the next // request off the stack and make the request. jQuery.each(callbackStack, function(i, requests) { var manifestRequest = function(jsonpCallback, req) { if (!req) { return; } // setup defaults and callbacks var url = req.url, type = 'GET', dataType = 'jsonp', completeFunc = function() { manifestRequest(i, requests.pop()); }, errorFunc = function() { jQuery.each(req.apps, function(idx, item) { F2.log('Removed failed ' + item.name + ' app', item); F2.removeApp(item.instanceId); }); }, successFunc = function(appManifest) { _loadApps(req.apps, appManifest); }; // optionally fire xhr overrides if (_config.xhr && _config.xhr.dataType) { dataType = _config.xhr.dataType(req.url, req.apps); if (typeof dataType !== 'string') { throw ('ContainerConfig.xhr.dataType should return a string'); } } if (_config.xhr && _config.xhr.type) { type = _config.xhr.type(req.url, req.apps); if (typeof type !== 'string') { throw ('ContainerConfig.xhr.type should return a string'); } } if (_config.xhr && _config.xhr.url) { url = _config.xhr.url(req.url, req.apps); if (typeof url !== 'string') { throw ('ContainerConfig.xhr.url should return a string'); } } // setup the default request function if an override is not present var requestFunc = _config.xhr; if (typeof requestFunc !== 'function') { requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) { jQuery.ajax({ url: url, type: type, data: { params: F2.stringify(req.apps, F2.appConfigReplacer) }, jsonp: false, // do not put 'callback=' in the query string jsonpCallback: jsonpCallback, // Unique function name dataType: dataType, success: successCallback, error: function(jqxhr, settings, exception) { F2.log('Failed to load app(s)', exception.toString(), req.apps); errorCallback(); }, complete: completeCallback }); }; } requestFunc(url, req.apps, successFunc, errorFunc, completeFunc); }; manifestRequest(i, requests.pop()); }); } }, /** * Removes all apps from the container * @method removeAllApps */ removeAllApps: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeAllApps()'); return; } jQuery.each(_apps, function(i, a) { F2.removeApp(a.config.instanceId); }); }, /** * Removes an app from the container * @method removeApp * @param {string} instanceId The app's instanceId */ removeApp: function(instanceId) { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeApp()'); return; } if (_apps[instanceId]) { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_BEFORE, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_AFTER, _apps[instanceId] // the app instance ); delete _apps[instanceId]; } } }; })()); exports.F2 = F2; if (typeof define !== 'undefined' && define.amd) { define(function() { return F2; }); } })(typeof exports !== 'undefined' ? exports : window);
docs/src/sections/ProgressBarSection.js
egauci/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function ProgressBarSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="progress">Progress bars</Anchor> <small>ProgressBar</small> </h2> <p className="lead">Provide up-to-date feedback on the progress of a workflow or action with simple yet flexible progress bars.</p> <h2><Anchor id="progress-basic">Basic example</Anchor></h2> <p>Default progress bar.</p> <ReactPlayground codeText={Samples.ProgressBarBasic} /> <h2><Anchor id="progress-label">With label</Anchor></h2> <p>Add a <code>label</code> prop to show a visible percentage. For low percentages, consider adding a min-width to ensure the label's text is fully visible.</p> <p>The following keys are interpolated with the current values: <code>%(min)s</code>, <code>%(max)s</code>, <code>%(now)s</code>, <code>%(percent)s</code>, <code>%(bsStyle)s</code></p> <ReactPlayground codeText={Samples.ProgressBarWithLabel} /> <h2><Anchor id="progress-screenreader-label">Screenreader only label</Anchor></h2> <p>Add a <code>srOnly</code> prop to hide the label visually.</p> <ReactPlayground codeText={Samples.ProgressBarScreenreaderLabel} /> <h2><Anchor id="progress-contextual">Contextual alternatives</Anchor></h2> <p>Progress bars use some of the same button and alert classes for consistent styles.</p> <ReactPlayground codeText={Samples.ProgressBarContextual} /> <h2><Anchor id="progress-striped">Striped</Anchor></h2> <p>Uses a gradient to create a striped effect. Not available in IE8.</p> <ReactPlayground codeText={Samples.ProgressBarStriped} /> <h2><Anchor id="progress-animated">Animated</Anchor></h2> <p>Add <code>active</code> prop to animate the stripes right to left. Not available in IE9 and below.</p> <ReactPlayground codeText={Samples.ProgressBarAnimated} /> <h2><Anchor id="progress-stacked">Stacked</Anchor></h2> <p>Nest <code>&lt;ProgressBar /&gt;</code>s to stack them.</p> <ReactPlayground codeText={Samples.ProgressBarStacked} /> <h3><Anchor id="progress-props">ProgressBar</Anchor></h3> <PropTable component="ProgressBar"/> </div> ); }
app/javascript/mastodon/features/list_editor/index.js
summoners-riftodon/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { injectIntl } from 'react-intl'; import { setupListEditor, clearListSuggestions, resetListEditor } from '../../actions/lists'; import Account from './components/account'; import Search from './components/search'; import Motion from '../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; const mapStateToProps = state => ({ title: state.getIn(['listEditor', 'title']), accountIds: state.getIn(['listEditor', 'accounts', 'items']), searchAccountIds: state.getIn(['listEditor', 'suggestions', 'items']), }); const mapDispatchToProps = dispatch => ({ onInitialize: listId => dispatch(setupListEditor(listId)), onClear: () => dispatch(clearListSuggestions()), onReset: () => dispatch(resetListEditor()), }); @connect(mapStateToProps, mapDispatchToProps) @injectIntl export default class ListEditor extends ImmutablePureComponent { static propTypes = { listId: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, onInitialize: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, onReset: PropTypes.func.isRequired, title: PropTypes.string.isRequired, accountIds: ImmutablePropTypes.list.isRequired, searchAccountIds: ImmutablePropTypes.list.isRequired, }; componentDidMount () { const { onInitialize, listId } = this.props; onInitialize(listId); } componentWillUnmount () { const { onReset } = this.props; onReset(); } render () { const { title, accountIds, searchAccountIds, onClear } = this.props; const showSearch = searchAccountIds.size > 0; return ( <div className='modal-root__modal list-editor'> <h4>{title}</h4> <Search /> <div className='drawer__pager'> <div className='drawer__inner list-editor__accounts'> {accountIds.map(accountId => <Account key={accountId} accountId={accountId} added />)} </div> {showSearch && <div role='button' tabIndex='-1' className='drawer__backdrop' onClick={onClear} />} <Motion defaultStyle={{ x: -100 }} style={{ x: spring(showSearch ? 0 : -100, { stiffness: 210, damping: 20 }) }}> {({ x }) => ( <div className='drawer__inner backdrop' style={{ transform: x === 0 ? null : `translateX(${x}%)`, visibility: x === -100 ? 'hidden' : 'visible' }}> {searchAccountIds.map(accountId => <Account key={accountId} accountId={accountId} />)} </div> )} </Motion> </div> </div> ); } }
packages/material-ui-icons/src/GraphicEqTwoTone.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M7 18h2V6H7v12zm4 4h2V2h-2v20zm-8-8h2v-4H3v4zm12 4h2V6h-2v12zm4-8v4h2v-4h-2z" /> , 'GraphicEqTwoTone');
NativeBaseDemo/demo/HomeScreen.js
MisterZhouZhou/ReactNativeLearing
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import {StyleSheet, Text, View, ListView, TouchableOpacity} from 'react-native'; export default class HomeScreen extends Component { constructor(props){ super(props); this.ds = new ListView.DataSource({rowHasChanged:(r1,r2)=>r1 != r2}); this.state = { dataSource:this.ds.cloneWithRows([]) } } componentDidMount(){ let cell = [ 'Drawer', 'Drawer1' ]; this.setState({dataSource:this.ds.cloneWithRows(cell)}); } onCellPress(rowData){ this.props.navigation.navigate(rowData); } render() { return ( <ListView style={{flex: 1}} dataSource={this.state.dataSource} renderRow={this._renderRow.bind(this)} enableEmptySections={true} /> ); } _renderRow(rowData){ return( <TouchableOpacity style={{backgroundColor: 'lightgray', padding: 10, marginTop: 10}} onPress={this.onCellPress.bind(this,rowData)}> <Text>{rowData}</Text> </TouchableOpacity> ); } }
ajax/libs/forerunnerdb/1.3.602/fdb-legacy.js
dannyxx001/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), CollectionGroup = _dereq_('../lib/CollectionGroup'), View = _dereq_('../lib/View'), Highchart = _dereq_('../lib/Highchart'), Persist = _dereq_('../lib/Persist'), Document = _dereq_('../lib/Document'), Overview = _dereq_('../lib/Overview'), OldView = _dereq_('../lib/OldView'), OldViewBind = _dereq_('../lib/OldView.Bind'), Grid = _dereq_('../lib/Grid'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[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":33,"./Shared":39}],3:[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":33,"./Shared":39}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Crc, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, joinMatchData, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { 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, resultArr[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 resultCollectionName = 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, resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], 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: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; case '2d': index = new Index2d(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":7,"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],5:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":4,"./Shared":39}],6:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],7:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],8:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[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 + '"'); } } }; /** * 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. * @func document * @memberof Db * @param {String} documentName The name of the document to create. * @returns {*} */ Db.prototype.document = function (documentName) { if (documentName) { // Handle being passed an instance if (documentName instanceof FdbDocument) { if (documentName.state() !== 'droppped') { return documentName; } else { documentName = documentName.name(); } } this._document = this._document || {}; this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this); return this._document[documentName]; } 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":4,"./Shared":39}],10:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],11:[function(_dereq_,module,exports){ "use strict"; // 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>&nbsp;All', '</a>', '</li>', '<li role="presentation" class="divider"></li>', '{^{for options}}', '<li role="presentation" data-link="data-val{:' + filterField + '}">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox">&nbsp;{^{:' + filterField + '}}', '</a>', '</li>', '{{/for}}' ].join('') }, { $wrap: 'options' }); elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) { var elem = window.jQuery(this), query = filterView.query(), search = elem.val(); if (search) { query[filterField] = new RegExp(search, 'gi'); } else { delete query[filterField]; } filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) { // Clear search text box window.jQuery(this).parents('li').find('.gridFilterSearch').val(''); // Clear view query var query = filterView.query(); delete query[filterField]; filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) { e.stopPropagation(); var fieldValue, elem = $(this), checkbox = elem.find('input[type="checkbox"]'), checked, addMode = true, fieldInArr, liElem, i; // If the checkbox is not the one clicked on if (!window.jQuery(e.target).is('input')) { // Set checkbox to opposite of current value checkbox.prop('checked', !checkbox.prop('checked')); checked = checkbox.is(':checked'); } else { checkbox.prop('checked', checkbox.prop('checked')); checked = checkbox.is(':checked'); } liElem = window.jQuery(this); fieldValue = liElem.attr('data-val'); // Check if the selection is the "all" option if (fieldValue === '$all') { // Remove the field from the query delete queryObj[filterField]; // Clear all other checkboxes liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false); } else { // Clear the "all" checkbox liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false); // Check if the type needs casting switch (filterVarType) { case 'integer': fieldValue = parseInt(fieldValue, 10); break; case 'float': fieldValue = parseFloat(fieldValue); break; default: } // Check if the item exists already queryObj[filterField] = queryObj[filterField] || { $in: [] }; fieldInArr = queryObj[filterField].$in; for (i = 0; i < fieldInArr.length; i++) { if (fieldInArr[i] === fieldValue) { // Item already exists if (checked === false) { // Remove the item fieldInArr.splice(i, 1); } addMode = false; break; } } if (addMode && checked) { fieldInArr.push(fieldValue); } if (!fieldInArr.length) { // Remove the field from the query delete queryObj[filterField]; } } // Set the view query self._from.queryData(queryObj); if (self._from.pageFirst) { self._from.pageFirst(); } }); }); } self.emit('refresh'); } else { throw('Grid requires the AutoBind module in order to operate!'); } } return this; }; /** * Returns the number of documents currently in the grid. * @func count * @memberof Grid * @returns {Number} */ Grid.prototype.count = function () { return this._from.count(); }; /** * Creates a grid and assigns the collection as its data source. * @func grid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.grid = View.prototype.grid = function (selector, template, options) { if (this._db && this._db._grid ) { if (selector !== undefined) { if (template !== undefined) { if (!this._db._grid[selector]) { var grid = new Grid(selector, template, options) .db(this._db) .from(this); this._grid = this._grid || []; this._grid.push(grid); this._db._grid[selector] = grid; return grid; } else { throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector); } } return this._db._grid[selector]; } return this._db._grid; } }; /** * Removes a grid safely from the DOM. Must be called when grid is * no longer required / is being removed from DOM otherwise references * will stick around and cause memory leaks. * @func unGrid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) { var i, grid; if (this._db && this._db._grid ) { if (selector && template) { if (this._db._grid[selector]) { grid = this._db._grid[selector]; delete this._db._grid[selector]; return grid.drop(); } else { throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name); } } else { // No parameters passed, remove all grids from this module for (i in this._db._grid) { if (this._db._grid.hasOwnProperty(i)) { grid = this._db._grid[i]; delete this._db._grid[i]; grid.drop(); if (this.debug()) { console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"'); } } } this._db._grid = {}; } } }; /** * Adds a grid to the internal grid lookup. * @func _addGrid * @memberof Collection * @param {Grid} grid The grid to add. * @returns {Collection} * @private */ Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) { if (grid !== undefined) { this._grid = this._grid || []; this._grid.push(grid); } return this; }; /** * Removes a grid from the internal grid lookup. * @func _removeGrid * @memberof Collection * @param {Grid} grid The grid to remove. * @returns {Collection} * @private */ Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) { if (grid !== undefined && this._grid) { var index = this._grid.indexOf(grid); if (index > -1) { this._grid.splice(index, 1); } } return this; }; // Extend DB with grids init Db.prototype.init = function () { this._grid = {}; DbInit.apply(this, arguments); }; /** * Determine if a grid with the passed name already exists. * @func gridExists * @memberof Db * @param {String} selector The jQuery selector to bind the grid to. * @returns {boolean} */ Db.prototype.gridExists = function (selector) { return Boolean(this._grid[selector]); }; /** * Creates a grid based on the passed arguments. * @func grid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.grid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Removes a grid based on the passed arguments. * @func unGrid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.unGrid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Returns an array of grids the DB currently has. * @func grids * @memberof Db * @returns {Array} An array of objects containing details of each grid * the database is currently managing. */ Db.prototype.grids = function () { var arr = [], item, i; for (i in this._grid) { if (this._grid.hasOwnProperty(i)) { item = this._grid[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Grid'); module.exports = Grid; },{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[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":31,"./Shared":39}],13:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":33,"./Shared":39}],16:[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":39}],17:[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":30,"./Shared":39}],18:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],19:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, data, options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],20:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":31,"./Serialiser":38}],21:[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; },{}],22:[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":31}],23:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],24:[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; },{}],25:[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; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":31}],27:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],28:[function(_dereq_,module,exports){ "use strict"; // Grab the view class var Shared, Core, OldView, OldViewInit; Shared = _dereq_('./Shared'); Core = Shared.modules.Core; OldView = Shared.modules.OldView; OldViewInit = OldView.prototype.init; OldView.prototype.init = function () { var self = this; this._binds = []; this._renderStart = 0; this._renderEnd = 0; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], _bindInsert: [], _bindUpdate: [], _bindRemove: [], _bindUpsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100, _bindInsert: 100, _bindUpdate: 100, _bindRemove: 100, _bindUpsert: 100 }; this._deferTime = { insert: 100, update: 1, remove: 1, upsert: 1, _bindInsert: 100, _bindUpdate: 1, _bindRemove: 1, _bindUpsert: 1 }; OldViewInit.apply(this, arguments); // Hook view events to update binds this.on('insert', function (successArr, failArr) { self._bindEvent('insert', successArr, failArr); }); this.on('update', function (successArr, failArr) { self._bindEvent('update', successArr, failArr); }); this.on('remove', function (successArr, failArr) { self._bindEvent('remove', successArr, failArr); }); this.on('change', self._bindChange); }; /** * Binds a selector to the insert, update and delete events of a particular * view and keeps the selector in sync so that updates are reflected on the * web page in real-time. * * @param {String} selector The jQuery selector string to get target elements. * @param {Object} options The options object. */ OldView.prototype.bind = function (selector, options) { if (options && options.template) { this._binds[selector] = options; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!'); } return this; }; /** * Un-binds a selector from the view changes. * @param {String} selector The jQuery selector string to identify the bind to remove. * @returns {Collection} */ OldView.prototype.unBind = function (selector) { delete this._binds[selector]; return this; }; /** * Returns true if the selector is bound to the view. * @param {String} selector The jQuery selector string to identify the bind to check for. * @returns {boolean} */ OldView.prototype.isBound = function (selector) { return Boolean(this._binds[selector]); }; /** * Sorts items in the DOM based on the bind settings and the passed item array. * @param {String} selector The jQuery selector of the bind container. * @param {Array} itemArr The array of items used to determine the order the DOM * elements should be in based on the order they are in, in the array. */ OldView.prototype.bindSortDom = function (selector, itemArr) { var container = window.jQuery(selector), arrIndex, arrItem, domItem; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr); } for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) { arrItem = itemArr[arrIndex]; // Now we've done our inserts into the DOM, let's ensure // they are still ordered correctly domItem = container.find('#' + arrItem[this._primaryKey]); if (domItem.length) { if (arrIndex === 0) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem); } container.prepend(domItem); } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem); } domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')')); } } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem); } } } }; OldView.prototype.bindRefresh = function (obj) { var binds = this._binds, bindKey, bind; if (!obj) { // Grab current data obj = { data: this.find() }; } for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { bind = binds[bindKey]; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); } this.bindSortDom(bindKey, obj.data); if (bind.afterOperation) { bind.afterOperation(); } if (bind.refresh) { bind.refresh(); } } } }; /** * Renders a bind view data to the DOM. * @param {String} bindSelector The jQuery selector string to use to identify * the bind target. Must match the selector used when defining the original bind. * @param {Function=} domHandler If specified, this handler method will be called * with the final HTML for the view instead of the DB handling the DOM insertion. */ OldView.prototype.bindRender = function (bindSelector, domHandler) { // Check the bind exists var bind = this._binds[bindSelector], domTarget = window.jQuery(bindSelector), allData, dataItem, itemHtml, finalHtml = window.jQuery('<ul></ul>'), bindCallback, i; if (bind) { allData = this._data.find(); bindCallback = function (itemHtml) { finalHtml.append(itemHtml); }; // Loop all items and add them to the screen for (i = 0; i < allData.length; i++) { dataItem = allData[i]; itemHtml = bind.template(dataItem, bindCallback); } if (!domHandler) { domTarget.append(finalHtml.html()); } else { domHandler(bindSelector, finalHtml.html()); } } }; OldView.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { 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); } this._bindEvent(type, dataArr, []); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { callback(); } this.emit('bindQueueComplete'); } }; OldView.prototype._bindEvent = function (type, successArr, failArr) { /*var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type];*/ var binds = this._binds, unfilteredDataSet = this.find({}), filteredDataSet, bindKey; // Check if the number of inserts is greater than the defer threshold /*if (successArr && successArr.length > deferThreshold) { // Break up upsert into blocks this._deferQueue[type] = queue.concat(successArr); // Fire off the insert queue handler this.processQueue(type); return; } else {*/ for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { if (binds[bindKey].reduce) { filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options); } else { filteredDataSet = unfilteredDataSet; } switch (type) { case 'insert': this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'update': this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'remove': this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; } } } //} }; OldView.prototype._bindChange = function (newDataArr) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr); } this.bindRefresh(newDataArr); }; OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, itemHtml, makeCallback, i; makeCallback = function (itemElem, insertedItem, failArr, all) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.insert) { options.insert(itemHtml, insertedItem, failArr, all); } else { // Handle the insert automatically // Add the item to the container if (options.prependInsert) { container.prepend(itemHtml); } else { container.append(itemHtml); } } if (options.afterInsert) { options.afterInsert(itemHtml, insertedItem, failArr, all); } }; }; // Loop the inserted items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (!itemElem.length) { itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all)); } } }; OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, itemData) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.update) { options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append'); } else { if (itemElem.length) { // An existing item is in the container, replace it with the // new rendered item from the updated data itemElem.replaceWith(itemHtml); } else { // The item element does not already exist, append it if (options.prependUpdate) { container.prepend(itemHtml); } else { container.append(itemHtml); } } } if (options.afterUpdate) { options.afterUpdate(itemHtml, itemData, all); } }; }; // Loop the updated items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); options.template(successArr[i], makeCallback(itemElem, successArr[i])); } }; OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, data, all) { return function () { if (options.remove) { options.remove(itemElem, data, all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, data, all); } } }; }; // Loop the removed items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (itemElem.length) { if (options.beforeRemove) { options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all)); } else { if (options.remove) { options.remove(itemElem, successArr[i], all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, successArr[i], all); } } } } } }; },{"./Shared":39}],29:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, CollectionGroup, Collection, CollectionInit, CollectionGroupInit, DbInit; Shared = _dereq_('./Shared'); /** * The view constructor. * @param viewName * @constructor */ var OldView = function (viewName) { this.init.apply(this, arguments); }; OldView.prototype.init = function (viewName) { var self = this; this._name = viewName; this._listeners = {}; this._query = { query: {}, options: {} }; // Register listeners for the CRUD events this._onFromSetData = function () { self._onSetData.apply(self, arguments); }; this._onFromInsert = function () { self._onInsert.apply(self, arguments); }; this._onFromUpdate = function () { self._onUpdate.apply(self, arguments); }; this._onFromRemove = function () { self._onRemove.apply(self, arguments); }; this._onFromChange = function () { if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); } self._onChange.apply(self, arguments); }; }; Shared.addModule('OldView', OldView); CollectionGroup = _dereq_('./CollectionGroup'); Collection = _dereq_('./Collection'); CollectionInit = Collection.prototype.init; CollectionGroupInit = CollectionGroup.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Shared.mixin(OldView.prototype, 'Mixin.Events'); /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ OldView.prototype.drop = function () { if ((this._db || this._from) && this._name) { if (this.debug()) { console.log('ForerunnerDB.OldView: Dropping view ' + this._name); } this._state = 'dropped'; this.emit('drop', this); if (this._db && this._db._oldViews) { delete this._db._oldViews[this._name]; } if (this._from && this._from._oldViews) { delete this._from._oldViews[this._name]; } delete this._listeners; return true; } return false; }; OldView.prototype.debug = function () { // TODO: Make this function work return false; }; /** * Gets / sets the DB the view is bound against. Automatically set * when the db.oldView(viewName) method is called. * @param db * @returns {*} */ OldView.prototype.db = function (db) { if (db !== undefined) { this._db = db; return this; } return this._db; }; /** * Gets / sets the collection that the view derives it's data from. * @param {*} collection A collection instance or the name of a collection * to use as the data set to derive view data from. * @returns {*} */ OldView.prototype.from = function (collection) { if (collection !== undefined) { // Check if this is a collection name or a collection instance if (typeof(collection) === 'string') { if (this._db.collectionExists(collection)) { collection = this._db.collection(collection); } else { throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.'); } } // Check if the existing from matches the passed one if (this._from !== collection) { // Check if we already have a collection assigned if (this._from) { // Remove ourselves from the collection view lookup this.removeFrom(); } this.addFrom(collection); } return this; } return this._from; }; OldView.prototype.addFrom = function (collection) { //var self = this; this._from = collection; if (this._from) { this._from.on('setData', this._onFromSetData); //this._from.on('insert', this._onFromInsert); //this._from.on('update', this._onFromUpdate); //this._from.on('remove', this._onFromRemove); this._from.on('change', this._onFromChange); // Add this view to the collection's view lookup this._from._addOldView(this); this._primaryKey = this._from._primaryKey; this.refresh(); return this; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()'); } }; OldView.prototype.removeFrom = function () { // Unsubscribe from events on this "from" this._from.off('setData', this._onFromSetData); //this._from.off('insert', this._onFromInsert); //this._from.off('update', this._onFromUpdate); //this._from.off('remove', this._onFromRemove); this._from.off('change', this._onFromChange); this._from._removeOldView(this); }; /** * Gets the primary key for this view from the assigned collection. * @returns {String} */ OldView.prototype.primaryKey = function () { if (this._from) { return this._from.primaryKey(); } return undefined; }; /** * Gets / sets the query that the view uses to build it's data set. * @param {Object=} query * @param {Boolean=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._query.query = query; } if (options !== undefined) { this._query.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query; }; /** * 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. */ OldView.prototype.queryAdd = function (obj, overwrite, refresh) { var query = this._query.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)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ OldView.prototype.queryRemove = function (obj, refresh) { var query = this._query.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Gets / sets the query being used to generate the view data. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.query = function (query, refresh) { if (query !== undefined) { this._query.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.query; }; /** * 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 {*} */ OldView.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._query.options = options; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.options; }; /** * Refreshes the view data and diffs between previous and new data to * determine if any events need to be triggered or DOM binds updated. */ OldView.prototype.refresh = function (force) { if (this._from) { // Take a copy of the data before updating it, we will use this to // "diff" between the old and new data and handle DOM bind updates var oldData = this._data, oldDataArr, oldDataItem, newData, newDataArr, query, primaryKey, dataItem, inserted = [], updated = [], removed = [], operated = false, i; if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing view ' + this._name); console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined")); if (typeof(this._data) !== "undefined") { console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length); } //console.log(OldView.prototype.refresh.caller); } // Query the collection and update the data if (this._query) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has query and options, getting subset...'); } // Run query against collection //console.log('refresh with query and options', this._query.options); this._data = this._from.subset(this._query.query, this._query.options); //console.log(this._data); } else { // No query, return whole collection if (this._query.options) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has options, getting subset...'); } this._data = this._from.subset({}, this._query.options); } else { if (this.debug()) { console.log('ForerunnerDB.OldView: View has no query or options, getting subset...'); } this._data = this._from.subset({}); } } // Check if there was old data if (!force && oldData) { if (this.debug()) { console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...'); } // Now determine the difference newData = this._data; if (oldData.subsetOf() === newData.subsetOf()) { if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from same collection...'); } newDataArr = newData.find(); oldDataArr = oldData.find(); primaryKey = newData._primaryKey; // The old data and new data were derived from the same parent collection // so scan the data to determine changes for (i = 0; i < newDataArr.length; i++) { dataItem = newDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data oldDataItem = oldData.find(query)[0]; if (!oldDataItem) { // New item detected inserted.push(dataItem); } else { // Check if an update has occurred if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) { // Updated / already included item detected updated.push(dataItem); } } } // Now loop the old data and check if any records were removed for (i = 0; i < oldDataArr.length; i++) { dataItem = oldDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data if (!newData.find(query)[0]) { // Removed item detected removed.push(dataItem); } } if (this.debug()) { console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows'); console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows'); console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows'); } // Now we have a diff of the two data sets, we need to get the DOM updated if (inserted.length) { this._onInsert(inserted, []); operated = true; } if (updated.length) { this._onUpdate(updated, []); operated = true; } if (removed.length) { this._onRemove(removed, []); operated = true; } } else { // The previous data and the new data are derived from different collections // and can therefore not be compared, all data is therefore effectively "new" // so first perform a remove of all existing data then do an insert on all new data if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from different collections...'); } removed = oldData.find(); if (removed.length) { this._onRemove(removed); operated = true; } inserted = newData.find(); if (inserted.length) { this._onInsert(inserted); operated = true; } } } else { // Force an update as if the view never got created by padding all elements // to the insert if (this.debug()) { console.log('ForerunnerDB.OldView: Forcing data update', newDataArr); } this._data = this._from.subset(this._query.query, this._query.options); newDataArr = this._data.find(); if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr); } this._onInsert(newDataArr, []); } if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); } this.emit('change'); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ OldView.prototype.count = function () { return this._data && this._data._data ? this._data._data.length : 0; }; /** * Queries the view data. See Collection.find() for more information. * @returns {*} */ OldView.prototype.find = function () { if (this._data) { if (this.debug()) { console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data); } return this._data.find.apply(this._data, arguments); } else { return []; } }; /** * Inserts into view data via the view collection. See Collection.insert() for more information. * @returns {*} */ OldView.prototype.insert = function () { if (this._from) { // Pass the args through to the from object return this._from.insert.apply(this._from, arguments); } else { return []; } }; /** * Updates into view data via the view collection. See Collection.update() for more information. * @returns {*} */ OldView.prototype.update = function () { if (this._from) { // Pass the args through to the from object return this._from.update.apply(this._from, arguments); } else { return []; } }; /** * Removed from view data via the view collection. See Collection.remove() for more information. * @returns {*} */ OldView.prototype.remove = function () { if (this._from) { // Pass the args through to the from object return this._from.remove.apply(this._from, arguments); } else { return []; } }; OldView.prototype._onSetData = function (newDataArr, oldDataArr) { this.emit('remove', oldDataArr, []); this.emit('insert', newDataArr, []); //this.refresh(); }; OldView.prototype._onInsert = function (successArr, failArr) { this.emit('insert', successArr, failArr); //this.refresh(); }; OldView.prototype._onUpdate = function (successArr, failArr) { this.emit('update', successArr, failArr); //this.refresh(); }; OldView.prototype._onRemove = function (successArr, failArr) { this.emit('remove', successArr, failArr); //this.refresh(); }; OldView.prototype._onChange = function () { if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); } this.refresh(); }; // Extend collection with view init Collection.prototype.init = function () { this._oldViews = []; CollectionInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend collection with view init CollectionGroup.prototype.init = function () { this._oldViews = []; CollectionGroupInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ CollectionGroup.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ CollectionGroup.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend DB with views init Db.prototype.init = function () { this._oldViews = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.oldView = function (viewName) { if (!this._oldViews[viewName]) { if (this.debug()) { console.log('ForerunnerDB.OldView: Creating view ' + viewName); } } this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this); return this._oldViews[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.oldViewExists = function (viewName) { return Boolean(this._oldViews[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.oldViews = function () { var arr = [], i; for (i in this._oldViews) { if (this._oldViews.hasOwnProperty(i)) { arr.push({ name: i, count: this._oldViews[i].count() }); } } return arr; }; Shared.finishModule('OldView'); module.exports = OldView; },{"./Collection":4,"./CollectionGroup":5,"./Shared":39}],30:[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":33,"./Shared":39}],31:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],32:[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]; } delete this._name; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; } return true; }; Db.prototype.overview = function (overviewName) { if (overviewName) { // Handle being passed an instance if (overviewName instanceof Overview) { return overviewName; } this._overview = this._overview || {}; this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this); return this._overview[overviewName]; } 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":4,"./Document":9,"./Shared":39}],33:[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":39}],34:[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; } else { meta.foundData = false; } 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; } else { meta.foundData = false; } 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) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { 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":4,"./CollectionGroup":5,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,"async":41,"localforage":77}],35:[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":39,"pako":78}],36:[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":39,"crypto-js":50}],37:[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":39}],38:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Handler for Date() objects this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); // Handler for RegExp() objects this.registerEncoder('$regexp', function (data) { if (data instanceof RegExp) { return { source: data.source, params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '') }; } }); this.registerDecoder('$regexp', function (data) { var type = typeof data; if (type === 'object') { return new RegExp(data.source, data.params); } else if (type === 'string') { return new RegExp(data); } }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],39:[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.602', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'); Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection(this.name() + '_internalPrivate'); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this.publicData().findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this.publicData().findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } // Check if we have an existing reactor io if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } if (typeof(source) === 'string') { source = this._db.collection(source); } if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } this._from = source; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" source and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(source, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check that the state of the "self" object is not dropped if (self && !self.isDropped()) { // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = source.find(this._querySettings.query, this._querySettings.options); this._privateData.primaryKey(source.primaryKey()); this._privateData.setData(collData, {}, callback); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data'); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"'); } this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._privateData.on.apply(this._privateData, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._privateData.off.apply(this._privateData, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { var coll = this.publicData(); return coll.distinct.apply(coll, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this.publicData().primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._publicData && this._publicData !== this._privateData) { this._publicData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this.privateData().db(db); this.publicData().db(db); // Apply the same debug settings this.debug(db.debug()); this.privateData().debug(db.debug()); this.publicData().debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._privateData.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._privateData.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this._querySettings.query; }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._privateData.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._privateData.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); //pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { if (this.publicData()) { return this.publicData().count.apply(this.publicData(), arguments); } return 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var self = this; if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } if (this._transformEnabled) { // Check for / create the public data collection if (!this._publicData) { // Create the public data collection this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); // Create a chain reaction IO node to keep the private and // public data collections in sync this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) { var data = chainPacket.data; switch (chainPacket.type) { case 'primaryKey': self._publicData.primaryKey(data); this.chainSend('primaryKey', data); break; case 'setData': self._publicData.setData(data); this.chainSend('setData', data); break; case 'insert': self._publicData.insert(data); this.chainSend('insert', data); break; case 'update': // Do the update self._publicData.update( data.query, data.update, data.options ); this.chainSend('update', data); break; case 'remove': self._publicData.remove(data.query, chainPacket.options); this.chainSend('remove', data); break; default: break; } }); } // Set initial data and settings this._publicData.primaryKey(this.privateData().primaryKey()); this._publicData.setData(this.privateData().find()); } else { // Remove the public data collection if (this._publicData) { this._publicData.drop(); delete this._publicData; if (this._transformIo) { this._transformIo.drop(); delete this._transformIo; } } } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { var self = this; // Handle being passed an instance if (viewName instanceof View) { return viewName; } if (this._view[viewName]) { return this._view[viewName]; } else { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); self.emit('create', [self._view[viewName], 'view', viewName]); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./Overload":31,"./ReactorIO":37,"./Shared":39}],41:[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 (!callback) { // 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 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) { 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; 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 inexistant dependency'); } 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(null); } }); 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 () { if (!q.paused && workers < q.concurrency && q.tasks.length) { while(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 = {}; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { 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":76}],42:[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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[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":44}],44:[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; })); },{}],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) { (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); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":44}],46:[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":44}],47:[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":44,"./hmac":49,"./sha1":68}],48:[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":43,"./core":44}],49:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var 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":44}],50:[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":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],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 () { // 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":44}],52:[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":44}],53:[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":43,"./core":44}],54:[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":43,"./core":44}],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) { /** * 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":43,"./core":44}],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) { /** * 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":43,"./core":44}],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) { /** * 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":43,"./core":44}],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) { /** * 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":43,"./core":44}],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) { /** * 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":43,"./core":44}],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) { /** * 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":43,"./core":44}],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) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":43,"./core":44}],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) { /** * 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":43,"./core":44}],63:[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":44,"./hmac":49,"./sha1":68}],64:[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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],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; /** * 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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[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":44}],68:[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":44}],69:[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":44,"./sha256":70}],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 (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":44}],71:[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":44,"./x64-core":75}],72:[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":44,"./sha512":73,"./x64-core":75}],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 () { // 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":44,"./x64-core":75}],74:[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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[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":44}],76:[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; }; },{}],77:[function(_dereq_,module,exports){ (function (process,global){ /*! localForage -- Offline Storage, Improved Version 1.3.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'); } } (function () { '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 }; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function (self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function () { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function () { try { return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var 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; })(); var localForage = new LocalForage(); exports['default'] = localForage; }).call(typeof window !== 'undefined' ? window : self); 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; (function () { 'use strict'; var globalObject = this; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; 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); }); }; }; })['catch'](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // 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 }; // 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(this); // Create an array of readiness of the related localForages. var readyPromises = []; 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 !== this) { // Don't wait for itself... readyPromises.push(forage.ready()['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(readyPromises).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 in forages) { 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) { 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); }; }); } 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; return _checkBlobSupport(dbInfo.db); }).then(function (blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { 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 }; exports['default'] = asyncStorage; }).call(typeof window !== 'undefined' ? window : self); 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; (function () { 'use strict'; var globalObject = this; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } // 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 }; exports['default'] = localStorageWrapper; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; (function () { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; exports['default'] = localforageSerializer; }).call(typeof window !== 'undefined' ? window : self); 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; (function () { 'use strict'; var globalObject = this; var openDatabase = this.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 self.setDriver(self.LOCALSTORAGE).then(function () { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); return 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 }; exports['default'] = webSQLStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ } /******/ ]) }); ; }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":76}],78:[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":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); 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); * ``` **/ var Deflate = function(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 alrorythm 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":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); 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); * ``` **/ var Inflate = function(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":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[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); },{}],82:[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":81}],83:[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; },{}],84:[function(_dereq_,module,exports){ 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 }; },{}],85:[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 = crc ^ (-1); for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],86:[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. */ var Config = function (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":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[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; },{}],88:[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; }; },{}],89:[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 /*crc32(0L, Z_NULL, 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":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[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":81}],91:[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) */ }; },{}],92:[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) */ 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]; /* 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) */ var StaticTreeDesc = function (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; var TreeDesc = function(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":81}],93:[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; },{}]},{},[1]);
src/scaffold/templates/javascript/src/example.mu.js
willowtreeapps/react-sapling
import React from 'react'; import {{componentName}} from './root'; const ComponentExample = React.createClass({ render() { return <{{componentName}} />; } }); export default ComponentExample;
src/routes/NotFound/NotFound.js
tonyxiao/segment-debugger
import React from 'react' import { browserHistory } from 'react-router' const goBack = (e) => { e.preventDefault() return browserHistory.goBack() } export const NotFound = () => ( <div> <h4>Page not found!</h4> <p><a href='#' onClick={goBack}>&larr; Back</a></p> </div> ) export default NotFound
ajax/libs/dc/2.1.1/dc.js
cdnjs/cdnjs
/*! * dc 2.1.1 * http://dc-js.github.io/dc.js/ * Copyright 2012-2016 Nick Zhu & the dc.js Developers * https://github.com/dc-js/dc.js/blob/master/AUTHORS * * 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() { function _dc(d3, crossfilter) { 'use strict'; /** * The entire dc.js library is scoped under the **dc** name space. It does not introduce * anything else into the global name space. * * Most `dc` functions are designed to allow function chaining, meaning they return the current chart * instance whenever it is appropriate. The getter forms of functions do not participate in function * chaining because they return values that are not the chart, although some, * such as {@link dc.baseMixin#svg .svg} and {@link dc.coordinateGridMixin#xAxis .xAxis}, * return values that are themselves chainable d3 objects. * @namespace dc * @version 2.1.1 * @example * // Example chaining * chart.width(300) * .height(300) * .filter('sunday'); */ /*jshint -W079*/ var dc = { version: '2.1.1', constants: { CHART_CLASS: 'dc-chart', DEBUG_GROUP_CLASS: 'debug', STACK_CLASS: 'stack', DESELECTED_CLASS: 'deselected', SELECTED_CLASS: 'selected', NODE_INDEX_NAME: '__index__', GROUP_INDEX_NAME: '__group_index__', DEFAULT_CHART_GROUP: '__default_chart_group__', EVENT_DELAY: 40, NEGLIGIBLE_NUMBER: 1e-10 }, _renderlet: null }; /*jshint +W079*/ /** * The dc.chartRegistry object maintains sets of all instantiated dc.js charts under named groups * and the default group. * * A chart group often corresponds to a crossfilter instance. It specifies * the set of charts which should be updated when a filter changes on one of the charts or when the * global functions {@link dc.filterAll dc.filterAll}, {@link dc.refocusAll dc.refocusAll}, * {@link dc.renderAll dc.renderAll}, {@link dc.redrawAll dc.redrawAll}, or chart functions * {@link dc.baseMixin#renderGroup baseMixin.renderGroup}, * {@link dc.baseMixin#redrawGroup baseMixin.redrawGroup} are called. * * @namespace chartRegistry * @memberof dc * @type {{has, register, deregister, clear, list}} */ dc.chartRegistry = (function () { // chartGroup:string => charts:array var _chartMap = {}; function initializeChartGroup (group) { if (!group) { group = dc.constants.DEFAULT_CHART_GROUP; } if (!_chartMap[group]) { _chartMap[group] = []; } return group; } return { /** * Determine if a given chart instance resides in any group in the registry. * @method has * @memberof dc.chartRegistry * @param {Object} chart dc.js chart instance * @returns {Boolean} */ has: function (chart) { for (var e in _chartMap) { if (_chartMap[e].indexOf(chart) >= 0) { return true; } } return false; }, /** * Add given chart instance to the given group, creating the group if necessary. * If no group is provided, the default group `dc.constants.DEFAULT_CHART_GROUP` will be used. * @method register * @memberof dc.chartRegistry * @param {Object} chart dc.js chart instance * @param {String} [group] Group name */ register: function (chart, group) { group = initializeChartGroup(group); _chartMap[group].push(chart); }, /** * Remove given chart instance from the given group, creating the group if necessary. * If no group is provided, the default group `dc.constants.DEFAULT_CHART_GROUP` will be used. * @method deregister * @memberof dc.chartRegistry * @param {Object} chart dc.js chart instance * @param {String} [group] Group name */ deregister: function (chart, group) { group = initializeChartGroup(group); for (var i = 0; i < _chartMap[group].length; i++) { if (_chartMap[group][i].anchorName() === chart.anchorName()) { _chartMap[group].splice(i, 1); break; } } }, /** * Clear given group if one is provided, otherwise clears all groups. * @method clear * @memberof dc.chartRegistry * @param {String} group Group name */ clear: function (group) { if (group) { delete _chartMap[group]; } else { _chartMap = {}; } }, /** * Get an array of each chart instance in the given group. * If no group is provided, the charts in the default group are returned. * @method list * @memberof dc.chartRegistry * @param {String} [group] Group name * @returns {Array<Object>} */ list: function (group) { group = initializeChartGroup(group); return _chartMap[group]; } }; })(); /** * Add given chart instance to the given group, creating the group if necessary. * If no group is provided, the default group `dc.constants.DEFAULT_CHART_GROUP` will be used. * @memberof dc * @method registerChart * @param {Object} chart dc.js chart instance * @param {String} [group] Group name */ dc.registerChart = function (chart, group) { dc.chartRegistry.register(chart, group); }; /** * Remove given chart instance from the given group, creating the group if necessary. * If no group is provided, the default group `dc.constants.DEFAULT_CHART_GROUP` will be used. * @memberof dc * @method deregisterChart * @param {Object} chart dc.js chart instance * @param {String} [group] Group name */ dc.deregisterChart = function (chart, group) { dc.chartRegistry.deregister(chart, group); }; /** * Determine if a given chart instance resides in any group in the registry. * @memberof dc * @method hasChart * @param {Object} chart dc.js chart instance * @returns {Boolean} */ dc.hasChart = function (chart) { return dc.chartRegistry.has(chart); }; /** * Clear given group if one is provided, otherwise clears all groups. * @memberof dc * @method deregisterAllCharts * @param {String} group Group name */ dc.deregisterAllCharts = function (group) { dc.chartRegistry.clear(group); }; /** * Clear all filters on all charts within the given chart group. If the chart group is not given then * only charts that belong to the default chart group will be reset. * @memberof dc * @method filterAll * @param {String} [group] */ dc.filterAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].filterAll(); } }; /** * Reset zoom level / focus on all charts that belong to the given chart group. If the chart group is * not given then only charts that belong to the default chart group will be reset. * @memberof dc * @method refocusAll * @param {String} [group] */ dc.refocusAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { if (charts[i].focus) { charts[i].focus(); } } }; /** * Re-render all charts belong to the given chart group. If the chart group is not given then only * charts that belong to the default chart group will be re-rendered. * @memberof dc * @method renderAll * @param {String} [group] */ dc.renderAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].render(); } if (dc._renderlet !== null) { dc._renderlet(group); } }; /** * Redraw all charts belong to the given chart group. If the chart group is not given then only charts * that belong to the default chart group will be re-drawn. Redraw is different from re-render since * when redrawing dc tries to update the graphic incrementally, using transitions, instead of starting * from scratch. * @memberof dc * @method redrawAll * @param {String} [group] */ dc.redrawAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].redraw(); } if (dc._renderlet !== null) { dc._renderlet(group); } }; /** * If this boolean is set truthy, all transitions will be disabled, and changes to the charts will happen * immediately. * @memberof dc * @member disableTransitions * @type {Boolean} * @default false */ dc.disableTransitions = false; /** * Start a transition on a selection if transitions are globally enabled * ({@link dc.disableTransitions} is false) and the duration is greater than zero; otherwise return * the selection. Since most operations are the same on a d3 selection and a d3 transition, this * allows a common code path for both cases. * @memberof dc * @method transition * @param {d3.selection} selection - the selection to be transitioned * @param {Number|Function} [duration=250] - the duration of the transition in milliseconds, a * function returning the duration, or 0 for no transition * @param {Number|Function} [delay] - the delay of the transition in milliseconds, or a function * returning the delay, or 0 for no delay * @param {String} [name] - the name of the transition (if concurrent transitions on the same * elements are needed) * @returns {d3.transition|d3.selection} */ dc.transition = function (selection, duration, delay, name) { if (dc.disableTransitions || duration <= 0) { return selection; } var s = selection.transition(name); if (duration >= 0 || duration !== undefined) { s = s.duration(duration); } if (delay >= 0 || delay !== undefined) { s = s.delay(delay); } return s; }; /* somewhat silly, but to avoid duplicating logic */ dc.optionalTransition = function (enable, duration, delay, name) { if (enable) { return function (selection) { return dc.transition(selection, duration, delay, name); }; } else { return function (selection) { return selection; }; } }; // See http://stackoverflow.com/a/20773846 dc.afterTransition = function (transition, callback) { if (transition.empty() || !transition.duration) { callback.call(transition); } else { var n = 0; transition .each(function () { ++n; }) .each('end', function () { if (!--n) { callback.call(transition); } }); } }; /** * @namespace units * @memberof dc * @type {{}} */ dc.units = {}; /** * The default value for {@link dc.coordinateGridMixin#xUnits .xUnits} for the * {@link dc.coordinateGridMixin Coordinate Grid Chart} and should * be used when the x values are a sequence of integers. * It is a function that counts the number of integers in the range supplied in its start and end parameters. * @method integers * @memberof dc.units * @see {@link dc.coordinateGridMixin#xUnits coordinateGridMixin.xUnits} * @example * chart.xUnits(dc.units.integers) // already the default * @param {Number} start * @param {Number} end * @returns {Number} */ dc.units.integers = function (start, end) { return Math.abs(end - start); }; /** * This argument can be passed to the {@link dc.coordinateGridMixin#xUnits .xUnits} function of the to * specify ordinal units for the x axis. Usually this parameter is used in combination with passing * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md d3.scale.ordinal} to * {@link dc.coordinateGridMixin#x .x}. * It just returns the domain passed to it, which for ordinal charts is an array of all values. * @method ordinal * @memberof dc.units * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md d3.scale.ordinal} * @see {@link dc.coordinateGridMixin#xUnits coordinateGridMixin.xUnits} * @see {@link dc.coordinateGridMixin#x coordinateGridMixin.x} * @example * chart.xUnits(dc.units.ordinal) * .x(d3.scale.ordinal()) * @param {*} start * @param {*} end * @param {Array<String>} domain * @returns {Array<String>} */ dc.units.ordinal = function (start, end, domain) { return domain; }; /** * @namespace fp * @memberof dc.units * @type {{}} */ dc.units.fp = {}; /** * This function generates an argument for the {@link dc.coordinateGridMixin Coordinate Grid Chart} * {@link dc.coordinateGridMixin#xUnits .xUnits} function specifying that the x values are floating-point * numbers with the given precision. * The returned function determines how many values at the given precision will fit into the range * supplied in its start and end parameters. * @method precision * @memberof dc.units.fp * @see {@link dc.coordinateGridMixin#xUnits coordinateGridMixin.xUnits} * @example * // specify values (and ticks) every 0.1 units * chart.xUnits(dc.units.fp.precision(0.1) * // there are 500 units between 0.5 and 1 if the precision is 0.001 * var thousandths = dc.units.fp.precision(0.001); * thousandths(0.5, 1.0) // returns 500 * @param {Number} precision * @returns {Function} start-end unit function */ dc.units.fp.precision = function (precision) { var _f = function (s, e) { var d = Math.abs((e - s) / _f.resolution); if (dc.utils.isNegligible(d - Math.floor(d))) { return Math.floor(d); } else { return Math.ceil(d); } }; _f.resolution = precision; return _f; }; dc.round = {}; dc.round.floor = function (n) { return Math.floor(n); }; dc.round.ceil = function (n) { return Math.ceil(n); }; dc.round.round = function (n) { return Math.round(n); }; dc.override = function (obj, functionName, newFunction) { var existingFunction = obj[functionName]; obj['_' + functionName] = existingFunction; obj[functionName] = newFunction; }; dc.renderlet = function (_) { if (!arguments.length) { return dc._renderlet; } dc._renderlet = _; return dc; }; dc.instanceOfChart = function (o) { return o instanceof Object && o.__dcFlag__ && true; }; dc.errors = {}; dc.errors.Exception = function (msg) { var _msg = msg || 'Unexpected internal error'; this.message = _msg; this.toString = function () { return _msg; }; this.stack = (new Error()).stack; }; dc.errors.Exception.prototype = Object.create(Error.prototype); dc.errors.Exception.prototype.constructor = dc.errors.Exception; dc.errors.InvalidStateException = function () { dc.errors.Exception.apply(this, arguments); }; dc.errors.InvalidStateException.prototype = Object.create(dc.errors.Exception.prototype); dc.errors.InvalidStateException.prototype.constructor = dc.errors.InvalidStateException; dc.errors.BadArgumentException = function () { dc.errors.Exception.apply(this, arguments); }; dc.errors.BadArgumentException.prototype = Object.create(dc.errors.Exception.prototype); dc.errors.BadArgumentException.prototype.constructor = dc.errors.BadArgumentException; /** * The default date format for dc.js * @name dateFormat * @memberof dc * @type {Function} * @default d3.time.format('%m/%d/%Y') */ dc.dateFormat = d3.time.format('%m/%d/%Y'); /** * @namespace printers * @memberof dc * @type {{}} */ dc.printers = {}; /** * Converts a list of filters into a readable string. * @method filters * @memberof dc.printers * @param {Array<dc.filters>} filters * @returns {String} */ dc.printers.filters = function (filters) { var s = ''; for (var i = 0; i < filters.length; ++i) { if (i > 0) { s += ', '; } s += dc.printers.filter(filters[i]); } return s; }; /** * Converts a filter into a readable string. * @method filter * @memberof dc.printers * @param {dc.filters|any|Array<any>} filter * @returns {String} */ dc.printers.filter = function (filter) { var s = ''; if (typeof filter !== 'undefined' && filter !== null) { if (filter instanceof Array) { if (filter.length >= 2) { s = '[' + dc.utils.printSingleValue(filter[0]) + ' -> ' + dc.utils.printSingleValue(filter[1]) + ']'; } else if (filter.length >= 1) { s = dc.utils.printSingleValue(filter[0]); } } else { s = dc.utils.printSingleValue(filter); } } return s; }; /** * Returns a function that given a string property name, can be used to pluck the property off an object. A function * can be passed as the second argument to also alter the data being returned. * * This can be a useful shorthand method to create accessor functions. * @method pluck * @memberof dc * @example * var xPluck = dc.pluck('x'); * var objA = {x: 1}; * xPluck(objA) // 1 * @example * var xPosition = dc.pluck('x', function (x, i) { * // `this` is the original datum, * // `x` is the x property of the datum, * // `i` is the position in the array * return this.radius + x; * }); * dc.selectAll('.circle').data(...).x(xPosition); * @param {String} n * @param {Function} [f] * @returns {Function} */ dc.pluck = function (n, f) { if (!f) { return function (d) { return d[n]; }; } return function (d, i) { return f.call(d, d[n], i); }; }; /** * @namespace utils * @memberof dc * @type {{}} */ dc.utils = {}; /** * Print a single value filter. * @method printSingleValue * @memberof dc.utils * @param {any} filter * @returns {String} */ dc.utils.printSingleValue = function (filter) { var s = '' + filter; if (filter instanceof Date) { s = dc.dateFormat(filter); } else if (typeof(filter) === 'string') { s = filter; } else if (dc.utils.isFloat(filter)) { s = dc.utils.printSingleValue.fformat(filter); } else if (dc.utils.isInteger(filter)) { s = Math.round(filter); } return s; }; dc.utils.printSingleValue.fformat = d3.format('.2f'); /** * Arbitrary add one value to another. * @method add * @memberof dc.utils * @todo * These assume than any string r is a percentage (whether or not it includes %). * They also generate strange results if l is a string. * @param {String|Date|Number} l the value to modify * @param {Number} r the amount by which to modify the value * @param {String} [t] if `l` is a `Date`, the * [interval](https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Intervals.md#interval) in * the `d3.time` namespace * @returns {String|Date|Number} */ dc.utils.add = function (l, r, t) { if (typeof r === 'string') { r = r.replace('%', ''); } if (l instanceof Date) { if (typeof r === 'string') { r = +r; } if (t === 'millis') { return new Date(l.getTime() + r); } t = t || 'day'; return d3.time[t].offset(l, r); } else if (typeof r === 'string') { var percentage = (+r / 100); return l > 0 ? l * (1 + percentage) : l * (1 - percentage); } else { return l + r; } }; /** * Arbitrary subtract one value from another. * @method subtract * @memberof dc.utils * @todo * These assume than any string r is a percentage (whether or not it includes %). * They also generate strange results if l is a string. * @param {String|Date|Number} l the value to modify * @param {Number} r the amount by which to modify the value * @param {String} [t] if `l` is a `Date`, the * [interval](https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Intervals.md#interval) in * the `d3.time` namespace * @returns {String|Date|Number} */ dc.utils.subtract = function (l, r, t) { if (typeof r === 'string') { r = r.replace('%', ''); } if (l instanceof Date) { if (typeof r === 'string') { r = +r; } if (t === 'millis') { return new Date(l.getTime() - r); } t = t || 'day'; return d3.time[t].offset(l, -r); } else if (typeof r === 'string') { var percentage = (+r / 100); return l < 0 ? l * (1 + percentage) : l * (1 - percentage); } else { return l - r; } }; /** * Is the value a number? * @method isNumber * @memberof dc.utils * @param {any} n * @returns {Boolean} */ dc.utils.isNumber = function (n) { return n === +n; }; /** * Is the value a float? * @method isFloat * @memberof dc.utils * @param {any} n * @returns {Boolean} */ dc.utils.isFloat = function (n) { return n === +n && n !== (n | 0); }; /** * Is the value an integer? * @method isInteger * @memberof dc.utils * @param {any} n * @returns {Boolean} */ dc.utils.isInteger = function (n) { return n === +n && n === (n | 0); }; /** * Is the value very close to zero? * @method isNegligible * @memberof dc.utils * @param {any} n * @returns {Boolean} */ dc.utils.isNegligible = function (n) { return !dc.utils.isNumber(n) || (n < dc.constants.NEGLIGIBLE_NUMBER && n > -dc.constants.NEGLIGIBLE_NUMBER); }; /** * Ensure the value is no greater or less than the min/max values. If it is return the boundary value. * @method clamp * @memberof dc.utils * @param {any} val * @param {any} min * @param {any} max * @returns {any} */ dc.utils.clamp = function (val, min, max) { return val < min ? min : (val > max ? max : val); }; /** * Using a simple static counter, provide a unique integer id. * @method uniqueId * @memberof dc.utils * @returns {Number} */ var _idCounter = 0; dc.utils.uniqueId = function () { return ++_idCounter; }; /** * Convert a name to an ID. * @method nameToId * @memberof dc.utils * @param {String} name * @returns {String} */ dc.utils.nameToId = function (name) { return name.toLowerCase().replace(/[\s]/g, '_').replace(/[\.']/g, ''); }; /** * Append or select an item on a parent element. * @method appendOrSelect * @memberof dc.utils * @param {d3.selection} parent * @param {String} selector * @param {String} tag * @returns {d3.selection} */ dc.utils.appendOrSelect = function (parent, selector, tag) { tag = tag || selector; var element = parent.select(selector); if (element.empty()) { element = parent.append(tag); } return element; }; /** * Return the number if the value is a number; else 0. * @method safeNumber * @memberof dc.utils * @param {Number|any} n * @returns {Number} */ dc.utils.safeNumber = function (n) { return dc.utils.isNumber(+n) ? +n : 0;}; dc.logger = {}; dc.logger.enableDebugLog = false; dc.logger.warn = function (msg) { if (console) { if (console.warn) { console.warn(msg); } else if (console.log) { console.log(msg); } } return dc.logger; }; dc.logger.debug = function (msg) { if (dc.logger.enableDebugLog && console) { if (console.debug) { console.debug(msg); } else if (console.log) { console.log(msg); } } return dc.logger; }; dc.logger.deprecate = function (fn, msg) { // Allow logging of deprecation var warned = false; function deprecated () { if (!warned) { dc.logger.warn(msg); warned = true; } return fn.apply(this, arguments); } return deprecated; }; dc.events = { current: null }; /** * This function triggers a throttled event function with a specified delay (in milli-seconds). Events * that are triggered repetitively due to user interaction such brush dragging might flood the library * and invoke more renders than can be executed in time. Using this function to wrap your event * function allows the library to smooth out the rendering by throttling events and only responding to * the most recent event. * @name events.trigger * @memberof dc * @example * chart.on('renderlet', function(chart) { * // smooth the rendering through event throttling * dc.events.trigger(function(){ * // focus some other chart to the range selected by user on this chart * someOtherChart.focus(chart.filter()); * }); * }) * @param {Function} closure * @param {Number} [delay] */ dc.events.trigger = function (closure, delay) { if (!delay) { closure(); return; } dc.events.current = closure; setTimeout(function () { if (closure === dc.events.current) { closure(); } }, delay); }; /** * The dc.js filters are functions which are passed into crossfilter to chose which records will be * accumulated to produce values for the charts. In the crossfilter model, any filters applied on one * dimension will affect all the other dimensions but not that one. dc always applies a filter * function to the dimension; the function combines multiple filters and if any of them accept a * record, it is filtered in. * * These filter constructors are used as appropriate by the various charts to implement brushing. We * mention below which chart uses which filter. In some cases, many instances of a filter will be added. * * Each of the dc.js filters is an object with the following properties: * * `isFiltered` - a function that returns true if a value is within the filter * * `filterType` - a string identifying the filter, here the name of the constructor * * Currently these filter objects are also arrays, but this is not a requirement. Custom filters * can be used as long as they have the properties above. * @namespace filters * @memberof dc * @type {{}} */ dc.filters = {}; /** * RangedFilter is a filter which accepts keys between `low` and `high`. It is used to implement X * axis brushing for the {@link dc.coordinateGridMixin coordinate grid charts}. * * Its `filterType` is 'RangedFilter' * @name RangedFilter * @memberof dc.filters * @param {Number} low * @param {Number} high * @returns {Array<Number>} * @constructor */ dc.filters.RangedFilter = function (low, high) { var range = new Array(low, high); range.isFiltered = function (value) { return value >= this[0] && value < this[1]; }; range.filterType = 'RangedFilter'; return range; }; /** * TwoDimensionalFilter is a filter which accepts a single two-dimensional value. It is used by the * {@link dc.heatMap heat map chart} to include particular cells as they are clicked. (Rows and columns are * filtered by filtering all the cells in the row or column.) * * Its `filterType` is 'TwoDimensionalFilter' * @name TwoDimensionalFilter * @memberof dc.filters * @param {Array<Number>} filter * @returns {Array<Number>} * @constructor */ dc.filters.TwoDimensionalFilter = function (filter) { if (filter === null) { return null; } var f = filter; f.isFiltered = function (value) { return value.length && value.length === f.length && value[0] === f[0] && value[1] === f[1]; }; f.filterType = 'TwoDimensionalFilter'; return f; }; /** * The RangedTwoDimensionalFilter allows filtering all values which fit within a rectangular * region. It is used by the {@link dc.scatterPlot scatter plot} to implement rectangular brushing. * * It takes two two-dimensional points in the form `[[x1,y1],[x2,y2]]`, and normalizes them so that * `x1 <= x2` and `y1 <= y2`. It then returns a filter which accepts any points which are in the * rectangular range including the lower values but excluding the higher values. * * If an array of two values are given to the RangedTwoDimensionalFilter, it interprets the values as * two x coordinates `x1` and `x2` and returns a filter which accepts any points for which `x1 <= x < * x2`. * * Its `filterType` is 'RangedTwoDimensionalFilter' * @name RangedTwoDimensionalFilter * @memberof dc.filters * @param {Array<Array<Number>>} filter * @returns {Array<Array<Number>>} * @constructor */ dc.filters.RangedTwoDimensionalFilter = function (filter) { if (filter === null) { return null; } var f = filter; var fromBottomLeft; if (f[0] instanceof Array) { fromBottomLeft = [ [Math.min(filter[0][0], filter[1][0]), Math.min(filter[0][1], filter[1][1])], [Math.max(filter[0][0], filter[1][0]), Math.max(filter[0][1], filter[1][1])] ]; } else { fromBottomLeft = [[filter[0], -Infinity], [filter[1], Infinity]]; } f.isFiltered = function (value) { var x, y; if (value instanceof Array) { x = value[0]; y = value[1]; } else { x = value; y = fromBottomLeft[0][1]; } return x >= fromBottomLeft[0][0] && x < fromBottomLeft[1][0] && y >= fromBottomLeft[0][1] && y < fromBottomLeft[1][1]; }; f.filterType = 'RangedTwoDimensionalFilter'; return f; }; /** * `dc.baseMixin` is an abstract functional object representing a basic `dc` chart object * for all chart and widget implementations. Methods from the {@link #dc.baseMixin dc.baseMixin} are inherited * and available on all chart implementations in the `dc` library. * @name baseMixin * @memberof dc * @mixin * @param {Object} _chart * @returns {dc.baseMixin} */ dc.baseMixin = function (_chart) { _chart.__dcFlag__ = dc.utils.uniqueId(); var _dimension; var _group; var _anchor; var _root; var _svg; var _isChild; var _minWidth = 200; var _defaultWidthCalc = function (element) { var width = element && element.getBoundingClientRect && element.getBoundingClientRect().width; return (width && width > _minWidth) ? width : _minWidth; }; var _widthCalc = _defaultWidthCalc; var _minHeight = 200; var _defaultHeightCalc = function (element) { var height = element && element.getBoundingClientRect && element.getBoundingClientRect().height; return (height && height > _minHeight) ? height : _minHeight; }; var _heightCalc = _defaultHeightCalc; var _width, _height; var _keyAccessor = dc.pluck('key'); var _valueAccessor = dc.pluck('value'); var _label = dc.pluck('key'); var _ordering = dc.pluck('key'); var _orderSort; var _renderLabel = false; var _title = function (d) { return _chart.keyAccessor()(d) + ': ' + _chart.valueAccessor()(d); }; var _renderTitle = true; var _controlsUseVisibility = false; var _transitionDuration = 750; var _transitionDelay = 0; var _filterPrinter = dc.printers.filters; var _mandatoryAttributes = ['dimension', 'group']; var _chartGroup = dc.constants.DEFAULT_CHART_GROUP; var _listeners = d3.dispatch( 'preRender', 'postRender', 'preRedraw', 'postRedraw', 'filtered', 'zoomed', 'renderlet', 'pretransition'); var _legend; var _commitHandler; var _filters = []; var _filterHandler = function (dimension, filters) { if (filters.length === 0) { dimension.filter(null); } else if (filters.length === 1 && !filters[0].isFiltered) { // single value and not a function-based filter dimension.filterExact(filters[0]); } else if (filters.length === 1 && filters[0].filterType === 'RangedFilter') { // single range-based filter dimension.filterRange(filters[0]); } else { dimension.filterFunction(function (d) { for (var i = 0; i < filters.length; i++) { var filter = filters[i]; if (filter.isFiltered && filter.isFiltered(d)) { return true; } else if (filter <= d && filter >= d) { return true; } } return false; }); } return filters; }; var _data = function (group) { return group.all(); }; /** * Set or get the height attribute of a chart. The height is applied to the SVGElement generated by * the chart when rendered (or re-rendered). If a value is given, then it will be used to calculate * the new height and the chart returned for method chaining. The value can either be a numeric, a * function, or falsy. If no value is specified then the value of the current height attribute will * be returned. * * By default, without an explicit height being given, the chart will select the width of its * anchor element. If that isn't possible it defaults to 200 (provided by the * {@link dc.baseMixin#minHeight minHeight} property). Setting the value falsy will return * the chart to the default behavior. * @method height * @memberof dc.baseMixin * @instance * @see {@link dc.baseMixin#minHeight minHeight} * @example * // Default height * chart.height(function (element) { * var height = element && element.getBoundingClientRect && element.getBoundingClientRect().height; * return (height && height > chart.minHeight()) ? height : chart.minHeight(); * }); * * chart.height(250); // Set the chart's height to 250px; * chart.height(function(anchor) { return doSomethingWith(anchor); }); // set the chart's height with a function * chart.height(null); // reset the height to the default auto calculation * @param {Number|Function} [height] * @returns {Number|dc.baseMixin} */ _chart.height = function (height) { if (!arguments.length) { if (!dc.utils.isNumber(_height)) { // only calculate once _height = _heightCalc(_root.node()); } return _height; } _heightCalc = d3.functor(height || _defaultHeightCalc); _height = undefined; return _chart; }; /** * Set or get the width attribute of a chart. * @method width * @memberof dc.baseMixin * @instance * @see {@link dc.baseMixin#height height} * @see {@link dc.baseMixin#minWidth minWidth} * @example * // Default width * chart.width(function (element) { * var width = element && element.getBoundingClientRect && element.getBoundingClientRect().width; * return (width && width > chart.minWidth()) ? width : chart.minWidth(); * }); * @param {Number|Function} [width] * @returns {Number|dc.baseMixin} */ _chart.width = function (width) { if (!arguments.length) { if (!dc.utils.isNumber(_width)) { // only calculate once _width = _widthCalc(_root.node()); } return _width; } _widthCalc = d3.functor(width || _defaultWidthCalc); _width = undefined; return _chart; }; /** * Set or get the minimum width attribute of a chart. This only has effect when used with the default * {@link dc.baseMixin#width width} function. * @method minWidth * @memberof dc.baseMixin * @instance * @see {@link dc.baseMixin#width width} * @param {Number} [minWidth=200] * @returns {Number|dc.baseMixin} */ _chart.minWidth = function (minWidth) { if (!arguments.length) { return _minWidth; } _minWidth = minWidth; return _chart; }; /** * Set or get the minimum height attribute of a chart. This only has effect when used with the default * {@link dc.baseMixin#height height} function. * @method minHeight * @memberof dc.baseMixin * @instance * @see {@link dc.baseMixin#height height} * @param {Number} [minHeight=200] * @returns {Number|dc.baseMixin} */ _chart.minHeight = function (minHeight) { if (!arguments.length) { return _minHeight; } _minHeight = minHeight; return _chart; }; /** * **mandatory** * * Set or get the dimension attribute of a chart. In `dc`, a dimension can be any valid * {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#dimension crossfilter dimension} * * If a value is given, then it will be used as the new dimension. If no value is specified then * the current dimension will be returned. * @method dimension * @memberof dc.baseMixin * @instance * @see {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#dimension crossfilter.dimension} * @example * var index = crossfilter([]); * var dimension = index.dimension(dc.pluck('key')); * chart.dimension(dimension); * @param {crossfilter.dimension} [dimension] * @returns {crossfilter.dimension|dc.baseMixin} */ _chart.dimension = function (dimension) { if (!arguments.length) { return _dimension; } _dimension = dimension; _chart.expireCache(); return _chart; }; /** * Set the data callback or retrieve the chart's data set. The data callback is passed the chart's * group and by default will return * {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#group_all group.all}. * This behavior may be modified to, for instance, return only the top 5 groups. * @method data * @memberof dc.baseMixin * @instance * @example * // Default data function * chart.data(function (group) { return group.all(); }); * * chart.data(function (group) { return group.top(5); }); * @param {Function} [callback] * @returns {*|dc.baseMixin} */ _chart.data = function (callback) { if (!arguments.length) { return _data.call(_chart, _group); } _data = d3.functor(callback); _chart.expireCache(); return _chart; }; /** * **mandatory** * * Set or get the group attribute of a chart. In `dc` a group is a * {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#group-map-reduce crossfilter group}. * Usually the group should be created from the particular dimension associated with the same chart. If a value is * given, then it will be used as the new group. * * If no value specified then the current group will be returned. * If `name` is specified then it will be used to generate legend label. * @method group * @memberof dc.baseMixin * @instance * @see {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#group-map-reduce crossfilter.group} * @example * var index = crossfilter([]); * var dimension = index.dimension(dc.pluck('key')); * chart.dimension(dimension); * chart.group(dimension.group(crossfilter.reduceSum())); * @param {crossfilter.group} [group] * @param {String} [name] * @returns {crossfilter.group|dc.baseMixin} */ _chart.group = function (group, name) { if (!arguments.length) { return _group; } _group = group; _chart._groupName = name; _chart.expireCache(); return _chart; }; /** * Get or set an accessor to order ordinal dimensions. The chart uses * {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#quicksort_by crossfilter.quicksort.by} * to sort elements; this accessor returns the value to order on. * @method ordering * @memberof dc.baseMixin * @instance * @see {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#quicksort_by crossfilter.quicksort.by} * @example * // Default ordering accessor * _chart.ordering(dc.pluck('key')); * @param {Function} [orderFunction] * @returns {Function|dc.baseMixin} */ _chart.ordering = function (orderFunction) { if (!arguments.length) { return _ordering; } _ordering = orderFunction; _orderSort = crossfilter.quicksort.by(_ordering); _chart.expireCache(); return _chart; }; _chart._computeOrderedGroups = function (data) { var dataCopy = data.slice(0); if (dataCopy.length <= 1) { return dataCopy; } if (!_orderSort) { _orderSort = crossfilter.quicksort.by(_ordering); } return _orderSort(dataCopy, 0, dataCopy.length); }; /** * Clear all filters associated with this chart. The same effect can be achieved by calling * {@link dc.baseMixin#filter chart.filter(null)}. * @method filterAll * @memberof dc.baseMixin * @instance * @returns {dc.baseMixin} */ _chart.filterAll = function () { return _chart.filter(null); }; /** * Execute d3 single selection in the chart's scope using the given selector and return the d3 * selection. * * This function is **not chainable** since it does not return a chart instance; however the d3 * selection result can be chained to d3 function calls. * @method select * @memberof dc.baseMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#d3_select d3.select} * @example * // Has the same effect as d3.select('#chart-id').select(selector) * chart.select(selector) * @returns {d3.selection} */ _chart.select = function (s) { return _root.select(s); }; /** * Execute in scope d3 selectAll using the given selector and return d3 selection result. * * This function is **not chainable** since it does not return a chart instance; however the d3 * selection result can be chained to d3 function calls. * @method selectAll * @memberof dc.baseMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#d3_selectAll d3.selectAll} * @example * // Has the same effect as d3.select('#chart-id').selectAll(selector) * chart.selectAll(selector) * @returns {d3.selection} */ _chart.selectAll = function (s) { return _root ? _root.selectAll(s) : null; }; /** * Set the root SVGElement to either be an existing chart's root; or any valid [d3 single * selector](https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements) specifying a dom * block element such as a div; or a dom element or d3 selection. Optionally registers the chart * within the chartGroup. This class is called internally on chart initialization, but be called * again to relocate the chart. However, it will orphan any previously created SVGElements. * @method anchor * @memberof dc.baseMixin * @instance * @param {anchorChart|anchorSelector|anchorNode} [parent] * @param {String} [chartGroup] * @returns {String|node|d3.selection|dc.baseMixin} */ _chart.anchor = function (parent, chartGroup) { if (!arguments.length) { return _anchor; } if (dc.instanceOfChart(parent)) { _anchor = parent.anchor(); _root = parent.root(); _isChild = true; } else if (parent) { if (parent.select && parent.classed) { // detect d3 selection _anchor = parent.node(); } else { _anchor = parent; } _root = d3.select(_anchor); _root.classed(dc.constants.CHART_CLASS, true); dc.registerChart(_chart, chartGroup); _isChild = false; } else { throw new dc.errors.BadArgumentException('parent must be defined'); } _chartGroup = chartGroup; return _chart; }; /** * Returns the DOM id for the chart's anchored location. * @method anchorName * @memberof dc.baseMixin * @instance * @returns {String} */ _chart.anchorName = function () { var a = _chart.anchor(); if (a && a.id) { return a.id; } if (a && a.replace) { return a.replace('#', ''); } return 'dc-chart' + _chart.chartID(); }; /** * Returns the root element where a chart resides. Usually it will be the parent div element where * the SVGElement was created. You can also pass in a new root element however this is usually handled by * dc internally. Resetting the root element on a chart outside of dc internals may have * unexpected consequences. * @method root * @memberof dc.baseMixin * @instance * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement HTMLElement} * @param {HTMLElement} [rootElement] * @returns {HTMLElement|dc.baseMixin} */ _chart.root = function (rootElement) { if (!arguments.length) { return _root; } _root = rootElement; return _chart; }; /** * Returns the top SVGElement for this specific chart. You can also pass in a new SVGElement, * however this is usually handled by dc internally. Resetting the SVGElement on a chart outside * of dc internals may have unexpected consequences. * @method svg * @memberof dc.baseMixin * @instance * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/SVGElement SVGElement} * @param {SVGElement|d3.selection} [svgElement] * @returns {SVGElement|d3.selection|dc.baseMixin} */ _chart.svg = function (svgElement) { if (!arguments.length) { return _svg; } _svg = svgElement; return _chart; }; /** * Remove the chart's SVGElements from the dom and recreate the container SVGElement. * @method resetSvg * @memberof dc.baseMixin * @instance * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/SVGElement SVGElement} * @returns {SVGElement} */ _chart.resetSvg = function () { _chart.select('svg').remove(); return generateSvg(); }; function sizeSvg () { if (_svg) { _svg .attr('width', _chart.width()) .attr('height', _chart.height()); } } function generateSvg () { _svg = _chart.root().append('svg'); sizeSvg(); return _svg; } /** * Set or get the filter printer function. The filter printer function is used to generate human * friendly text for filter value(s) associated with the chart instance. The text will get shown * in the `.filter element; see {@link dc.baseMixin#turnOnControls turnOnControls}. * * By default dc charts use a default filter printer {@link dc.printers.filters dc.printers.filters} * that provides simple printing support for both single value and ranged filters. * @method filterPrinter * @memberof dc.baseMixin * @instance * @example * // for a chart with an ordinal brush, print the filters in upper case * chart.filterPrinter(function(filters) { * return filters.map(function(f) { return f.toUpperCase(); }).join(', '); * }); * // for a chart with a range brush, print the filter as start and extent * chart.filterPrinter(function(filters) { * return 'start ' + dc.utils.printSingleValue(filters[0][0]) + * ' extent ' + dc.utils.printSingleValue(filters[0][1] - filters[0][0]); * }); * @param {Function} [filterPrinterFunction=dc.printers.filters] * @returns {Function|dc.baseMixin} */ _chart.filterPrinter = function (filterPrinterFunction) { if (!arguments.length) { return _filterPrinter; } _filterPrinter = filterPrinterFunction; return _chart; }; /** * If set, use the `visibility` attribute instead of the `display` attribute for showing/hiding * chart reset and filter controls, for less disruption to the layout. * @method controlsUseVisibility * @memberof dc.baseMixin * @instance * @param {Boolean} [controlsUseVisibility=false] * @returns {Boolean|dc.baseMixin} **/ _chart.controlsUseVisibility = function (useVisibility) { if (!arguments.length) { return _controlsUseVisibility; } _controlsUseVisibility = useVisibility; return _chart; }; /** * Turn on optional control elements within the root element. dc currently supports the * following html control elements. * * root.selectAll('.reset') - elements are turned on if the chart has an active filter. This type * of control element is usually used to store a reset link to allow user to reset filter on a * certain chart. This element will be turned off automatically if the filter is cleared. * * root.selectAll('.filter') elements are turned on if the chart has an active filter. The text * content of this element is then replaced with the current filter value using the filter printer * function. This type of element will be turned off automatically if the filter is cleared. * @method turnOnControls * @memberof dc.baseMixin * @instance * @returns {dc.baseMixin} */ _chart.turnOnControls = function () { if (_root) { var attribute = _chart.controlsUseVisibility() ? 'visibility' : 'display'; _chart.selectAll('.reset').style(attribute, null); _chart.selectAll('.filter').text(_filterPrinter(_chart.filters())).style(attribute, null); } return _chart; }; /** * Turn off optional control elements within the root element. * @method turnOffControls * @memberof dc.baseMixin * @see {@link dc.baseMixin#turnOnControls turnOnControls} * @instance * @returns {dc.baseMixin} */ _chart.turnOffControls = function () { if (_root) { var attribute = _chart.controlsUseVisibility() ? 'visibility' : 'display'; var value = _chart.controlsUseVisibility() ? 'hidden' : 'none'; _chart.selectAll('.reset').style(attribute, value); _chart.selectAll('.filter').style(attribute, value).text(_chart.filter()); } return _chart; }; /** * Set or get the animation transition duration (in milliseconds) for this chart instance. * @method transitionDuration * @memberof dc.baseMixin * @instance * @param {Number} [duration=750] * @returns {Number|dc.baseMixin} */ _chart.transitionDuration = function (duration) { if (!arguments.length) { return _transitionDuration; } _transitionDuration = duration; return _chart; }; /** * Set or get the animation transition delay (in milliseconds) for this chart instance. * @method transitionDelay * @memberof dc.baseMixin * @instance * @param {Number} [delay=0] * @returns {Number|dc.baseMixin} */ _chart.transitionDelay = function (delay) { if (!arguments.length) { return _transitionDelay; } _transitionDelay = delay; return _chart; }; _chart._mandatoryAttributes = function (_) { if (!arguments.length) { return _mandatoryAttributes; } _mandatoryAttributes = _; return _chart; }; function checkForMandatoryAttributes (a) { if (!_chart[a] || !_chart[a]()) { throw new dc.errors.InvalidStateException('Mandatory attribute chart.' + a + ' is missing on chart[#' + _chart.anchorName() + ']'); } } /** * Invoking this method will force the chart to re-render everything from scratch. Generally it * should only be used to render the chart for the first time on the page or if you want to make * sure everything is redrawn from scratch instead of relying on the default incremental redrawing * behaviour. * @method render * @memberof dc.baseMixin * @instance * @returns {dc.baseMixin} */ _chart.render = function () { _height = _width = undefined; // force recalculate _listeners.preRender(_chart); if (_mandatoryAttributes) { _mandatoryAttributes.forEach(checkForMandatoryAttributes); } var result = _chart._doRender(); if (_legend) { _legend.render(); } _chart._activateRenderlets('postRender'); return result; }; _chart._activateRenderlets = function (event) { _listeners.pretransition(_chart); if (_chart.transitionDuration() > 0 && _svg) { _svg.transition().duration(_chart.transitionDuration()).delay(_chart.transitionDelay()) .each('end', function () { _listeners.renderlet(_chart); if (event) { _listeners[event](_chart); } }); } else { _listeners.renderlet(_chart); if (event) { _listeners[event](_chart); } } }; /** * Calling redraw will cause the chart to re-render data changes incrementally. If there is no * change in the underlying data dimension then calling this method will have no effect on the * chart. Most chart interaction in dc will automatically trigger this method through internal * events (in particular {@link dc.redrawAll dc.redrawAll}); therefore, you only need to * manually invoke this function if data is manipulated outside of dc's control (for example if * data is loaded in the background using * {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#crossfilter_add crossfilter.add}). * @method redraw * @memberof dc.baseMixin * @instance * @returns {dc.baseMixin} */ _chart.redraw = function () { sizeSvg(); _listeners.preRedraw(_chart); var result = _chart._doRedraw(); if (_legend) { _legend.render(); } _chart._activateRenderlets('postRedraw'); return result; }; /** * Gets/sets the commit handler. If the chart has a commit handler, the handler will be called when * the chart's filters have changed, in order to send the filter data asynchronously to a server. * * Unlike other functions in dc.js, the commit handler is asynchronous. It takes two arguments: * a flag indicating whether this is a render (true) or a redraw (false), and a callback to be * triggered once the commit is filtered. The callback has the standard node.js continuation signature * with error first and result second. * @method commitHandler * @memberof dc.baseMixin * @instance * @returns {dc.baseMixin} */ _chart.commitHandler = function (commitHandler) { if (!arguments.length) { return _commitHandler; } _commitHandler = commitHandler; return _chart; }; /** * Redraws all charts in the same group as this chart, typically in reaction to a filter * change. If the chart has a {@link dc.baseMixin.commitFilter commitHandler}, it will * be executed and waited for. * @method redrawGroup * @memberof dc.baseMixin * @instance * @returns {dc.baseMixin} */ _chart.redrawGroup = function () { if (_commitHandler) { _commitHandler(false, function (error, result) { if (error) { console.log(error); } else { dc.redrawAll(_chart.chartGroup()); } }); } else { dc.redrawAll(_chart.chartGroup()); } return _chart; }; /** * Renders all charts in the same group as this chart. If the chart has a * {@link dc.baseMixin.commitFilter commitHandler}, it will be executed and waited for * @method renderGroup * @memberof dc.baseMixin * @instance * @returns {dc.baseMixin} */ _chart.renderGroup = function () { if (_commitHandler) { _commitHandler(false, function (error, result) { if (error) { console.log(error); } else { dc.renderAll(_chart.chartGroup()); } }); } else { dc.renderAll(_chart.chartGroup()); } return _chart; }; _chart._invokeFilteredListener = function (f) { if (f !== undefined) { _listeners.filtered(_chart, f); } }; _chart._invokeZoomedListener = function () { _listeners.zoomed(_chart); }; var _hasFilterHandler = function (filters, filter) { if (filter === null || typeof(filter) === 'undefined') { return filters.length > 0; } return filters.some(function (f) { return filter <= f && filter >= f; }); }; /** * Set or get the has-filter handler. The has-filter handler is a function that checks to see if * the chart's current filters (first argument) include a specific filter (second argument). Using a custom has-filter handler allows * you to change the way filters are checked for and replaced. * @method hasFilterHandler * @memberof dc.baseMixin * @instance * @example * // default has-filter handler * chart.hasFilterHandler(function (filters, filter) { * if (filter === null || typeof(filter) === 'undefined') { * return filters.length > 0; * } * return filters.some(function (f) { * return filter <= f && filter >= f; * }); * }); * * // custom filter handler (no-op) * chart.hasFilterHandler(function(filters, filter) { * return false; * }); * @param {Function} [hasFilterHandler] * @returns {Function|dc.baseMixin} */ _chart.hasFilterHandler = function (hasFilterHandler) { if (!arguments.length) { return _hasFilterHandler; } _hasFilterHandler = hasFilterHandler; return _chart; }; /** * Check whether any active filter or a specific filter is associated with particular chart instance. * This function is **not chainable**. * @method hasFilter * @memberof dc.baseMixin * @instance * @see {@link dc.baseMixin#hasFilterHandler hasFilterHandler} * @param {*} [filter] * @returns {Boolean} */ _chart.hasFilter = function (filter) { return _hasFilterHandler(_filters, filter); }; var _removeFilterHandler = function (filters, filter) { for (var i = 0; i < filters.length; i++) { if (filters[i] <= filter && filters[i] >= filter) { filters.splice(i, 1); break; } } return filters; }; /** * Set or get the remove filter handler. The remove filter handler is a function that removes a * filter from the chart's current filters. Using a custom remove filter handler allows you to * change how filters are removed or perform additional work when removing a filter, e.g. when * using a filter server other than crossfilter. * * The handler should return a new or modified array as the result. * @method removeFilterHandler * @memberof dc.baseMixin * @instance * @example * // default remove filter handler * chart.removeFilterHandler(function (filters, filter) { * for (var i = 0; i < filters.length; i++) { * if (filters[i] <= filter && filters[i] >= filter) { * filters.splice(i, 1); * break; * } * } * return filters; * }); * * // custom filter handler (no-op) * chart.removeFilterHandler(function(filters, filter) { * return filters; * }); * @param {Function} [removeFilterHandler] * @returns {Function|dc.baseMixin} */ _chart.removeFilterHandler = function (removeFilterHandler) { if (!arguments.length) { return _removeFilterHandler; } _removeFilterHandler = removeFilterHandler; return _chart; }; var _addFilterHandler = function (filters, filter) { filters.push(filter); return filters; }; /** * Set or get the add filter handler. The add filter handler is a function that adds a filter to * the chart's filter list. Using a custom add filter handler allows you to change the way filters * are added or perform additional work when adding a filter, e.g. when using a filter server other * than crossfilter. * * The handler should return a new or modified array as the result. * @method addFilterHandler * @memberof dc.baseMixin * @instance * @example * // default add filter handler * chart.addFilterHandler(function (filters, filter) { * filters.push(filter); * return filters; * }); * * // custom filter handler (no-op) * chart.addFilterHandler(function(filters, filter) { * return filters; * }); * @param {Function} [addFilterHandler] * @returns {Function|dc.baseMixin} */ _chart.addFilterHandler = function (addFilterHandler) { if (!arguments.length) { return _addFilterHandler; } _addFilterHandler = addFilterHandler; return _chart; }; var _resetFilterHandler = function (filters) { return []; }; /** * Set or get the reset filter handler. The reset filter handler is a function that resets the * chart's filter list by returning a new list. Using a custom reset filter handler allows you to * change the way filters are reset, or perform additional work when resetting the filters, * e.g. when using a filter server other than crossfilter. * * The handler should return a new or modified array as the result. * @method resetFilterHandler * @memberof dc.baseMixin * @instance * @example * // default remove filter handler * function (filters) { * return []; * } * * // custom filter handler (no-op) * chart.resetFilterHandler(function(filters) { * return filters; * }); * @param {Function} [resetFilterHandler] * @returns {dc.baseMixin} */ _chart.resetFilterHandler = function (resetFilterHandler) { if (!arguments.length) { return _resetFilterHandler; } _resetFilterHandler = resetFilterHandler; return _chart; }; function applyFilters (filters) { if (_chart.dimension() && _chart.dimension().filter) { var fs = _filterHandler(_chart.dimension(), filters); if (fs) { filters = fs; } } return filters; } /** * Replace the chart filter. This is equivalent to calling `chart.filter(null).filter(filter)` * but more efficient because the filter is only applied once. * * @method replaceFilter * @memberof dc.baseMixin * @instance * @param {*} [filter] * @returns {dc.baseMixin} **/ _chart.replaceFilter = function (filter) { _filters = _resetFilterHandler(_filters); _chart.filter(filter); }; /** * Filter the chart by the given parameter, or return the current filter if no input parameter * is given. * * The filter parameter can take one of these forms: * * A single value: the value will be toggled (added if it is not present in the current * filters, removed if it is present) * * An array containing a single array of values (`[[value,value,value]]`): each value is * toggled * * When appropriate for the chart, a {@link dc.filters dc filter object} such as * * {@link dc.filters.RangedFilter `dc.filters.RangedFilter`} for the * {@link dc.coordinateGridMixin dc.coordinateGridMixin} charts * * {@link dc.filters.TwoDimensionalFilter `dc.filters.TwoDimensionalFilter`} for the * {@link dc.heatMap heat map} * * {@link dc.filters.RangedTwoDimensionalFilter `dc.filters.RangedTwoDimensionalFilter`} * for the {@link dc.scatterPlot scatter plot} * * `null`: the filter will be reset using the * {@link dc.baseMixin#resetFilterHandler resetFilterHandler} * * Note that this is always a toggle (even when it doesn't make sense for the filter type). If * you wish to replace the current filter, either call `chart.filter(null)` first - or it's more * efficient to call {@link dc.baseMixin#replaceFilter `chart.replaceFilter(filter)`} instead. * * Each toggle is executed by checking if the value is already present using the * {@link dc.baseMixin#hasFilterHandler hasFilterHandler}; if it is not present, it is added * using the {@link dc.baseMixin#addFilterHandler addFilterHandler}; if it is already present, * it is removed using the {@link dc.baseMixin#removeFilterHandler removeFilterHandler}. * * Once the filters array has been updated, the filters are applied to the * crossfilter dimension, using the {@link dc.baseMixin#filterHandler filterHandler}. * * Once you have set the filters, call {@link dc.baseMixin#redrawGroup `chart.redrawGroup()`} * (or {@link dc.redrawAll `dc.redrawAll()`}) to redraw the chart's group. * @method filter * @memberof dc.baseMixin * @instance * @see {@link dc.baseMixin#addFilterHandler addFilterHandler} * @see {@link dc.baseMixin#removeFilterHandler removeFilterHandler} * @see {@link dc.baseMixin#resetFilterHandler resetFilterHandler} * @see {@link dc.baseMixin#filterHandler filterHandler} * @example * // filter by a single string * chart.filter('Sunday'); * // filter by a single age * chart.filter(18); * // filter by a set of states * chart.filter([['MA', 'TX', 'ND', 'WA']]); * // filter by range -- note the use of dc.filters.RangedFilter, which is different * // from the syntax for filtering a crossfilter dimension directly, dimension.filter([15,20]) * chart.filter(dc.filters.RangedFilter(15,20)); * @param {*} [filter] * @returns {dc.baseMixin} */ _chart.filter = function (filter) { if (!arguments.length) { return _filters.length > 0 ? _filters[0] : null; } var filters = _filters; if (filter instanceof Array && filter[0] instanceof Array && !filter.isFiltered) { // toggle each filter filter[0].forEach(function (f) { if (_hasFilterHandler(filters, f)) { filters = _removeFilterHandler(filters, f); } else { filters = _addFilterHandler(filters, f); } }); } else if (filter === null) { filters = _resetFilterHandler(filters); } else { if (_hasFilterHandler(filters, filter)) { filters = _removeFilterHandler(filters, filter); } else { filters = _addFilterHandler(filters, filter); } } _filters = applyFilters(filters); _chart._invokeFilteredListener(filter); if (_root !== null && _chart.hasFilter()) { _chart.turnOnControls(); } else { _chart.turnOffControls(); } return _chart; }; /** * Returns all current filters. This method does not perform defensive cloning of the internal * filter array before returning, therefore any modification of the returned array will effect the * chart's internal filter storage. * @method filters * @memberof dc.baseMixin * @instance * @returns {Array<*>} */ _chart.filters = function () { return _filters; }; _chart.highlightSelected = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, true); d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); }; _chart.fadeDeselected = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, false); d3.select(e).classed(dc.constants.DESELECTED_CLASS, true); }; _chart.resetHighlight = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, false); d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); }; /** * This function is passed to d3 as the onClick handler for each chart. The default behavior is to * filter on the clicked datum (passed to the callback) and redraw the chart group. * @method onClick * @memberof dc.baseMixin * @instance * @param {*} datum */ _chart.onClick = function (datum) { var filter = _chart.keyAccessor()(datum); dc.events.trigger(function () { _chart.filter(filter); _chart.redrawGroup(); }); }; /** * Set or get the filter handler. The filter handler is a function that performs the filter action * on a specific dimension. Using a custom filter handler allows you to perform additional logic * before or after filtering. * @method filterHandler * @memberof dc.baseMixin * @instance * @see {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#dimension_filter crossfilter.dimension.filter} * @example * // the default filter handler handles all possible cases for the charts in dc.js * // you can replace it with something more specialized for your own chart * chart.filterHandler(function (dimension, filters) { * if (filters.length === 0) { * // the empty case (no filtering) * dimension.filter(null); * } else if (filters.length === 1 && !filters[0].isFiltered) { * // single value and not a function-based filter * dimension.filterExact(filters[0]); * } else if (filters.length === 1 && filters[0].filterType === 'RangedFilter') { * // single range-based filter * dimension.filterRange(filters[0]); * } else { * // an array of values, or an array of filter objects * dimension.filterFunction(function (d) { * for (var i = 0; i < filters.length; i++) { * var filter = filters[i]; * if (filter.isFiltered && filter.isFiltered(d)) { * return true; * } else if (filter <= d && filter >= d) { * return true; * } * } * return false; * }); * } * return filters; * }); * * // custom filter handler * chart.filterHandler(function(dimension, filter){ * var newFilter = filter + 10; * dimension.filter(newFilter); * return newFilter; // set the actual filter value to the new value * }); * @param {Function} [filterHandler] * @returns {Function|dc.baseMixin} */ _chart.filterHandler = function (filterHandler) { if (!arguments.length) { return _filterHandler; } _filterHandler = filterHandler; return _chart; }; // abstract function stub _chart._doRender = function () { // do nothing in base, should be overridden by sub-function return _chart; }; _chart._doRedraw = function () { // do nothing in base, should be overridden by sub-function return _chart; }; _chart.legendables = function () { // do nothing in base, should be overridden by sub-function return []; }; _chart.legendHighlight = function () { // do nothing in base, should be overridden by sub-function }; _chart.legendReset = function () { // do nothing in base, should be overridden by sub-function }; _chart.legendToggle = function () { // do nothing in base, should be overriden by sub-function }; _chart.isLegendableHidden = function () { // do nothing in base, should be overridden by sub-function return false; }; /** * Set or get the key accessor function. The key accessor function is used to retrieve the key * value from the crossfilter group. Key values are used differently in different charts, for * example keys correspond to slices in a pie chart and x axis positions in a grid coordinate chart. * @method keyAccessor * @memberof dc.baseMixin * @instance * @example * // default key accessor * chart.keyAccessor(function(d) { return d.key; }); * // custom key accessor for a multi-value crossfilter reduction * chart.keyAccessor(function(p) { return p.value.absGain; }); * @param {Function} [keyAccessor] * @returns {Function|dc.baseMixin} */ _chart.keyAccessor = function (keyAccessor) { if (!arguments.length) { return _keyAccessor; } _keyAccessor = keyAccessor; return _chart; }; /** * Set or get the value accessor function. The value accessor function is used to retrieve the * value from the crossfilter group. Group values are used differently in different charts, for * example values correspond to slice sizes in a pie chart and y axis positions in a grid * coordinate chart. * @method valueAccessor * @memberof dc.baseMixin * @instance * @example * // default value accessor * chart.valueAccessor(function(d) { return d.value; }); * // custom value accessor for a multi-value crossfilter reduction * chart.valueAccessor(function(p) { return p.value.percentageGain; }); * @param {Function} [valueAccessor] * @returns {Function|dc.baseMixin} */ _chart.valueAccessor = function (valueAccessor) { if (!arguments.length) { return _valueAccessor; } _valueAccessor = valueAccessor; return _chart; }; /** * Set or get the label function. The chart class will use this function to render labels for each * child element in the chart, e.g. slices in a pie chart or bubbles in a bubble chart. Not every * chart supports the label function, for example line chart does not use this function * at all. By default, enables labels; pass false for the second parameter if this is not desired. * @method label * @memberof dc.baseMixin * @instance * @example * // default label function just return the key * chart.label(function(d) { return d.key; }); * // label function has access to the standard d3 data binding and can get quite complicated * chart.label(function(d) { return d.data.key + '(' + Math.floor(d.data.value / all.value() * 100) + '%)'; }); * @param {Function} [labelFunction] * @param {Boolean} [enableLabels=true] * @returns {Function|dc.baseMixin} */ _chart.label = function (labelFunction, enableLabels) { if (!arguments.length) { return _label; } _label = labelFunction; if ((enableLabels === undefined) || enableLabels) { _renderLabel = true; } return _chart; }; /** * Turn on/off label rendering * @method renderLabel * @memberof dc.baseMixin * @instance * @param {Boolean} [renderLabel=false] * @returns {Boolean|dc.baseMixin} */ _chart.renderLabel = function (renderLabel) { if (!arguments.length) { return _renderLabel; } _renderLabel = renderLabel; return _chart; }; /** * Set or get the title function. The chart class will use this function to render the SVGElement title * (usually interpreted by browser as tooltips) for each child element in the chart, e.g. a slice * in a pie chart or a bubble in a bubble chart. Almost every chart supports the title function; * however in grid coordinate charts you need to turn off the brush in order to see titles, because * otherwise the brush layer will block tooltip triggering. * @method title * @memberof dc.baseMixin * @instance * @example * // default title function shows "key: value" * chart.title(function(d) { return d.key + ': ' + d.value; }); * // title function has access to the standard d3 data binding and can get quite complicated * chart.title(function(p) { * return p.key.getFullYear() * + '\n' * + 'Index Gain: ' + numberFormat(p.value.absGain) + '\n' * + 'Index Gain in Percentage: ' + numberFormat(p.value.percentageGain) + '%\n' * + 'Fluctuation / Index Ratio: ' + numberFormat(p.value.fluctuationPercentage) + '%'; * }); * @param {Function} [titleFunction] * @returns {Function|dc.baseMixin} */ _chart.title = function (titleFunction) { if (!arguments.length) { return _title; } _title = titleFunction; return _chart; }; /** * Turn on/off title rendering, or return the state of the render title flag if no arguments are * given. * @method renderTitle * @memberof dc.baseMixin * @instance * @param {Boolean} [renderTitle=true] * @returns {Boolean|dc.baseMixin} */ _chart.renderTitle = function (renderTitle) { if (!arguments.length) { return _renderTitle; } _renderTitle = renderTitle; return _chart; }; /** * A renderlet is similar to an event listener on rendering event. Multiple renderlets can be added * to an individual chart. Each time a chart is rerendered or redrawn the renderlets are invoked * right after the chart finishes its transitions, giving you a way to modify the SVGElements. * Renderlet functions take the chart instance as the only input parameter and you can * use the dc API or use raw d3 to achieve pretty much any effect. * * Use {@link dc.baseMixin#on on} with a 'renderlet' prefix. * Generates a random key for the renderlet, which makes it hard to remove. * @method renderlet * @memberof dc.baseMixin * @instance * @deprecated * @example * // do this instead of .renderlet(function(chart) { ... }) * chart.on("renderlet", function(chart){ * // mix of dc API and d3 manipulation * chart.select('g.y').style('display', 'none'); * // its a closure so you can also access other chart variable available in the closure scope * moveChart.filter(chart.filter()); * }); * @param {Function} renderletFunction * @returns {dc.baseMixin} */ _chart.renderlet = dc.logger.deprecate(function (renderletFunction) { _chart.on('renderlet.' + dc.utils.uniqueId(), renderletFunction); return _chart; }, 'chart.renderlet has been deprecated. Please use chart.on("renderlet.<renderletKey>", renderletFunction)'); /** * Get or set the chart group to which this chart belongs. Chart groups are rendered or redrawn * together since it is expected they share the same underlying crossfilter data set. * @method chartGroup * @memberof dc.baseMixin * @instance * @param {String} [chartGroup] * @returns {String|dc.baseMixin} */ _chart.chartGroup = function (chartGroup) { if (!arguments.length) { return _chartGroup; } if (!_isChild) { dc.deregisterChart(_chart, _chartGroup); } _chartGroup = chartGroup; if (!_isChild) { dc.registerChart(_chart, _chartGroup); } return _chart; }; /** * Expire the internal chart cache. dc charts cache some data internally on a per chart basis to * speed up rendering and avoid unnecessary calculation; however it might be useful to clear the * cache if you have changed state which will affect rendering. For example, if you invoke * {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#crossfilter_add crossfilter.add} * function or reset group or dimension after rendering, it is a good idea to * clear the cache to make sure charts are rendered properly. * @method expireCache * @memberof dc.baseMixin * @instance * @returns {dc.baseMixin} */ _chart.expireCache = function () { // do nothing in base, should be overridden by sub-function return _chart; }; /** * Attach a dc.legend widget to this chart. The legend widget will automatically draw legend labels * based on the color setting and names associated with each group. * @method legend * @memberof dc.baseMixin * @instance * @example * chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) * @param {dc.legend} [legend] * @returns {dc.legend|dc.baseMixin} */ _chart.legend = function (legend) { if (!arguments.length) { return _legend; } _legend = legend; _legend.parent(_chart); return _chart; }; /** * Returns the internal numeric ID of the chart. * @method chartID * @memberof dc.baseMixin * @instance * @returns {String} */ _chart.chartID = function () { return _chart.__dcFlag__; }; /** * Set chart options using a configuration object. Each key in the object will cause the method of * the same name to be called with the value to set that attribute for the chart. * @method options * @memberof dc.baseMixin * @instance * @example * chart.options({dimension: myDimension, group: myGroup}); * @param {{}} opts * @returns {dc.baseMixin} */ _chart.options = function (opts) { var applyOptions = [ 'anchor', 'group', 'xAxisLabel', 'yAxisLabel', 'stack', 'title', 'point', 'getColor', 'overlayGeoJson' ]; for (var o in opts) { if (typeof(_chart[o]) === 'function') { if (opts[o] instanceof Array && applyOptions.indexOf(o) !== -1) { _chart[o].apply(_chart, opts[o]); } else { _chart[o].call(_chart, opts[o]); } } else { dc.logger.debug('Not a valid option setter name: ' + o); } } return _chart; }; /** * All dc chart instance supports the following listeners. * Supports the following events: * * `renderlet` - This listener function will be invoked after transitions after redraw and render. Replaces the * deprecated {@link dc.baseMixin#renderlet renderlet} method. * * `pretransition` - Like `.on('renderlet', ...)` but the event is fired before transitions start. * * `preRender` - This listener function will be invoked before chart rendering. * * `postRender` - This listener function will be invoked after chart finish rendering including * all renderlets' logic. * * `preRedraw` - This listener function will be invoked before chart redrawing. * * `postRedraw` - This listener function will be invoked after chart finish redrawing * including all renderlets' logic. * * `filtered` - This listener function will be invoked after a filter is applied, added or removed. * * `zoomed` - This listener function will be invoked after a zoom is triggered. * @method on * @memberof dc.baseMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Internals.md#dispatch_on d3.dispatch.on} * @example * .on('renderlet', function(chart, filter){...}) * .on('pretransition', function(chart, filter){...}) * .on('preRender', function(chart){...}) * .on('postRender', function(chart){...}) * .on('preRedraw', function(chart){...}) * .on('postRedraw', function(chart){...}) * .on('filtered', function(chart, filter){...}) * .on('zoomed', function(chart, filter){...}) * @param {String} event * @param {Function} listener * @returns {dc.baseMixin} */ _chart.on = function (event, listener) { _listeners.on(event, listener); return _chart; }; return _chart; }; /** * Margin is a mixin that provides margin utility functions for both the Row Chart and Coordinate Grid * Charts. * @name marginMixin * @memberof dc * @mixin * @param {Object} _chart * @returns {dc.marginMixin} */ dc.marginMixin = function (_chart) { var _margin = {top: 10, right: 50, bottom: 30, left: 30}; /** * Get or set the margins for a particular coordinate grid chart instance. The margins is stored as * an associative Javascript array. * @method margins * @memberof dc.marginMixin * @instance * @example * var leftMargin = chart.margins().left; // 30 by default * chart.margins().left = 50; * leftMargin = chart.margins().left; // now 50 * @param {{top: Number, right: Number, left: Number, bottom: Number}} [margins={top: 10, right: 50, bottom: 30, left: 30}] * @returns {{top: Number, right: Number, left: Number, bottom: Number}|dc.marginMixin} */ _chart.margins = function (margins) { if (!arguments.length) { return _margin; } _margin = margins; return _chart; }; _chart.effectiveWidth = function () { return _chart.width() - _chart.margins().left - _chart.margins().right; }; _chart.effectiveHeight = function () { return _chart.height() - _chart.margins().top - _chart.margins().bottom; }; return _chart; }; /** * The Color Mixin is an abstract chart functional class providing universal coloring support * as a mix-in for any concrete chart implementation. * @name colorMixin * @memberof dc * @mixin * @param {Object} _chart * @returns {dc.colorMixin} */ dc.colorMixin = function (_chart) { var _colors = d3.scale.category20c(); var _defaultAccessor = true; var _colorAccessor = function (d) { return _chart.keyAccessor()(d); }; /** * Retrieve current color scale or set a new color scale. This methods accepts any function that * operates like a d3 scale. * @method colors * @memberof dc.colorMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Scales.md d3.scale} * @example * // alternate categorical scale * chart.colors(d3.scale.category20b()); * // ordinal scale * chart.colors(d3.scale.ordinal().range(['red','green','blue'])); * // convenience method, the same as above * chart.ordinalColors(['red','green','blue']); * // set a linear scale * chart.linearColors(["#4575b4", "#ffffbf", "#a50026"]); * @param {d3.scale} [colorScale=d3.scale.category20c()] * @returns {d3.scale|dc.colorMixin} */ _chart.colors = function (colorScale) { if (!arguments.length) { return _colors; } if (colorScale instanceof Array) { _colors = d3.scale.quantize().range(colorScale); // deprecated legacy support, note: this fails for ordinal domains } else { _colors = d3.functor(colorScale); } return _chart; }; /** * Convenience method to set the color scale to * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md#ordinal d3.scale.ordinal} with * range `r`. * @method ordinalColors * @memberof dc.colorMixin * @instance * @param {Array<String>} r * @returns {dc.colorMixin} */ _chart.ordinalColors = function (r) { return _chart.colors(d3.scale.ordinal().range(r)); }; /** * Convenience method to set the color scale to an Hcl interpolated linear scale with range `r`. * @method linearColors * @memberof dc.colorMixin * @instance * @param {Array<Number>} r * @returns {dc.colorMixin} */ _chart.linearColors = function (r) { return _chart.colors(d3.scale.linear() .range(r) .interpolate(d3.interpolateHcl)); }; /** * Set or the get color accessor function. This function will be used to map a data point in a * crossfilter group to a color value on the color scale. The default function uses the key * accessor. * @method colorAccessor * @memberof dc.colorMixin * @instance * @example * // default index based color accessor * .colorAccessor(function (d, i){return i;}) * // color accessor for a multi-value crossfilter reduction * .colorAccessor(function (d){return d.value.absGain;}) * @param {Function} [colorAccessor] * @returns {Function|dc.colorMixin} */ _chart.colorAccessor = function (colorAccessor) { if (!arguments.length) { return _colorAccessor; } _colorAccessor = colorAccessor; _defaultAccessor = false; return _chart; }; // what is this? _chart.defaultColorAccessor = function () { return _defaultAccessor; }; /** * Set or get the current domain for the color mapping function. The domain must be supplied as an * array. * * Note: previously this method accepted a callback function. Instead you may use a custom scale * set by {@link dc.colorMixin#colors .colors}. * @method colorDomain * @memberof dc.colorMixin * @instance * @param {Array<String>} [domain] * @returns {Array<String>|dc.colorMixin} */ _chart.colorDomain = function (domain) { if (!arguments.length) { return _colors.domain(); } _colors.domain(domain); return _chart; }; /** * Set the domain by determining the min and max values as retrieved by * {@link dc.colorMixin#colorAccessor .colorAccessor} over the chart's dataset. * @method calculateColorDomain * @memberof dc.colorMixin * @instance * @returns {dc.colorMixin} */ _chart.calculateColorDomain = function () { var newDomain = [d3.min(_chart.data(), _chart.colorAccessor()), d3.max(_chart.data(), _chart.colorAccessor())]; _colors.domain(newDomain); return _chart; }; /** * Get the color for the datum d and counter i. This is used internally by charts to retrieve a color. * @method getColor * @memberof dc.colorMixin * @instance * @param {*} d * @param {Number} [i] * @returns {String} */ _chart.getColor = function (d, i) { return _colors(_colorAccessor.call(this, d, i)); }; /** * **Deprecated.** Get/set the color calculator. This actually replaces the * {@link dc.colorMixin#getColor getColor} method! * * This is not recommended, since using a {@link dc.colorMixin#colorAccessor colorAccessor} and * color scale ({@link dc.colorMixin#colors .colors}) is more powerful and idiomatic d3. * @method colorCalculator * @memberof dc.colorMixin * @instance * @param {*} [colorCalculator] * @returns {Function|dc.colorMixin} */ _chart.colorCalculator = dc.logger.deprecate(function (colorCalculator) { if (!arguments.length) { return _chart.getColor; } _chart.getColor = colorCalculator; return _chart; }, 'colorMixin.colorCalculator has been deprecated. Please colorMixin.colors and colorMixin.colorAccessor instead'); return _chart; }; /** * Coordinate Grid is an abstract base chart designed to support a number of coordinate grid based * concrete chart types, e.g. bar chart, line chart, and bubble chart. * @name coordinateGridMixin * @memberof dc * @mixin * @mixes dc.colorMixin * @mixes dc.marginMixin * @mixes dc.baseMixin * @param {Object} _chart * @returns {dc.coordinateGridMixin} */ dc.coordinateGridMixin = function (_chart) { var GRID_LINE_CLASS = 'grid-line'; var HORIZONTAL_CLASS = 'horizontal'; var VERTICAL_CLASS = 'vertical'; var Y_AXIS_LABEL_CLASS = 'y-axis-label'; var X_AXIS_LABEL_CLASS = 'x-axis-label'; var DEFAULT_AXIS_LABEL_PADDING = 12; _chart = dc.colorMixin(dc.marginMixin(dc.baseMixin(_chart))); _chart.colors(d3.scale.category10()); _chart._mandatoryAttributes().push('x'); var _parent; var _g; var _chartBodyG; var _x; var _xOriginalDomain; var _xAxis = d3.svg.axis().orient('bottom'); var _xUnits = dc.units.integers; var _xAxisPadding = 0; var _xAxisPaddingUnit = 'day'; var _xElasticity = false; var _xAxisLabel; var _xAxisLabelPadding = 0; var _lastXDomain; var _y; var _yAxis = d3.svg.axis().orient('left'); var _yAxisPadding = 0; var _yElasticity = false; var _yAxisLabel; var _yAxisLabelPadding = 0; var _brush = d3.svg.brush(); var _brushOn = true; var _round; var _renderHorizontalGridLine = false; var _renderVerticalGridLine = false; var _refocused = false, _resizing = false; var _unitCount; var _zoomScale = [1, Infinity]; var _zoomOutRestrict = true; var _zoom = d3.behavior.zoom().on('zoom', zoomHandler); var _nullZoom = d3.behavior.zoom().on('zoom', null); var _hasBeenMouseZoomable = false; var _rangeChart; var _focusChart; var _mouseZoomable = false; var _clipPadding = 0; var _outerRangeBandPadding = 0.5; var _rangeBandPadding = 0; var _useRightYAxis = false; /** * When changing the domain of the x or y scale, it is necessary to tell the chart to recalculate * and redraw the axes. (`.rescale()` is called automatically when the x or y scale is replaced * with {@link dc.coordinateGridMixin+x .x()} or {@link dc.coordinateGridMixin#y .y()}, and has * no effect on elastic scales.) * @method rescale * @memberof dc.coordinateGridMixin * @instance * @returns {dc.coordinateGridMixin} */ _chart.rescale = function () { _unitCount = undefined; _resizing = true; return _chart; }; _chart.resizing = function () { return _resizing; }; /** * Get or set the range selection chart associated with this instance. Setting the range selection * chart using this function will automatically update its selection brush when the current chart * zooms in. In return the given range chart will also automatically attach this chart as its focus * chart hence zoom in when range brush updates. * * Usually the range and focus charts will share a dimension. The range chart will set the zoom * boundaries for the focus chart, so its dimension values must be compatible with the domain of * the focus chart. * * See the [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) example for this effect in action. * @method rangeChart * @memberof dc.coordinateGridMixin * @instance * @param {dc.coordinateGridMixin} [rangeChart] * @returns {dc.coordinateGridMixin} */ _chart.rangeChart = function (rangeChart) { if (!arguments.length) { return _rangeChart; } _rangeChart = rangeChart; _rangeChart.focusChart(_chart); return _chart; }; /** * Get or set the scale extent for mouse zooms. * @method zoomScale * @memberof dc.coordinateGridMixin * @instance * @param {Array<Number|Date>} [extent=[1, Infinity]] * @returns {Array<Number|Date>|dc.coordinateGridMixin} */ _chart.zoomScale = function (extent) { if (!arguments.length) { return _zoomScale; } _zoomScale = extent; return _chart; }; /** * Get or set the zoom restriction for the chart. If true limits the zoom to origional domain of the chart. * @method zoomOutRestrict * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [zoomOutRestrict=true] * @returns {Boolean|dc.coordinateGridMixin} */ _chart.zoomOutRestrict = function (zoomOutRestrict) { if (!arguments.length) { return _zoomOutRestrict; } _zoomScale[0] = zoomOutRestrict ? 1 : 0; _zoomOutRestrict = zoomOutRestrict; return _chart; }; _chart._generateG = function (parent) { if (parent === undefined) { _parent = _chart.svg(); } else { _parent = parent; } var href = window.location.href.split('#')[0]; _g = _parent.append('g'); _chartBodyG = _g.append('g').attr('class', 'chart-body') .attr('transform', 'translate(' + _chart.margins().left + ', ' + _chart.margins().top + ')') .attr('clip-path', 'url(' + href + '#' + getClipPathId() + ')'); return _g; }; /** * Get or set the root g element. This method is usually used to retrieve the g element in order to * overlay custom svg drawing programatically. **Caution**: The root g element is usually generated * by dc.js internals, and resetting it might produce unpredictable result. * @method g * @memberof dc.coordinateGridMixin * @instance * @param {SVGElement} [gElement] * @returns {SVGElement|dc.coordinateGridMixin} */ _chart.g = function (gElement) { if (!arguments.length) { return _g; } _g = gElement; return _chart; }; /** * Set or get mouse zoom capability flag (default: false). When turned on the chart will be * zoomable using the mouse wheel. If the range selector chart is attached zooming will also update * the range selection brush on the associated range selector chart. * @method mouseZoomable * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [mouseZoomable=false] * @returns {Boolean|dc.coordinateGridMixin} */ _chart.mouseZoomable = function (mouseZoomable) { if (!arguments.length) { return _mouseZoomable; } _mouseZoomable = mouseZoomable; return _chart; }; /** * Retrieve the svg group for the chart body. * @method chartBodyG * @memberof dc.coordinateGridMixin * @instance * @param {SVGElement} [chartBodyG] * @returns {SVGElement} */ _chart.chartBodyG = function (chartBodyG) { if (!arguments.length) { return _chartBodyG; } _chartBodyG = chartBodyG; return _chart; }; /** * **mandatory** * * Get or set the x scale. The x scale can be any d3 * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Quantitative-Scales.md quantitive scale} or * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md ordinal scale}. * @method x * @memberof dc.coordinateGridMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Scales.md d3.scale} * @example * // set x to a linear scale * chart.x(d3.scale.linear().domain([-2500, 2500])) * // set x to a time scale to generate histogram * chart.x(d3.time.scale().domain([new Date(1985, 0, 1), new Date(2012, 11, 31)])) * @param {d3.scale} [xScale] * @returns {d3.scale|dc.coordinateGridMixin} */ _chart.x = function (xScale) { if (!arguments.length) { return _x; } _x = xScale; _xOriginalDomain = _x.domain(); _chart.rescale(); return _chart; }; _chart.xOriginalDomain = function () { return _xOriginalDomain; }; /** * Set or get the xUnits function. The coordinate grid chart uses the xUnits function to calculate * the number of data projections on x axis such as the number of bars for a bar chart or the * number of dots for a line chart. This function is expected to return a Javascript array of all * data points on x axis, or the number of points on the axis. [d3 time range functions * d3.time.days, d3.time.months, and * d3.time.years](https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Intervals.md#aliases) are all valid xUnits * function. dc.js also provides a few units function, see the {@link dc.units Units Namespace} for * a list of built-in units functions. * @method xUnits * @memberof dc.coordinateGridMixin * @instance * @todo Add docs for utilities * @example * // set x units to count days * chart.xUnits(d3.time.days); * // set x units to count months * chart.xUnits(d3.time.months); * * // A custom xUnits function can be used as long as it follows the following interface: * // units in integer * function(start, end, xDomain) { * // simply calculates how many integers in the domain * return Math.abs(end - start); * }; * * // fixed units * function(start, end, xDomain) { * // be aware using fixed units will disable the focus/zoom ability on the chart * return 1000; * @param {Function} [xUnits=dc.units.integers] * @returns {Function|dc.coordinateGridMixin} */ _chart.xUnits = function (xUnits) { if (!arguments.length) { return _xUnits; } _xUnits = xUnits; return _chart; }; /** * Set or get the x axis used by a particular coordinate grid chart instance. This function is most * useful when x axis customization is required. The x axis in dc.js is an instance of a * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#axis d3 axis object}; * therefore it supports any valid d3 axis manipulation. * * **Caution**: The x axis is usually generated internally by dc; resetting it may cause * unexpected results. Note also that when used as a getter, this function is not chainable: * it returns the axis, not the chart, * {@link https://github.com/dc-js/dc.js/wiki/FAQ#why-does-everything-break-after-a-call-to-xaxis-or-yaxis * so attempting to call chart functions after calling `.xAxis()` will fail}. * @method xAxis * @memberof dc.coordinateGridMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#axis d3.svg.axis} * @example * // customize x axis tick format * chart.xAxis().tickFormat(function(v) {return v + '%';}); * // customize x axis tick values * chart.xAxis().tickValues([0, 100, 200, 300]); * @param {d3.svg.axis} [xAxis=d3.svg.axis().orient('bottom')] * @returns {d3.svg.axis|dc.coordinateGridMixin} */ _chart.xAxis = function (xAxis) { if (!arguments.length) { return _xAxis; } _xAxis = xAxis; return _chart; }; /** * Turn on/off elastic x axis behavior. If x axis elasticity is turned on, then the grid chart will * attempt to recalculate the x axis range whenever a redraw event is triggered. * @method elasticX * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [elasticX=false] * @returns {Boolean|dc.coordinateGridMixin} */ _chart.elasticX = function (elasticX) { if (!arguments.length) { return _xElasticity; } _xElasticity = elasticX; return _chart; }; /** * Set or get x axis padding for the elastic x axis. The padding will be added to both end of the x * axis if elasticX is turned on; otherwise it is ignored. * * Padding can be an integer or percentage in string (e.g. '10%'). Padding can be applied to * number or date x axes. When padding a date axis, an integer represents number of units being padded * and a percentage string will be treated the same as an integer. The unit will be determined by the * xAxisPaddingUnit variable. * @method xAxisPadding * @memberof dc.coordinateGridMixin * @instance * @param {Number|String} [padding=0] * @returns {Number|String|dc.coordinateGridMixin} */ _chart.xAxisPadding = function (padding) { if (!arguments.length) { return _xAxisPadding; } _xAxisPadding = padding; return _chart; }; /** * Set or get x axis padding unit for the elastic x axis. The padding unit will determine which unit to * use when applying xAxis padding if elasticX is turned on and if x-axis uses a time dimension; * otherwise it is ignored. * * Padding unit is a string that will be used when the padding is calculated. Available parameters are * the available d3 time intervals; see * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Intervals.md#interval d3.time.interval}. * @method xAxisPaddingUnit * @memberof dc.coordinateGridMixin * @instance * @param {String} [unit='days'] * @returns {String|dc.coordinateGridMixin} */ _chart.xAxisPaddingUnit = function (unit) { if (!arguments.length) { return _xAxisPaddingUnit; } _xAxisPaddingUnit = unit; return _chart; }; /** * Returns the number of units displayed on the x axis using the unit measure configured by * {@link dc.coordinateGridMixin#xUnits xUnits}. * @method xUnitCount * @memberof dc.coordinateGridMixin * @instance * @returns {Number} */ _chart.xUnitCount = function () { if (_unitCount === undefined) { var units = _chart.xUnits()(_chart.x().domain()[0], _chart.x().domain()[1], _chart.x().domain()); if (units instanceof Array) { _unitCount = units.length; } else { _unitCount = units; } } return _unitCount; }; /** * Gets or sets whether the chart should be drawn with a right axis instead of a left axis. When * used with a chart in a composite chart, allows both left and right Y axes to be shown on a * chart. * @method useRightYAxis * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [useRightYAxis=false] * @returns {Boolean|dc.coordinateGridMixin} */ _chart.useRightYAxis = function (useRightYAxis) { if (!arguments.length) { return _useRightYAxis; } _useRightYAxis = useRightYAxis; return _chart; }; /** * Returns true if the chart is using ordinal xUnits ({@link dc.units.ordinal dc.units.ordinal}, or false * otherwise. Most charts behave differently with ordinal data and use the result of this method to * trigger the appropriate logic. * @method isOrdinal * @memberof dc.coordinateGridMixin * @instance * @returns {Boolean} */ _chart.isOrdinal = function () { return _chart.xUnits() === dc.units.ordinal; }; _chart._useOuterPadding = function () { return true; }; _chart._ordinalXDomain = function () { var groups = _chart._computeOrderedGroups(_chart.data()); return groups.map(_chart.keyAccessor()); }; function compareDomains (d1, d2) { return !d1 || !d2 || d1.length !== d2.length || d1.some(function (elem, i) { return (elem && d2[i]) ? elem.toString() !== d2[i].toString() : elem === d2[i]; }); } function prepareXAxis (g, render) { if (!_chart.isOrdinal()) { if (_chart.elasticX()) { _x.domain([_chart.xAxisMin(), _chart.xAxisMax()]); } } else { // _chart.isOrdinal() if (_chart.elasticX() || _x.domain().length === 0) { _x.domain(_chart._ordinalXDomain()); } } // has the domain changed? var xdom = _x.domain(); if (render || compareDomains(_lastXDomain, xdom)) { _chart.rescale(); } _lastXDomain = xdom; // please can't we always use rangeBands for bar charts? if (_chart.isOrdinal()) { _x.rangeBands([0, _chart.xAxisLength()], _rangeBandPadding, _chart._useOuterPadding() ? _outerRangeBandPadding : 0); } else { _x.range([0, _chart.xAxisLength()]); } _xAxis = _xAxis.scale(_chart.x()); renderVerticalGridLines(g); } _chart.renderXAxis = function (g) { var axisXG = g.select('g.x'); if (axisXG.empty()) { axisXG = g.append('g') .attr('class', 'axis x') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart._xAxisY() + ')'); } var axisXLab = g.select('text.' + X_AXIS_LABEL_CLASS); if (axisXLab.empty() && _chart.xAxisLabel()) { axisXLab = g.append('text') .attr('class', X_AXIS_LABEL_CLASS) .attr('transform', 'translate(' + (_chart.margins().left + _chart.xAxisLength() / 2) + ',' + (_chart.height() - _xAxisLabelPadding) + ')') .attr('text-anchor', 'middle'); } if (_chart.xAxisLabel() && axisXLab.text() !== _chart.xAxisLabel()) { axisXLab.text(_chart.xAxisLabel()); } dc.transition(axisXG, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart._xAxisY() + ')') .call(_xAxis); dc.transition(axisXLab, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', 'translate(' + (_chart.margins().left + _chart.xAxisLength() / 2) + ',' + (_chart.height() - _xAxisLabelPadding) + ')'); }; function renderVerticalGridLines (g) { var gridLineG = g.select('g.' + VERTICAL_CLASS); if (_renderVerticalGridLine) { if (gridLineG.empty()) { gridLineG = g.insert('g', ':first-child') .attr('class', GRID_LINE_CLASS + ' ' + VERTICAL_CLASS) .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); } var ticks = _xAxis.tickValues() ? _xAxis.tickValues() : (typeof _x.ticks === 'function' ? _x.ticks(_xAxis.ticks()[0]) : _x.domain()); var lines = gridLineG.selectAll('line') .data(ticks); // enter var linesGEnter = lines.enter() .append('line') .attr('x1', function (d) { return _x(d); }) .attr('y1', _chart._xAxisY() - _chart.margins().top) .attr('x2', function (d) { return _x(d); }) .attr('y2', 0) .attr('opacity', 0); dc.transition(linesGEnter, _chart.transitionDuration(), _chart.transitionDelay()) .attr('opacity', 1); // update dc.transition(lines, _chart.transitionDuration(), _chart.transitionDelay()) .attr('x1', function (d) { return _x(d); }) .attr('y1', _chart._xAxisY() - _chart.margins().top) .attr('x2', function (d) { return _x(d); }) .attr('y2', 0); // exit lines.exit().remove(); } else { gridLineG.selectAll('line').remove(); } } _chart._xAxisY = function () { return (_chart.height() - _chart.margins().bottom); }; _chart.xAxisLength = function () { return _chart.effectiveWidth(); }; /** * Set or get the x axis label. If setting the label, you may optionally include additional padding to * the margin to make room for the label. By default the padded is set to 12 to accomodate the text height. * @method xAxisLabel * @memberof dc.coordinateGridMixin * @instance * @param {String} [labelText] * @param {Number} [padding=12] * @returns {String} */ _chart.xAxisLabel = function (labelText, padding) { if (!arguments.length) { return _xAxisLabel; } _xAxisLabel = labelText; _chart.margins().bottom -= _xAxisLabelPadding; _xAxisLabelPadding = (padding === undefined) ? DEFAULT_AXIS_LABEL_PADDING : padding; _chart.margins().bottom += _xAxisLabelPadding; return _chart; }; _chart._prepareYAxis = function (g) { if (_y === undefined || _chart.elasticY()) { if (_y === undefined) { _y = d3.scale.linear(); } var min = _chart.yAxisMin() || 0, max = _chart.yAxisMax() || 0; _y.domain([min, max]).rangeRound([_chart.yAxisHeight(), 0]); } _y.range([_chart.yAxisHeight(), 0]); _yAxis = _yAxis.scale(_y); if (_useRightYAxis) { _yAxis.orient('right'); } _chart._renderHorizontalGridLinesForAxis(g, _y, _yAxis); }; _chart.renderYAxisLabel = function (axisClass, text, rotation, labelXPosition) { labelXPosition = labelXPosition || _yAxisLabelPadding; var axisYLab = _chart.g().select('text.' + Y_AXIS_LABEL_CLASS + '.' + axisClass + '-label'); var labelYPosition = (_chart.margins().top + _chart.yAxisHeight() / 2); if (axisYLab.empty() && text) { axisYLab = _chart.g().append('text') .attr('transform', 'translate(' + labelXPosition + ',' + labelYPosition + '),rotate(' + rotation + ')') .attr('class', Y_AXIS_LABEL_CLASS + ' ' + axisClass + '-label') .attr('text-anchor', 'middle') .text(text); } if (text && axisYLab.text() !== text) { axisYLab.text(text); } dc.transition(axisYLab, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', 'translate(' + labelXPosition + ',' + labelYPosition + '),rotate(' + rotation + ')'); }; _chart.renderYAxisAt = function (axisClass, axis, position) { var axisYG = _chart.g().select('g.' + axisClass); if (axisYG.empty()) { axisYG = _chart.g().append('g') .attr('class', 'axis ' + axisClass) .attr('transform', 'translate(' + position + ',' + _chart.margins().top + ')'); } dc.transition(axisYG, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', 'translate(' + position + ',' + _chart.margins().top + ')') .call(axis); }; _chart.renderYAxis = function () { var axisPosition = _useRightYAxis ? (_chart.width() - _chart.margins().right) : _chart._yAxisX(); _chart.renderYAxisAt('y', _yAxis, axisPosition); var labelPosition = _useRightYAxis ? (_chart.width() - _yAxisLabelPadding) : _yAxisLabelPadding; var rotation = _useRightYAxis ? 90 : -90; _chart.renderYAxisLabel('y', _chart.yAxisLabel(), rotation, labelPosition); }; _chart._renderHorizontalGridLinesForAxis = function (g, scale, axis) { var gridLineG = g.select('g.' + HORIZONTAL_CLASS); if (_renderHorizontalGridLine) { var ticks = axis.tickValues() ? axis.tickValues() : scale.ticks(axis.ticks()[0]); if (gridLineG.empty()) { gridLineG = g.insert('g', ':first-child') .attr('class', GRID_LINE_CLASS + ' ' + HORIZONTAL_CLASS) .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); } var lines = gridLineG.selectAll('line') .data(ticks); // enter var linesGEnter = lines.enter() .append('line') .attr('x1', 1) .attr('y1', function (d) { return scale(d); }) .attr('x2', _chart.xAxisLength()) .attr('y2', function (d) { return scale(d); }) .attr('opacity', 0); dc.transition(linesGEnter, _chart.transitionDuration(), _chart.transitionDelay()) .attr('opacity', 1); // update dc.transition(lines, _chart.transitionDuration(), _chart.transitionDelay()) .attr('x1', 1) .attr('y1', function (d) { return scale(d); }) .attr('x2', _chart.xAxisLength()) .attr('y2', function (d) { return scale(d); }); // exit lines.exit().remove(); } else { gridLineG.selectAll('line').remove(); } }; _chart._yAxisX = function () { return _chart.useRightYAxis() ? _chart.width() - _chart.margins().right : _chart.margins().left; }; /** * Set or get the y axis label. If setting the label, you may optionally include additional padding * to the margin to make room for the label. By default the padding is set to 12 to accommodate the * text height. * @method yAxisLabel * @memberof dc.coordinateGridMixin * @instance * @param {String} [labelText] * @param {Number} [padding=12] * @returns {String|dc.coordinateGridMixin} */ _chart.yAxisLabel = function (labelText, padding) { if (!arguments.length) { return _yAxisLabel; } _yAxisLabel = labelText; _chart.margins().left -= _yAxisLabelPadding; _yAxisLabelPadding = (padding === undefined) ? DEFAULT_AXIS_LABEL_PADDING : padding; _chart.margins().left += _yAxisLabelPadding; return _chart; }; /** * Get or set the y scale. The y scale is typically automatically determined by the chart implementation. * @method y * @memberof dc.coordinateGridMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Scales.md d3.scale} * @param {d3.scale} [yScale] * @returns {d3.scale|dc.coordinateGridMixin} */ _chart.y = function (yScale) { if (!arguments.length) { return _y; } _y = yScale; _chart.rescale(); return _chart; }; /** * Set or get the y axis used by the coordinate grid chart instance. This function is most useful * when y axis customization is required. The y axis in dc.js is simply an instance of a [d3 axis * object](https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#axis); therefore it supports any * valid d3 axis manipulation. * * **Caution**: The y axis is usually generated internally by dc; resetting it may cause * unexpected results. Note also that when used as a getter, this function is not chainable: it * returns the axis, not the chart, * {@link https://github.com/dc-js/dc.js/wiki/FAQ#why-does-everything-break-after-a-call-to-xaxis-or-yaxis * so attempting to call chart functions after calling `.yAxis()` will fail}. * @method yAxis * @memberof dc.coordinateGridMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#axis d3.svg.axis} * @example * // customize y axis tick format * chart.yAxis().tickFormat(function(v) {return v + '%';}); * // customize y axis tick values * chart.yAxis().tickValues([0, 100, 200, 300]); * @param {d3.svg.axis} [yAxis=d3.svg.axis().orient('left')] * @returns {d3.svg.axis|dc.coordinateGridMixin} */ _chart.yAxis = function (yAxis) { if (!arguments.length) { return _yAxis; } _yAxis = yAxis; return _chart; }; /** * Turn on/off elastic y axis behavior. If y axis elasticity is turned on, then the grid chart will * attempt to recalculate the y axis range whenever a redraw event is triggered. * @method elasticY * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [elasticY=false] * @returns {Boolean|dc.coordinateGridMixin} */ _chart.elasticY = function (elasticY) { if (!arguments.length) { return _yElasticity; } _yElasticity = elasticY; return _chart; }; /** * Turn on/off horizontal grid lines. * @method renderHorizontalGridLines * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [renderHorizontalGridLines=false] * @returns {Boolean|dc.coordinateGridMixin} */ _chart.renderHorizontalGridLines = function (renderHorizontalGridLines) { if (!arguments.length) { return _renderHorizontalGridLine; } _renderHorizontalGridLine = renderHorizontalGridLines; return _chart; }; /** * Turn on/off vertical grid lines. * @method renderVerticalGridLines * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [renderVerticalGridLines=false] * @returns {Boolean|dc.coordinateGridMixin} */ _chart.renderVerticalGridLines = function (renderVerticalGridLines) { if (!arguments.length) { return _renderVerticalGridLine; } _renderVerticalGridLine = renderVerticalGridLines; return _chart; }; /** * Calculates the minimum x value to display in the chart. Includes xAxisPadding if set. * @method xAxisMin * @memberof dc.coordinateGridMixin * @instance * @returns {*} */ _chart.xAxisMin = function () { var min = d3.min(_chart.data(), function (e) { return _chart.keyAccessor()(e); }); return dc.utils.subtract(min, _xAxisPadding, _xAxisPaddingUnit); }; /** * Calculates the maximum x value to display in the chart. Includes xAxisPadding if set. * @method xAxisMax * @memberof dc.coordinateGridMixin * @instance * @returns {*} */ _chart.xAxisMax = function () { var max = d3.max(_chart.data(), function (e) { return _chart.keyAccessor()(e); }); return dc.utils.add(max, _xAxisPadding, _xAxisPaddingUnit); }; /** * Calculates the minimum y value to display in the chart. Includes yAxisPadding if set. * @method yAxisMin * @memberof dc.coordinateGridMixin * @instance * @returns {*} */ _chart.yAxisMin = function () { var min = d3.min(_chart.data(), function (e) { return _chart.valueAccessor()(e); }); return dc.utils.subtract(min, _yAxisPadding); }; /** * Calculates the maximum y value to display in the chart. Includes yAxisPadding if set. * @method yAxisMax * @memberof dc.coordinateGridMixin * @instance * @returns {*} */ _chart.yAxisMax = function () { var max = d3.max(_chart.data(), function (e) { return _chart.valueAccessor()(e); }); return dc.utils.add(max, _yAxisPadding); }; /** * Set or get y axis padding for the elastic y axis. The padding will be added to the top and * bottom of the y axis if elasticY is turned on; otherwise it is ignored. * * Padding can be an integer or percentage in string (e.g. '10%'). Padding can be applied to * number or date axes. When padding a date axis, an integer represents number of days being padded * and a percentage string will be treated the same as an integer. * @method yAxisPadding * @memberof dc.coordinateGridMixin * @instance * @param {Number|String} [padding=0] * @returns {Number|dc.coordinateGridMixin} */ _chart.yAxisPadding = function (padding) { if (!arguments.length) { return _yAxisPadding; } _yAxisPadding = padding; return _chart; }; _chart.yAxisHeight = function () { return _chart.effectiveHeight(); }; /** * Set or get the rounding function used to quantize the selection when brushing is enabled. * @method round * @memberof dc.coordinateGridMixin * @instance * @example * // set x unit round to by month, this will make sure range selection brush will * // select whole months * chart.round(d3.time.month.round); * @param {Function} [round] * @returns {Function|dc.coordinateGridMixin} */ _chart.round = function (round) { if (!arguments.length) { return _round; } _round = round; return _chart; }; _chart._rangeBandPadding = function (_) { if (!arguments.length) { return _rangeBandPadding; } _rangeBandPadding = _; return _chart; }; _chart._outerRangeBandPadding = function (_) { if (!arguments.length) { return _outerRangeBandPadding; } _outerRangeBandPadding = _; return _chart; }; dc.override(_chart, 'filter', function (_) { if (!arguments.length) { return _chart._filter(); } _chart._filter(_); if (_) { _chart.brush().extent(_); } else { _chart.brush().clear(); } return _chart; }); _chart.brush = function (_) { if (!arguments.length) { return _brush; } _brush = _; return _chart; }; function brushHeight () { return _chart._xAxisY() - _chart.margins().top; } _chart.renderBrush = function (g) { if (_brushOn) { _brush.on('brush', _chart._brushing); _brush.on('brushstart', _chart._disableMouseZoom); _brush.on('brushend', configureMouseZoom); var gBrush = g.append('g') .attr('class', 'brush') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')') .call(_brush.x(_chart.x())); _chart.setBrushY(gBrush, false); _chart.setHandlePaths(gBrush); if (_chart.hasFilter()) { _chart.redrawBrush(g, false); } } }; _chart.setHandlePaths = function (gBrush) { gBrush.selectAll('.resize').append('path').attr('d', _chart.resizeHandlePath); }; _chart.setBrushY = function (gBrush) { gBrush.selectAll('rect') .attr('height', brushHeight()); gBrush.selectAll('.resize path') .attr('d', _chart.resizeHandlePath); }; _chart.extendBrush = function () { var extent = _brush.extent(); if (_chart.round()) { extent[0] = extent.map(_chart.round())[0]; extent[1] = extent.map(_chart.round())[1]; _g.select('.brush') .call(_brush.extent(extent)); } return extent; }; _chart.brushIsEmpty = function (extent) { return _brush.empty() || !extent || extent[1] <= extent[0]; }; _chart._brushing = function () { var extent = _chart.extendBrush(); _chart.redrawBrush(_g, false); if (_chart.brushIsEmpty(extent)) { dc.events.trigger(function () { _chart.filter(null); _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); } else { var rangedFilter = dc.filters.RangedFilter(extent[0], extent[1]); dc.events.trigger(function () { _chart.replaceFilter(rangedFilter); _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); } }; _chart.redrawBrush = function (g, doTransition) { if (_brushOn) { if (_chart.filter() && _chart.brush().empty()) { _chart.brush().extent(_chart.filter()); } var gBrush = dc.optionalTransition(doTransition, _chart.transitionDuration(), _chart.transitionDelay())(g.select('g.brush')); _chart.setBrushY(gBrush); gBrush.call(_chart.brush() .x(_chart.x()) .extent(_chart.brush().extent())); } _chart.fadeDeselectedArea(); }; _chart.fadeDeselectedArea = function () { // do nothing, sub-chart should override this function }; // borrowed from Crossfilter example _chart.resizeHandlePath = function (d) { var e = +(d === 'e'), x = e ? 1 : -1, y = brushHeight() / 3; return 'M' + (0.5 * x) + ',' + y + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) + 'V' + (2 * y - 6) + 'A6,6 0 0 ' + e + ' ' + (0.5 * x) + ',' + (2 * y) + 'Z' + 'M' + (2.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8) + 'M' + (4.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8); }; function getClipPathId () { return _chart.anchorName().replace(/[ .#=\[\]]/g, '-') + '-clip'; } /** * Get or set the padding in pixels for the clip path. Once set padding will be applied evenly to * the top, left, right, and bottom when the clip path is generated. If set to zero, the clip area * will be exactly the chart body area minus the margins. * @method clipPadding * @memberof dc.coordinateGridMixin * @instance * @param {Number} [padding=5] * @returns {Number|dc.coordinateGridMixin} */ _chart.clipPadding = function (padding) { if (!arguments.length) { return _clipPadding; } _clipPadding = padding; return _chart; }; function generateClipPath () { var defs = dc.utils.appendOrSelect(_parent, 'defs'); // cannot select <clippath> elements; bug in WebKit, must select by id // https://groups.google.com/forum/#!topic/d3-js/6EpAzQ2gU9I var id = getClipPathId(); var chartBodyClip = dc.utils.appendOrSelect(defs, '#' + id, 'clipPath').attr('id', id); var padding = _clipPadding * 2; dc.utils.appendOrSelect(chartBodyClip, 'rect') .attr('width', _chart.xAxisLength() + padding) .attr('height', _chart.yAxisHeight() + padding) .attr('transform', 'translate(-' + _clipPadding + ', -' + _clipPadding + ')'); } _chart._preprocessData = function () {}; _chart._doRender = function () { _chart.resetSvg(); _chart._preprocessData(); _chart._generateG(); generateClipPath(); drawChart(true); configureMouseZoom(); return _chart; }; _chart._doRedraw = function () { _chart._preprocessData(); drawChart(false); generateClipPath(); return _chart; }; function drawChart (render) { if (_chart.isOrdinal()) { _brushOn = false; } prepareXAxis(_chart.g(), render); _chart._prepareYAxis(_chart.g()); _chart.plotData(); if (_chart.elasticX() || _resizing || render) { _chart.renderXAxis(_chart.g()); } if (_chart.elasticY() || _resizing || render) { _chart.renderYAxis(_chart.g()); } if (render) { _chart.renderBrush(_chart.g(), false); } else { _chart.redrawBrush(_chart.g(), _resizing); } _chart.fadeDeselectedArea(); _resizing = false; } function configureMouseZoom () { if (_mouseZoomable) { _chart._enableMouseZoom(); } else if (_hasBeenMouseZoomable) { _chart._disableMouseZoom(); } } _chart._enableMouseZoom = function () { _hasBeenMouseZoomable = true; _zoom.x(_chart.x()) .scaleExtent(_zoomScale) .size([_chart.width(), _chart.height()]) .duration(_chart.transitionDuration()); _chart.root().call(_zoom); }; _chart._disableMouseZoom = function () { _chart.root().call(_nullZoom); }; function zoomHandler () { _refocused = true; if (_zoomOutRestrict) { var constraint = _xOriginalDomain; if (_rangeChart) { constraint = intersectExtents(constraint, _rangeChart.x().domain()); } var constrained = constrainExtent(_chart.x().domain(), constraint); if (constrained) { _chart.x().domain(constrained); } } var domain = _chart.x().domain(); var domFilter = dc.filters.RangedFilter(domain[0], domain[1]); _chart.replaceFilter(domFilter); _chart.rescale(); _chart.redraw(); if (_rangeChart && !rangesEqual(_chart.filter(), _rangeChart.filter())) { dc.events.trigger(function () { _rangeChart.replaceFilter(domFilter); _rangeChart.redraw(); }); } _chart._invokeZoomedListener(); dc.events.trigger(function () { _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); _refocused = !rangesEqual(domain, _xOriginalDomain); } function intersectExtents (ext1, ext2) { if (ext1[0] > ext2[1] || ext1[1] < ext2[0]) { console.warn('could not intersect extents'); } return [Math.max(ext1[0], ext2[0]), Math.min(ext1[1], ext2[1])]; } function constrainExtent (extent, constraint) { var size = extent[1] - extent[0]; if (extent[0] < constraint[0]) { return [constraint[0], Math.min(constraint[1], dc.utils.add(constraint[0], size, 'millis'))]; } else if (extent[1] > constraint[1]) { return [Math.max(constraint[0], dc.utils.subtract(constraint[1], size, 'millis')), constraint[1]]; } else { return null; } } /** * Zoom this chart to focus on the given range. The given range should be an array containing only * 2 elements (`[start, end]`) defining a range in the x domain. If the range is not given or set * to null, then the zoom will be reset. _For focus to work elasticX has to be turned off; * otherwise focus will be ignored. * @method focus * @memberof dc.coordinateGridMixin * @instance * @example * chart.on('renderlet', function(chart) { * // smooth the rendering through event throttling * dc.events.trigger(function(){ * // focus some other chart to the range selected by user on this chart * someOtherChart.focus(chart.filter()); * }); * }) * @param {Array<Number>} [range] */ _chart.focus = function (range) { if (hasRangeSelected(range)) { _chart.x().domain(range); } else { _chart.x().domain(_xOriginalDomain); } _zoom.x(_chart.x()); zoomHandler(); }; _chart.refocused = function () { return _refocused; }; _chart.focusChart = function (c) { if (!arguments.length) { return _focusChart; } _focusChart = c; _chart.on('filtered', function (chart) { if (!chart.filter()) { dc.events.trigger(function () { _focusChart.x().domain(_focusChart.xOriginalDomain()); }); } else if (!rangesEqual(chart.filter(), _focusChart.filter())) { dc.events.trigger(function () { _focusChart.focus(chart.filter()); }); } }); return _chart; }; function rangesEqual (range1, range2) { if (!range1 && !range2) { return true; } else if (!range1 || !range2) { return false; } else if (range1.length === 0 && range2.length === 0) { return true; } else if (range1[0].valueOf() === range2[0].valueOf() && range1[1].valueOf() === range2[1].valueOf()) { return true; } return false; } /** * Turn on/off the brush-based range filter. When brushing is on then user can drag the mouse * across a chart with a quantitative scale to perform range filtering based on the extent of the * brush, or click on the bars of an ordinal bar chart or slices of a pie chart to filter and * un-filter them. However turning on the brush filter will disable other interactive elements on * the chart such as highlighting, tool tips, and reference lines. Zooming will still be possible * if enabled, but only via scrolling (panning will be disabled.) * @method brushOn * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [brushOn=true] * @returns {Boolean|dc.coordinateGridMixin} */ _chart.brushOn = function (brushOn) { if (!arguments.length) { return _brushOn; } _brushOn = brushOn; return _chart; }; function hasRangeSelected (range) { return range instanceof Array && range.length > 1; } return _chart; }; /** * Stack Mixin is an mixin that provides cross-chart support of stackability using d3.layout.stack. * @name stackMixin * @memberof dc * @mixin * @param {Object} _chart * @returns {dc.stackMixin} */ dc.stackMixin = function (_chart) { function prepareValues (layer, layerIdx) { var valAccessor = layer.accessor || _chart.valueAccessor(); layer.name = String(layer.name || layerIdx); layer.values = layer.group.all().map(function (d, i) { return { x: _chart.keyAccessor()(d, i), y: layer.hidden ? null : valAccessor(d, i), data: d, layer: layer.name, hidden: layer.hidden }; }); layer.values = layer.values.filter(domainFilter()); return layer.values; } var _stackLayout = d3.layout.stack() .values(prepareValues); var _stack = []; var _titles = {}; var _hidableStacks = false; function domainFilter () { if (!_chart.x()) { return d3.functor(true); } var xDomain = _chart.x().domain(); if (_chart.isOrdinal()) { // TODO #416 //var domainSet = d3.set(xDomain); return function () { return true; //domainSet.has(p.x); }; } if (_chart.elasticX()) { return function () { return true; }; } return function (p) { //return true; return p.x >= xDomain[0] && p.x <= xDomain[xDomain.length - 1]; }; } /** * Stack a new crossfilter group onto this chart with an optional custom value accessor. All stacks * in the same chart will share the same key accessor and therefore the same set of keys. * * For example, in a stacked bar chart, the bars of each stack will be positioned using the same set * of keys on the x axis, while stacked vertically. If name is specified then it will be used to * generate the legend label. * @method stack * @memberof dc.stackMixin * @instance * @see {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#group-map-reduce crossfilter.group} * @example * // stack group using default accessor * chart.stack(valueSumGroup) * // stack group using custom accessor * .stack(avgByDayGroup, function(d){return d.value.avgByDay;}); * @param {crossfilter.group} group * @param {String} [name] * @param {Function} [accessor] * @returns {Array<{group: crossfilter.group, name: String, accessor: Function}>|dc.stackMixin} */ _chart.stack = function (group, name, accessor) { if (!arguments.length) { return _stack; } if (arguments.length <= 2) { accessor = name; } var layer = {group: group}; if (typeof name === 'string') { layer.name = name; } if (typeof accessor === 'function') { layer.accessor = accessor; } _stack.push(layer); return _chart; }; dc.override(_chart, 'group', function (g, n, f) { if (!arguments.length) { return _chart._group(); } _stack = []; _titles = {}; _chart.stack(g, n); if (f) { _chart.valueAccessor(f); } return _chart._group(g, n); }); /** * Allow named stacks to be hidden or shown by clicking on legend items. * This does not affect the behavior of hideStack or showStack. * @method hidableStacks * @memberof dc.stackMixin * @instance * @param {Boolean} [hidableStacks=false] * @returns {Boolean|dc.stackMixin} */ _chart.hidableStacks = function (hidableStacks) { if (!arguments.length) { return _hidableStacks; } _hidableStacks = hidableStacks; return _chart; }; function findLayerByName (n) { var i = _stack.map(dc.pluck('name')).indexOf(n); return _stack[i]; } /** * Hide all stacks on the chart with the given name. * The chart must be re-rendered for this change to appear. * @method hideStack * @memberof dc.stackMixin * @instance * @param {String} stackName * @returns {dc.stackMixin} */ _chart.hideStack = function (stackName) { var layer = findLayerByName(stackName); if (layer) { layer.hidden = true; } return _chart; }; /** * Show all stacks on the chart with the given name. * The chart must be re-rendered for this change to appear. * @method showStack * @memberof dc.stackMixin * @instance * @param {String} stackName * @returns {dc.stackMixin} */ _chart.showStack = function (stackName) { var layer = findLayerByName(stackName); if (layer) { layer.hidden = false; } return _chart; }; _chart.getValueAccessorByIndex = function (index) { return _stack[index].accessor || _chart.valueAccessor(); }; _chart.yAxisMin = function () { var min = d3.min(flattenStack(), function (p) { return (p.y < 0) ? (p.y + p.y0) : p.y0; }); return dc.utils.subtract(min, _chart.yAxisPadding()); }; _chart.yAxisMax = function () { var max = d3.max(flattenStack(), function (p) { return (p.y > 0) ? (p.y + p.y0) : p.y0; }); return dc.utils.add(max, _chart.yAxisPadding()); }; function flattenStack () { var valueses = _chart.data().map(function (layer) { return layer.values; }); return Array.prototype.concat.apply([], valueses); } _chart.xAxisMin = function () { var min = d3.min(flattenStack(), dc.pluck('x')); return dc.utils.subtract(min, _chart.xAxisPadding(), _chart.xAxisPaddingUnit()); }; _chart.xAxisMax = function () { var max = d3.max(flattenStack(), dc.pluck('x')); return dc.utils.add(max, _chart.xAxisPadding(), _chart.xAxisPaddingUnit()); }; /** * Set or get the title function. Chart class will use this function to render svg title (usually interpreted by * browser as tooltips) for each child element in the chart, i.e. a slice in a pie chart or a bubble in a bubble chart. * Almost every chart supports title function however in grid coordinate chart you need to turn off brush in order to * use title otherwise the brush layer will block tooltip trigger. * * If the first argument is a stack name, the title function will get or set the title for that stack. If stackName * is not provided, the first stack is implied. * @method title * @memberof dc.stackMixin * @instance * @example * // set a title function on 'first stack' * chart.title('first stack', function(d) { return d.key + ': ' + d.value; }); * // get a title function from 'second stack' * var secondTitleFunction = chart.title('second stack'); * @param {String} [stackName] * @param {Function} [titleAccessor] * @returns {String|dc.stackMixin} */ dc.override(_chart, 'title', function (stackName, titleAccessor) { if (!stackName) { return _chart._title(); } if (typeof stackName === 'function') { return _chart._title(stackName); } if (stackName === _chart._groupName && typeof titleAccessor === 'function') { return _chart._title(titleAccessor); } if (typeof titleAccessor !== 'function') { return _titles[stackName] || _chart._title(); } _titles[stackName] = titleAccessor; return _chart; }); /** * Gets or sets the stack layout algorithm, which computes a baseline for each stack and * propagates it to the next. * @method stackLayout * @memberof dc.stackMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Stack-Layout.md d3.layout.stack} * @param {Function} [stack=d3.layout.stack] * @returns {Function|dc.stackMixin} */ _chart.stackLayout = function (stack) { if (!arguments.length) { return _stackLayout; } _stackLayout = stack; if (_stackLayout.values() === d3.layout.stack().values()) { _stackLayout.values(prepareValues); } return _chart; }; function visability (l) { return !l.hidden; } _chart.data(function () { var layers = _stack.filter(visability); return layers.length ? _chart.stackLayout()(layers) : []; }); _chart._ordinalXDomain = function () { var flat = flattenStack().map(dc.pluck('data')); var ordered = _chart._computeOrderedGroups(flat); return ordered.map(_chart.keyAccessor()); }; _chart.colorAccessor(function (d) { var layer = this.layer || this.name || d.name || d.layer; return layer; }); _chart.legendables = function () { return _stack.map(function (layer, i) { return { chart: _chart, name: layer.name, hidden: layer.hidden || false, color: _chart.getColor.call(layer, layer.values, i) }; }); }; _chart.isLegendableHidden = function (d) { var layer = findLayerByName(d.name); return layer ? layer.hidden : false; }; _chart.legendToggle = function (d) { if (_hidableStacks) { if (_chart.isLegendableHidden(d)) { _chart.showStack(d.name); } else { _chart.hideStack(d.name); } //_chart.redraw(); _chart.renderGroup(); } }; return _chart; }; /** * Cap is a mixin that groups small data elements below a _cap_ into an *others* grouping for both the * Row and Pie Charts. * * The top ordered elements in the group up to the cap amount will be kept in the chart, and the rest * will be replaced with an *others* element, with value equal to the sum of the replaced values. The * keys of the elements below the cap limit are recorded in order to filter by those keys when the * others* element is clicked. * @name capMixin * @memberof dc * @mixin * @param {Object} _chart * @returns {dc.capMixin} */ dc.capMixin = function (_chart) { var _cap = Infinity; var _othersLabel = 'Others'; var _othersGrouper = function (topRows) { var topRowsSum = d3.sum(topRows, _chart.valueAccessor()), allRows = _chart.group().all(), allRowsSum = d3.sum(allRows, _chart.valueAccessor()), topKeys = topRows.map(_chart.keyAccessor()), allKeys = allRows.map(_chart.keyAccessor()), topSet = d3.set(topKeys), others = allKeys.filter(function (d) {return !topSet.has(d);}); if (allRowsSum > topRowsSum) { return topRows.concat([{ 'others': others, 'key': _chart.othersLabel(), 'value': allRowsSum - topRowsSum }]); } return topRows; }; _chart.cappedKeyAccessor = function (d, i) { if (d.others) { return d.key; } return _chart.keyAccessor()(d, i); }; _chart.cappedValueAccessor = function (d, i) { if (d.others) { return d.value; } return _chart.valueAccessor()(d, i); }; _chart.data(function (group) { if (_cap === Infinity) { return _chart._computeOrderedGroups(group.all()); } else { var topRows = group.top(_cap); // ordered by crossfilter group order (default value) topRows = _chart._computeOrderedGroups(topRows); // re-order using ordering (default key) if (_othersGrouper) { return _othersGrouper(topRows); } return topRows; } }); /** * Get or set the count of elements to that will be included in the cap. If there is an * {@link dc.capMixin#othersGrouper othersGrouper}, any further elements will be combined in an * extra element with its name determined by {@link dc.capMixin#othersLabel othersLabel}. * * Up through dc.js 2.0.*, capping uses * {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#group_top group.top(N)}, * which selects the largest items according to * {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#group_order group.order()}. * The chart then sorts the items according to {@link dc.baseMixin#ordering baseMixin.ordering()}. * So the two values essentially have to agree, but if the former is incorrect (it's easy to * forget about `group.order()`), the latter will mask the problem. This also makes * {@link https://github.com/dc-js/dc.js/wiki/FAQ#fake-groups fake groups} difficult to * implement. * * In dc.js 2.1 and forward, only * {@link https://github.com/crossfilter/crossfilter/wiki/API-Reference#group_all group.all()} * and `baseMixin.ordering()` are used. * @method cap * @memberof dc.capMixin * @instance * @param {Number} [count=Infinity] * @returns {Number|dc.capMixin} */ _chart.cap = function (count) { if (!arguments.length) { return _cap; } _cap = count; return _chart; }; /** * Get or set the label for *Others* slice when slices cap is specified. * @method othersLabel * @memberof dc.capMixin * @instance * @param {String} [label="Others"] * @returns {String|dc.capMixin} */ _chart.othersLabel = function (label) { if (!arguments.length) { return _othersLabel; } _othersLabel = label; return _chart; }; /** * Get or set the grouper function that will perform the insertion of data for the *Others* slice * if the slices cap is specified. If set to a falsy value, no others will be added. By default the * grouper function computes the sum of all values below the cap. * @method othersGrouper * @memberof dc.capMixin * @instance * @example * // Do not show others * chart.othersGrouper(null); * // Default others grouper * chart.othersGrouper(function (topRows) { * var topRowsSum = d3.sum(topRows, _chart.valueAccessor()), * allRows = _chart.group().all(), * allRowsSum = d3.sum(allRows, _chart.valueAccessor()), * topKeys = topRows.map(_chart.keyAccessor()), * allKeys = allRows.map(_chart.keyAccessor()), * topSet = d3.set(topKeys), * others = allKeys.filter(function (d) {return !topSet.has(d);}); * if (allRowsSum > topRowsSum) { * return topRows.concat([{ * 'others': others, * 'key': _chart.othersLabel(), * 'value': allRowsSum - topRowsSum * }]); * } * return topRows; * }); * // Custom others grouper * chart.othersGrouper(function (data) { * // compute the value for others, presumably the sum of all values below the cap * var othersSum = yourComputeOthersValueLogic(data) * * // the keys are needed to properly filter when the others element is clicked * var othersKeys = yourComputeOthersKeysArrayLogic(data); * * // add the others row to the dataset * data.push({'key': 'Others', 'value': othersSum, 'others': othersKeys }); * * return data; * }); * @param {Function} [grouperFunction] * @returns {Function|dc.capMixin} */ _chart.othersGrouper = function (grouperFunction) { if (!arguments.length) { return _othersGrouper; } _othersGrouper = grouperFunction; return _chart; }; dc.override(_chart, 'onClick', function (d) { if (d.others) { _chart.filter([d.others]); } _chart._onClick(d); }); return _chart; }; /** * This Mixin provides reusable functionalities for any chart that needs to visualize data using bubbles. * @name bubbleMixin * @memberof dc * @mixin * @mixes dc.colorMixin * @param {Object} _chart * @returns {dc.bubbleMixin} */ dc.bubbleMixin = function (_chart) { var _maxBubbleRelativeSize = 0.3; var _minRadiusWithLabel = 10; _chart.BUBBLE_NODE_CLASS = 'node'; _chart.BUBBLE_CLASS = 'bubble'; _chart.MIN_RADIUS = 10; _chart = dc.colorMixin(_chart); _chart.renderLabel(true); _chart.data(function (group) { return group.top(Infinity); }); var _r = d3.scale.linear().domain([0, 100]); var _rValueAccessor = function (d) { return d.r; }; /** * Get or set the bubble radius scale. By default the bubble chart uses * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Quantitative-Scales.md#linear d3.scale.linear().domain([0, 100])} * as its radius scale. * @method r * @memberof dc.bubbleMixin * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Scales.md d3.scale} * @param {d3.scale} [bubbleRadiusScale=d3.scale.linear().domain([0, 100])] * @returns {d3.scale|dc.bubbleMixin} */ _chart.r = function (bubbleRadiusScale) { if (!arguments.length) { return _r; } _r = bubbleRadiusScale; return _chart; }; /** * Get or set the radius value accessor function. If set, the radius value accessor function will * be used to retrieve a data value for each bubble. The data retrieved then will be mapped using * the r scale to the actual bubble radius. This allows you to encode a data dimension using bubble * size. * @method radiusValueAccessor * @memberof dc.bubbleMixin * @instance * @param {Function} [radiusValueAccessor] * @returns {Function|dc.bubbleMixin} */ _chart.radiusValueAccessor = function (radiusValueAccessor) { if (!arguments.length) { return _rValueAccessor; } _rValueAccessor = radiusValueAccessor; return _chart; }; _chart.rMin = function () { var min = d3.min(_chart.data(), function (e) { return _chart.radiusValueAccessor()(e); }); return min; }; _chart.rMax = function () { var max = d3.max(_chart.data(), function (e) { return _chart.radiusValueAccessor()(e); }); return max; }; _chart.bubbleR = function (d) { var value = _chart.radiusValueAccessor()(d); var r = _chart.r()(value); if (isNaN(r) || value <= 0) { r = 0; } return r; }; var labelFunction = function (d) { return _chart.label()(d); }; var shouldLabel = function (d) { return (_chart.bubbleR(d) > _minRadiusWithLabel); }; var labelOpacity = function (d) { return shouldLabel(d) ? 1 : 0; }; var labelPointerEvent = function (d) { return shouldLabel(d) ? 'all' : 'none'; }; _chart._doRenderLabel = function (bubbleGEnter) { if (_chart.renderLabel()) { var label = bubbleGEnter.select('text'); if (label.empty()) { label = bubbleGEnter.append('text') .attr('text-anchor', 'middle') .attr('dy', '.3em') .on('click', _chart.onClick); } label .attr('opacity', 0) .attr('pointer-events', labelPointerEvent) .text(labelFunction); dc.transition(label, _chart.transitionDuration(), _chart.transitionDelay()) .attr('opacity', labelOpacity); } }; _chart.doUpdateLabels = function (bubbleGEnter) { if (_chart.renderLabel()) { var labels = bubbleGEnter.select('text') .attr('pointer-events', labelPointerEvent) .text(labelFunction); dc.transition(labels, _chart.transitionDuration(), _chart.transitionDelay()) .attr('opacity', labelOpacity); } }; var titleFunction = function (d) { return _chart.title()(d); }; _chart._doRenderTitles = function (g) { if (_chart.renderTitle()) { var title = g.select('title'); if (title.empty()) { g.append('title').text(titleFunction); } } }; _chart.doUpdateTitles = function (g) { if (_chart.renderTitle()) { g.select('title').text(titleFunction); } }; /** * Get or set the minimum radius. This will be used to initialize the radius scale's range. * @method minRadius * @memberof dc.bubbleMixin * @instance * @param {Number} [radius=10] * @returns {Number|dc.bubbleMixin} */ _chart.minRadius = function (radius) { if (!arguments.length) { return _chart.MIN_RADIUS; } _chart.MIN_RADIUS = radius; return _chart; }; /** * Get or set the minimum radius for label rendering. If a bubble's radius is less than this value * then no label will be rendered. * @method minRadiusWithLabel * @memberof dc.bubbleMixin * @instance * @param {Number} [radius=10] * @returns {Number|dc.bubbleMixin} */ _chart.minRadiusWithLabel = function (radius) { if (!arguments.length) { return _minRadiusWithLabel; } _minRadiusWithLabel = radius; return _chart; }; /** * Get or set the maximum relative size of a bubble to the length of x axis. This value is useful * when the difference in radius between bubbles is too great. * @method maxBubbleRelativeSize * @memberof dc.bubbleMixin * @instance * @param {Number} [relativeSize=0.3] * @returns {Number|dc.bubbleMixin} */ _chart.maxBubbleRelativeSize = function (relativeSize) { if (!arguments.length) { return _maxBubbleRelativeSize; } _maxBubbleRelativeSize = relativeSize; return _chart; }; _chart.fadeDeselectedArea = function () { if (_chart.hasFilter()) { _chart.selectAll('g.' + _chart.BUBBLE_NODE_CLASS).each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll('g.' + _chart.BUBBLE_NODE_CLASS).each(function () { _chart.resetHighlight(this); }); } }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(d.key); }; _chart.onClick = function (d) { var filter = d.key; dc.events.trigger(function () { _chart.filter(filter); _chart.redrawGroup(); }); }; return _chart; }; /** * The pie chart implementation is usually used to visualize a small categorical distribution. The pie * chart uses keyAccessor to determine the slices, and valueAccessor to calculate the size of each * slice relative to the sum of all values. Slices are ordered by {@link dc.baseMixin#ordering ordering} * which defaults to sorting by key. * * Examples: * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index} * @class pieChart * @memberof dc * @mixes dc.capMixin * @mixes dc.colorMixin * @mixes dc.baseMixin * @example * // create a pie chart under #chart-container1 element using the default global chart group * var chart1 = dc.pieChart('#chart-container1'); * // create a pie chart under #chart-container2 element using chart group A * var chart2 = dc.pieChart('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.pieChart} */ dc.pieChart = function (parent, chartGroup) { var DEFAULT_MIN_ANGLE_FOR_LABEL = 0.5; var _sliceCssClass = 'pie-slice'; var _labelCssClass = 'pie-label'; var _sliceGroupCssClass = 'pie-slice-group'; var _labelGroupCssClass = 'pie-label-group'; var _emptyCssClass = 'empty-chart'; var _emptyTitle = 'empty'; var _radius, _givenRadius, // specified radius, if any _innerRadius = 0, _externalRadiusPadding = 0; var _g; var _cx; var _cy; var _minAngleForLabel = DEFAULT_MIN_ANGLE_FOR_LABEL; var _externalLabelRadius; var _drawPaths = false; var _chart = dc.capMixin(dc.colorMixin(dc.baseMixin({}))); _chart.colorAccessor(_chart.cappedKeyAccessor); _chart.title(function (d) { return _chart.cappedKeyAccessor(d) + ': ' + _chart.cappedValueAccessor(d); }); /** * Get or set the maximum number of slices the pie chart will generate. The top slices are determined by * value from high to low. Other slices exeeding the cap will be rolled up into one single *Others* slice. * @method slicesCap * @memberof dc.pieChart * @instance * @param {Number} [cap] * @returns {Number|dc.pieChart} */ _chart.slicesCap = _chart.cap; _chart.label(_chart.cappedKeyAccessor); _chart.renderLabel(true); _chart.transitionDuration(350); _chart.transitionDelay(0); _chart._doRender = function () { _chart.resetSvg(); _g = _chart.svg() .append('g') .attr('transform', 'translate(' + _chart.cx() + ',' + _chart.cy() + ')'); _g.append('g').attr('class', _sliceGroupCssClass); _g.append('g').attr('class', _labelGroupCssClass); drawChart(); return _chart; }; function drawChart () { // set radius on basis of chart dimension if missing _radius = _givenRadius ? _givenRadius : d3.min([_chart.width(), _chart.height()]) / 2; var arc = buildArcs(); var pie = pieLayout(); var pieData; // if we have data... if (d3.sum(_chart.data(), _chart.valueAccessor())) { pieData = pie(_chart.data()); _g.classed(_emptyCssClass, false); } else { // otherwise we'd be getting NaNs, so override // note: abuse others for its ignoring the value accessor pieData = pie([{key: _emptyTitle, value: 1, others: [_emptyTitle]}]); _g.classed(_emptyCssClass, true); } if (_g) { var slices = _g.select('g.' + _sliceGroupCssClass) .selectAll('g.' + _sliceCssClass) .data(pieData); var labels = _g.select('g.' + _labelGroupCssClass) .selectAll('text.' + _labelCssClass) .data(pieData); createElements(slices, labels, arc, pieData); updateElements(pieData, arc); removeElements(slices, labels); highlightFilter(); dc.transition(_g, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', 'translate(' + _chart.cx() + ',' + _chart.cy() + ')'); } } function createElements (slices, labels, arc, pieData) { var slicesEnter = createSliceNodes(slices); createSlicePath(slicesEnter, arc); createTitles(slicesEnter); createLabels(labels, pieData, arc); } function createSliceNodes (slices) { var slicesEnter = slices .enter() .append('g') .attr('class', function (d, i) { return _sliceCssClass + ' _' + i; }); return slicesEnter; } function createSlicePath (slicesEnter, arc) { var slicePath = slicesEnter.append('path') .attr('fill', fill) .on('click', onClick) .attr('d', function (d, i) { return safeArc(d, i, arc); }); var transition = dc.transition(slicePath, _chart.transitionDuration(), _chart.transitionDelay()); if (transition.attrTween) { transition.attrTween('d', tweenPie); } } function createTitles (slicesEnter) { if (_chart.renderTitle()) { slicesEnter.append('title').text(function (d) { return _chart.title()(d.data); }); } } _chart._applyLabelText = function (labels) { labels .text(function (d) { var data = d.data; if ((sliceHasNoData(data) || sliceTooSmall(d)) && !isSelectedSlice(d)) { return ''; } return _chart.label()(d.data); }); }; function positionLabels (labels, arc) { _chart._applyLabelText(labels); dc.transition(labels, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', function (d) { return labelPosition(d, arc); }) .attr('text-anchor', 'middle'); } function highlightSlice (i, whether) { _chart.select('g.pie-slice._' + i) .classed('highlight', whether); } function createLabels (labels, pieData, arc) { if (_chart.renderLabel()) { var labelsEnter = labels .enter() .append('text') .attr('class', function (d, i) { var classes = _sliceCssClass + ' ' + _labelCssClass + ' _' + i; if (_externalLabelRadius) { classes += ' external'; } return classes; }) .on('click', onClick) .on('mouseover', function (d, i) { highlightSlice(i, true); }) .on('mouseout', function (d, i) { highlightSlice(i, false); }); positionLabels(labelsEnter, arc); if (_externalLabelRadius && _drawPaths) { updateLabelPaths(pieData, arc); } } } function updateLabelPaths (pieData, arc) { var polyline = _g.selectAll('polyline.' + _sliceCssClass) .data(pieData); polyline .enter() .append('polyline') .attr('class', function (d, i) { return 'pie-path _' + i + ' ' + _sliceCssClass; }) .on('click', onClick) .on('mouseover', function (d, i) { highlightSlice(i, true); }) .on('mouseout', function (d, i) { highlightSlice(i, false); }); polyline.exit().remove(); var arc2 = d3.svg.arc() .outerRadius(_radius - _externalRadiusPadding + _externalLabelRadius) .innerRadius(_radius - _externalRadiusPadding); var transition = dc.transition(polyline, _chart.transitionDuration(), _chart.transitionDelay()); // this is one rare case where d3.selection differs from d3.transition if (transition.attrTween) { transition .attrTween('points', function (d) { var current = this._current || d; current = {startAngle: current.startAngle, endAngle: current.endAngle}; var interpolate = d3.interpolate(current, d); this._current = interpolate(0); return function (t) { var d2 = interpolate(t); return [arc.centroid(d2), arc2.centroid(d2)]; }; }); } else { transition.attr('points', function (d) { return [arc.centroid(d), arc2.centroid(d)]; }); } transition.style('visibility', function (d) { return d.endAngle - d.startAngle < 0.0001 ? 'hidden' : 'visible'; }); } function updateElements (pieData, arc) { updateSlicePaths(pieData, arc); updateLabels(pieData, arc); updateTitles(pieData); } function updateSlicePaths (pieData, arc) { var slicePaths = _g.selectAll('g.' + _sliceCssClass) .data(pieData) .select('path') .attr('d', function (d, i) { return safeArc(d, i, arc); }); var transition = dc.transition(slicePaths, _chart.transitionDuration(), _chart.transitionDelay()); if (transition.attrTween) { transition.attrTween('d', tweenPie); } transition.attr('fill', fill); } function updateLabels (pieData, arc) { if (_chart.renderLabel()) { var labels = _g.selectAll('text.' + _labelCssClass) .data(pieData); positionLabels(labels, arc); if (_externalLabelRadius && _drawPaths) { updateLabelPaths(pieData, arc); } } } function updateTitles (pieData) { if (_chart.renderTitle()) { _g.selectAll('g.' + _sliceCssClass) .data(pieData) .select('title') .text(function (d) { return _chart.title()(d.data); }); } } function removeElements (slices, labels) { slices.exit().remove(); labels.exit().remove(); } function highlightFilter () { if (_chart.hasFilter()) { _chart.selectAll('g.' + _sliceCssClass).each(function (d) { if (isSelectedSlice(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll('g.' + _sliceCssClass).each(function () { _chart.resetHighlight(this); }); } } /** * Get or set the external radius padding of the pie chart. This will force the radius of the * pie chart to become smaller or larger depending on the value. * @method externalRadiusPadding * @memberof dc.pieChart * @instance * @param {Number} [externalRadiusPadding=0] * @returns {Number|dc.pieChart} */ _chart.externalRadiusPadding = function (externalRadiusPadding) { if (!arguments.length) { return _externalRadiusPadding; } _externalRadiusPadding = externalRadiusPadding; return _chart; }; /** * Get or set the inner radius of the pie chart. If the inner radius is greater than 0px then the * pie chart will be rendered as a doughnut chart. * @method innerRadius * @memberof dc.pieChart * @instance * @param {Number} [innerRadius=0] * @returns {Number|dc.pieChart} */ _chart.innerRadius = function (innerRadius) { if (!arguments.length) { return _innerRadius; } _innerRadius = innerRadius; return _chart; }; /** * Get or set the outer radius. If the radius is not set, it will be half of the minimum of the * chart width and height. * @method radius * @memberof dc.pieChart * @instance * @param {Number} [radius] * @returns {Number|dc.pieChart} */ _chart.radius = function (radius) { if (!arguments.length) { return _givenRadius; } _givenRadius = radius; return _chart; }; /** * Get or set center x coordinate position. Default is center of svg. * @method cx * @memberof dc.pieChart * @instance * @param {Number} [cx] * @returns {Number|dc.pieChart} */ _chart.cx = function (cx) { if (!arguments.length) { return (_cx || _chart.width() / 2); } _cx = cx; return _chart; }; /** * Get or set center y coordinate position. Default is center of svg. * @method cy * @memberof dc.pieChart * @instance * @param {Number} [cy] * @returns {Number|dc.pieChart} */ _chart.cy = function (cy) { if (!arguments.length) { return (_cy || _chart.height() / 2); } _cy = cy; return _chart; }; function buildArcs () { return d3.svg.arc() .outerRadius(_radius - _externalRadiusPadding) .innerRadius(_innerRadius); } function isSelectedSlice (d) { return _chart.hasFilter(_chart.cappedKeyAccessor(d.data)); } _chart._doRedraw = function () { drawChart(); return _chart; }; /** * Get or set the minimal slice angle for label rendering. Any slice with a smaller angle will not * display a slice label. * @method minAngleForLabel * @memberof dc.pieChart * @instance * @param {Number} [minAngleForLabel=0.5] * @returns {Number|dc.pieChart} */ _chart.minAngleForLabel = function (minAngleForLabel) { if (!arguments.length) { return _minAngleForLabel; } _minAngleForLabel = minAngleForLabel; return _chart; }; function pieLayout () { return d3.layout.pie().sort(null).value(_chart.cappedValueAccessor); } function sliceTooSmall (d) { var angle = (d.endAngle - d.startAngle); return isNaN(angle) || angle < _minAngleForLabel; } function sliceHasNoData (d) { return _chart.cappedValueAccessor(d) === 0; } function tweenPie (b) { b.innerRadius = _innerRadius; var current = this._current; if (isOffCanvas(current)) { current = {startAngle: 0, endAngle: 0}; } else { // only interpolate startAngle & endAngle, not the whole data object current = {startAngle: current.startAngle, endAngle: current.endAngle}; } var i = d3.interpolate(current, b); this._current = i(0); return function (t) { return safeArc(i(t), 0, buildArcs()); }; } function isOffCanvas (current) { return !current || isNaN(current.startAngle) || isNaN(current.endAngle); } function fill (d, i) { return _chart.getColor(d.data, i); } function onClick (d, i) { if (_g.attr('class') !== _emptyCssClass) { _chart.onClick(d.data, i); } } function safeArc (d, i, arc) { var path = arc(d, i); if (path.indexOf('NaN') >= 0) { path = 'M0,0'; } return path; } /** * Title to use for the only slice when there is no data. * @method emptyTitle * @memberof dc.pieChart * @instance * @param {String} [title] * @returns {String|dc.pieChart} */ _chart.emptyTitle = function (title) { if (arguments.length === 0) { return _emptyTitle; } _emptyTitle = title; return _chart; }; /** * Position slice labels offset from the outer edge of the chart. * * The argument specifies the extra radius to be added for slice labels. * @method externalLabels * @memberof dc.pieChart * @instance * @param {Number} [externalLabelRadius] * @returns {Number|dc.pieChart} */ _chart.externalLabels = function (externalLabelRadius) { if (arguments.length === 0) { return _externalLabelRadius; } else if (externalLabelRadius) { _externalLabelRadius = externalLabelRadius; } else { _externalLabelRadius = undefined; } return _chart; }; /** * Get or set whether to draw lines from pie slices to their labels. * * @method drawPaths * @memberof dc.pieChart * @instance * @param {Boolean} [drawPaths] * @returns {Boolean|dc.pieChart} */ _chart.drawPaths = function (drawPaths) { if (arguments.length === 0) { return _drawPaths; } _drawPaths = drawPaths; return _chart; }; function labelPosition (d, arc) { var centroid; if (_externalLabelRadius) { centroid = d3.svg.arc() .outerRadius(_radius - _externalRadiusPadding + _externalLabelRadius) .innerRadius(_radius - _externalRadiusPadding + _externalLabelRadius) .centroid(d); } else { centroid = arc.centroid(d); } if (isNaN(centroid[0]) || isNaN(centroid[1])) { return 'translate(0,0)'; } else { return 'translate(' + centroid + ')'; } } _chart.legendables = function () { return _chart.data().map(function (d, i) { var legendable = {name: d.key, data: d.value, others: d.others, chart: _chart}; legendable.color = _chart.getColor(d, i); return legendable; }); }; _chart.legendHighlight = function (d) { highlightSliceFromLegendable(d, true); }; _chart.legendReset = function (d) { highlightSliceFromLegendable(d, false); }; _chart.legendToggle = function (d) { _chart.onClick({key: d.name, others: d.others}); }; function highlightSliceFromLegendable (legendable, highlighted) { _chart.selectAll('g.pie-slice').each(function (d) { if (legendable.name === d.data.key) { d3.select(this).classed('highlight', highlighted); } }); } return _chart.anchor(parent, chartGroup); }; /** * Concrete bar chart/histogram implementation. * * Examples: * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index} * - {@link http://dc-js.github.com/dc.js/crime/index.html Canadian City Crime Stats} * @class barChart * @memberof dc * @mixes dc.stackMixin * @mixes dc.coordinateGridMixin * @example * // create a bar chart under #chart-container1 element using the default global chart group * var chart1 = dc.barChart('#chart-container1'); * // create a bar chart under #chart-container2 element using chart group A * var chart2 = dc.barChart('#chart-container2', 'chartGroupA'); * // create a sub-chart under a composite parent chart * var chart3 = dc.barChart(compositeChart); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} * specifying a dom block element such as a div; or a dom element or d3 selection. If the bar * chart is a sub-chart in a {@link dc.compositeChart Composite Chart} then pass in the parent * composite chart instance instead. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.barChart} */ dc.barChart = function (parent, chartGroup) { var MIN_BAR_WIDTH = 1; var DEFAULT_GAP_BETWEEN_BARS = 2; var LABEL_PADDING = 3; var _chart = dc.stackMixin(dc.coordinateGridMixin({})); var _gap = DEFAULT_GAP_BETWEEN_BARS; var _centerBar = false; var _alwaysUseRounding = false; var _barWidth; dc.override(_chart, 'rescale', function () { _chart._rescale(); _barWidth = undefined; return _chart; }); dc.override(_chart, 'render', function () { if (_chart.round() && _centerBar && !_alwaysUseRounding) { dc.logger.warn('By default, brush rounding is disabled if bars are centered. ' + 'See dc.js bar chart API documentation for details.'); } return _chart._render(); }); _chart.label(function (d) { return dc.utils.printSingleValue(d.y0 + d.y); }, false); _chart.plotData = function () { var layers = _chart.chartBodyG().selectAll('g.stack') .data(_chart.data()); calculateBarWidth(); layers .enter() .append('g') .attr('class', function (d, i) { return 'stack ' + '_' + i; }); var last = layers.size() - 1; layers.each(function (d, i) { var layer = d3.select(this); renderBars(layer, i, d); if (_chart.renderLabel() && last === i) { renderLabels(layer, i, d); } }); }; function barHeight (d) { return dc.utils.safeNumber(Math.abs(_chart.y()(d.y + d.y0) - _chart.y()(d.y0))); } function renderLabels (layer, layerIndex, d) { var labels = layer.selectAll('text.barLabel') .data(d.values, dc.pluck('x')); labels.enter() .append('text') .attr('class', 'barLabel') .attr('text-anchor', 'middle'); if (_chart.isOrdinal()) { labels.on('click', _chart.onClick); labels.attr('cursor', 'pointer'); } dc.transition(labels, _chart.transitionDuration(), _chart.transitionDelay()) .attr('x', function (d) { var x = _chart.x()(d.x); if (!_centerBar) { x += _barWidth / 2; } return dc.utils.safeNumber(x); }) .attr('y', function (d) { var y = _chart.y()(d.y + d.y0); if (d.y < 0) { y -= barHeight(d); } return dc.utils.safeNumber(y - LABEL_PADDING); }) .text(function (d) { return _chart.label()(d); }); dc.transition(labels.exit(), _chart.transitionDuration(), _chart.transitionDelay()) .attr('height', 0) .remove(); } function renderBars (layer, layerIndex, d) { var bars = layer.selectAll('rect.bar') .data(d.values, dc.pluck('x')); var enter = bars.enter() .append('rect') .attr('class', 'bar') .attr('fill', dc.pluck('data', _chart.getColor)) .attr('y', _chart.yAxisHeight()) .attr('height', 0); if (_chart.renderTitle()) { enter.append('title').text(dc.pluck('data', _chart.title(d.name))); } if (_chart.isOrdinal()) { bars.on('click', _chart.onClick); } dc.transition(bars, _chart.transitionDuration(), _chart.transitionDelay()) .attr('x', function (d) { var x = _chart.x()(d.x); if (_centerBar) { x -= _barWidth / 2; } if (_chart.isOrdinal() && _gap !== undefined) { x += _gap / 2; } return dc.utils.safeNumber(x); }) .attr('y', function (d) { var y = _chart.y()(d.y + d.y0); if (d.y < 0) { y -= barHeight(d); } return dc.utils.safeNumber(y); }) .attr('width', _barWidth) .attr('height', function (d) { return barHeight(d); }) .attr('fill', dc.pluck('data', _chart.getColor)) .select('title').text(dc.pluck('data', _chart.title(d.name))); dc.transition(bars.exit(), _chart.transitionDuration(), _chart.transitionDelay()) .attr('x', function (d) { return _chart.x()(d.x); }) .attr('width', _barWidth * 0.9) .remove(); } function calculateBarWidth () { if (_barWidth === undefined) { var numberOfBars = _chart.xUnitCount(); // please can't we always use rangeBands for bar charts? if (_chart.isOrdinal() && _gap === undefined) { _barWidth = Math.floor(_chart.x().rangeBand()); } else if (_gap) { _barWidth = Math.floor((_chart.xAxisLength() - (numberOfBars - 1) * _gap) / numberOfBars); } else { _barWidth = Math.floor(_chart.xAxisLength() / (1 + _chart.barPadding()) / numberOfBars); } if (_barWidth === Infinity || isNaN(_barWidth) || _barWidth < MIN_BAR_WIDTH) { _barWidth = MIN_BAR_WIDTH; } } } _chart.fadeDeselectedArea = function () { var bars = _chart.chartBodyG().selectAll('rect.bar'); var extent = _chart.brush().extent(); if (_chart.isOrdinal()) { if (_chart.hasFilter()) { bars.classed(dc.constants.SELECTED_CLASS, function (d) { return _chart.hasFilter(d.x); }); bars.classed(dc.constants.DESELECTED_CLASS, function (d) { return !_chart.hasFilter(d.x); }); } else { bars.classed(dc.constants.SELECTED_CLASS, false); bars.classed(dc.constants.DESELECTED_CLASS, false); } } else { if (!_chart.brushIsEmpty(extent)) { var start = extent[0]; var end = extent[1]; bars.classed(dc.constants.DESELECTED_CLASS, function (d) { return d.x < start || d.x >= end; }); } else { bars.classed(dc.constants.DESELECTED_CLASS, false); } } }; /** * Whether the bar chart will render each bar centered around the data position on the x-axis. * @method centerBar * @memberof dc.barChart * @instance * @param {Boolean} [centerBar=false] * @returns {Boolean|dc.barChart} */ _chart.centerBar = function (centerBar) { if (!arguments.length) { return _centerBar; } _centerBar = centerBar; return _chart; }; dc.override(_chart, 'onClick', function (d) { _chart._onClick(d.data); }); /** * Get or set the spacing between bars as a fraction of bar size. Valid values are between 0-1. * Setting this value will also remove any previously set {@link dc.barChart#gap gap}. See the * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md#ordinal_rangeBands d3 docs} * for a visual description of how the padding is applied. * @method barPadding * @memberof dc.barChart * @instance * @param {Number} [barPadding=0] * @returns {Number|dc.barChart} */ _chart.barPadding = function (barPadding) { if (!arguments.length) { return _chart._rangeBandPadding(); } _chart._rangeBandPadding(barPadding); _gap = undefined; return _chart; }; _chart._useOuterPadding = function () { return _gap === undefined; }; /** * Get or set the outer padding on an ordinal bar chart. This setting has no effect on non-ordinal charts. * Will pad the width by `padding * barWidth` on each side of the chart. * @method outerPadding * @memberof dc.barChart * @instance * @param {Number} [padding=0.5] * @returns {Number|dc.barChart} */ _chart.outerPadding = _chart._outerRangeBandPadding; /** * Manually set fixed gap (in px) between bars instead of relying on the default auto-generated * gap. By default the bar chart implementation will calculate and set the gap automatically * based on the number of data points and the length of the x axis. * @method gap * @memberof dc.barChart * @instance * @param {Number} [gap=2] * @returns {Number|dc.barChart} */ _chart.gap = function (gap) { if (!arguments.length) { return _gap; } _gap = gap; return _chart; }; _chart.extendBrush = function () { var extent = _chart.brush().extent(); if (_chart.round() && (!_centerBar || _alwaysUseRounding)) { extent[0] = extent.map(_chart.round())[0]; extent[1] = extent.map(_chart.round())[1]; _chart.chartBodyG().select('.brush') .call(_chart.brush().extent(extent)); } return extent; }; /** * Set or get whether rounding is enabled when bars are centered. If false, using * rounding with centered bars will result in a warning and rounding will be ignored. This flag * has no effect if bars are not {@link dc.barChart#centerBar centered}. * When using standard d3.js rounding methods, the brush often doesn't align correctly with * centered bars since the bars are offset. The rounding function must add an offset to * compensate, such as in the following example. * @method alwaysUseRounding * @memberof dc.barChart * @instance * @example * chart.round(function(n) { return Math.floor(n) + 0.5; }); * @param {Boolean} [alwaysUseRounding=false] * @returns {Boolean|dc.barChart} */ _chart.alwaysUseRounding = function (alwaysUseRounding) { if (!arguments.length) { return _alwaysUseRounding; } _alwaysUseRounding = alwaysUseRounding; return _chart; }; function colorFilter (color, inv) { return function () { var item = d3.select(this); var match = item.attr('fill') === color; return inv ? !match : match; }; } _chart.legendHighlight = function (d) { if (!_chart.isLegendableHidden(d)) { _chart.g().selectAll('rect.bar') .classed('highlight', colorFilter(d.color)) .classed('fadeout', colorFilter(d.color, true)); } }; _chart.legendReset = function () { _chart.g().selectAll('rect.bar') .classed('highlight', false) .classed('fadeout', false); }; dc.override(_chart, 'xAxisMax', function () { var max = this._xAxisMax(); if ('resolution' in _chart.xUnits()) { var res = _chart.xUnits().resolution; max += res; } return max; }); return _chart.anchor(parent, chartGroup); }; /** * Concrete line/area chart implementation. * * Examples: * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index} * - {@link http://dc-js.github.com/dc.js/crime/index.html Canadian City Crime Stats} * @class lineChart * @memberof dc * @mixes dc.stackMixin * @mixes dc.coordinateGridMixin * @example * // create a line chart under #chart-container1 element using the default global chart group * var chart1 = dc.lineChart('#chart-container1'); * // create a line chart under #chart-container2 element using chart group A * var chart2 = dc.lineChart('#chart-container2', 'chartGroupA'); * // create a sub-chart under a composite parent chart * var chart3 = dc.lineChart(compositeChart); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} * specifying a dom block element such as a div; or a dom element or d3 selection. If the line * chart is a sub-chart in a {@link dc.compositeChart Composite Chart} then pass in the parent * composite chart instance instead. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.lineChart} */ dc.lineChart = function (parent, chartGroup) { var DEFAULT_DOT_RADIUS = 5; var TOOLTIP_G_CLASS = 'dc-tooltip'; var DOT_CIRCLE_CLASS = 'dot'; var Y_AXIS_REF_LINE_CLASS = 'yRef'; var X_AXIS_REF_LINE_CLASS = 'xRef'; var DEFAULT_DOT_OPACITY = 1e-6; var LABEL_PADDING = 3; var _chart = dc.stackMixin(dc.coordinateGridMixin({})); var _renderArea = false; var _dotRadius = DEFAULT_DOT_RADIUS; var _dataPointRadius = null; var _dataPointFillOpacity = DEFAULT_DOT_OPACITY; var _dataPointStrokeOpacity = DEFAULT_DOT_OPACITY; var _interpolate = 'linear'; var _tension = 0.7; var _defined; var _dashStyle; var _xyTipsOn = true; _chart.transitionDuration(500); _chart.transitionDelay(0); _chart._rangeBandPadding(1); _chart.plotData = function () { var chartBody = _chart.chartBodyG(); var layersList = chartBody.select('g.stack-list'); if (layersList.empty()) { layersList = chartBody.append('g').attr('class', 'stack-list'); } var layers = layersList.selectAll('g.stack').data(_chart.data()); var layersEnter = layers .enter() .append('g') .attr('class', function (d, i) { return 'stack ' + '_' + i; }); drawLine(layersEnter, layers); drawArea(layersEnter, layers); drawDots(chartBody, layers); if (_chart.renderLabel()) { drawLabels(layers); } }; /** * Gets or sets the interpolator to use for lines drawn, by string name, allowing e.g. step * functions, splines, and cubic interpolation. This is passed to * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#line_interpolate d3.svg.line.interpolate} and * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#area_interpolate d3.svg.area.interpolate}, * where you can find a complete list of valid arguments. * @method interpolate * @memberof dc.lineChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#line_interpolate d3.svg.line.interpolate} * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#area_interpolate d3.svg.area.interpolate} * @param {String} [interpolate='linear'] * @returns {String|dc.lineChart} */ _chart.interpolate = function (interpolate) { if (!arguments.length) { return _interpolate; } _interpolate = interpolate; return _chart; }; /** * Gets or sets the tension to use for lines drawn, in the range 0 to 1. * This parameter further customizes the interpolation behavior. It is passed to * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#line_tension d3.svg.line.tension} and * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#area_tension d3.svg.area.tension}. * @method tension * @memberof dc.lineChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#line_interpolate d3.svg.line.interpolate} * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#area_interpolate d3.svg.area.interpolate} * @param {Number} [tension=0.7] * @returns {Number|dc.lineChart} */ _chart.tension = function (tension) { if (!arguments.length) { return _tension; } _tension = tension; return _chart; }; /** * Gets or sets a function that will determine discontinuities in the line which should be * skipped: the path will be broken into separate subpaths if some points are undefined. * This function is passed to * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#line_defined d3.svg.line.defined} * * Note: crossfilter will sometimes coerce nulls to 0, so you may need to carefully write * custom reduce functions to get this to work, depending on your data. See * {@link https://github.com/dc-js/dc.js/issues/615#issuecomment-49089248 this GitHub comment} * for more details and an example. * @method defined * @memberof dc.lineChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#line_defined d3.svg.line.defined} * @param {Function} [defined] * @returns {Function|dc.lineChart} */ _chart.defined = function (defined) { if (!arguments.length) { return _defined; } _defined = defined; return _chart; }; /** * Set the line's d3 dashstyle. This value becomes the 'stroke-dasharray' of line. Defaults to empty * array (solid line). * @method dashStyle * @memberof dc.lineChart * @instance * @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray stroke-dasharray} * @example * // create a Dash Dot Dot Dot * chart.dashStyle([3,1,1,1]); * @param {Array<Number>} [dashStyle=[]] * @returns {Array<Number>|dc.lineChart} */ _chart.dashStyle = function (dashStyle) { if (!arguments.length) { return _dashStyle; } _dashStyle = dashStyle; return _chart; }; /** * Get or set render area flag. If the flag is set to true then the chart will render the area * beneath each line and the line chart effectively becomes an area chart. * @method renderArea * @memberof dc.lineChart * @instance * @param {Boolean} [renderArea=false] * @returns {Boolean|dc.lineChart} */ _chart.renderArea = function (renderArea) { if (!arguments.length) { return _renderArea; } _renderArea = renderArea; return _chart; }; function colors (d, i) { return _chart.getColor.call(d, d.values, i); } function drawLine (layersEnter, layers) { var line = d3.svg.line() .x(function (d) { return _chart.x()(d.x); }) .y(function (d) { return _chart.y()(d.y + d.y0); }) .interpolate(_interpolate) .tension(_tension); if (_defined) { line.defined(_defined); } var path = layersEnter.append('path') .attr('class', 'line') .attr('stroke', colors); if (_dashStyle) { path.attr('stroke-dasharray', _dashStyle); } dc.transition(layers.select('path.line'), _chart.transitionDuration(), _chart.transitionDelay()) //.ease('linear') .attr('stroke', colors) .attr('d', function (d) { return safeD(line(d.values)); }); } function drawArea (layersEnter, layers) { if (_renderArea) { var area = d3.svg.area() .x(function (d) { return _chart.x()(d.x); }) .y(function (d) { return _chart.y()(d.y + d.y0); }) .y0(function (d) { return _chart.y()(d.y0); }) .interpolate(_interpolate) .tension(_tension); if (_defined) { area.defined(_defined); } layersEnter.append('path') .attr('class', 'area') .attr('fill', colors) .attr('d', function (d) { return safeD(area(d.values)); }); dc.transition(layers.select('path.area'), _chart.transitionDuration(), _chart.transitionDelay()) //.ease('linear') .attr('fill', colors) .attr('d', function (d) { return safeD(area(d.values)); }); } } function safeD (d) { return (!d || d.indexOf('NaN') >= 0) ? 'M0,0' : d; } function drawDots (chartBody, layers) { if (_chart.xyTipsOn() === 'always' || (!_chart.brushOn() && _chart.xyTipsOn())) { var tooltipListClass = TOOLTIP_G_CLASS + '-list'; var tooltips = chartBody.select('g.' + tooltipListClass); if (tooltips.empty()) { tooltips = chartBody.append('g').attr('class', tooltipListClass); } layers.each(function (d, layerIndex) { var points = d.values; if (_defined) { points = points.filter(_defined); } var g = tooltips.select('g.' + TOOLTIP_G_CLASS + '._' + layerIndex); if (g.empty()) { g = tooltips.append('g').attr('class', TOOLTIP_G_CLASS + ' _' + layerIndex); } createRefLines(g); var dots = g.selectAll('circle.' + DOT_CIRCLE_CLASS) .data(points, dc.pluck('x')); dots.enter() .append('circle') .attr('class', DOT_CIRCLE_CLASS) .attr('r', getDotRadius()) .style('fill-opacity', _dataPointFillOpacity) .style('stroke-opacity', _dataPointStrokeOpacity) .attr('fill', _chart.getColor) .on('mousemove', function () { var dot = d3.select(this); showDot(dot); showRefLines(dot, g); }) .on('mouseout', function () { var dot = d3.select(this); hideDot(dot); hideRefLines(g); }); dots.call(renderTitle, d); dc.transition(dots, _chart.transitionDuration()) .attr('cx', function (d) { return dc.utils.safeNumber(_chart.x()(d.x)); }) .attr('cy', function (d) { return dc.utils.safeNumber(_chart.y()(d.y + d.y0)); }) .attr('fill', _chart.getColor); dots.exit().remove(); }); } } _chart.label(function (d) { return dc.utils.printSingleValue(d.y0 + d.y); }, false); function drawLabels (layers) { layers.each(function (d, layerIndex) { var layer = d3.select(this); var labels = layer.selectAll('text.lineLabel') .data(d.values, dc.pluck('x')); labels.enter() .append('text') .attr('class', 'lineLabel') .attr('text-anchor', 'middle'); dc.transition(labels, _chart.transitionDuration()) .attr('x', function (d) { return dc.utils.safeNumber(_chart.x()(d.x)); }) .attr('y', function (d) { var y = _chart.y()(d.y + d.y0) - LABEL_PADDING; return dc.utils.safeNumber(y); }) .text(function (d) { return _chart.label()(d); }); dc.transition(labels.exit(), _chart.transitionDuration()) .attr('height', 0) .remove(); }); } function createRefLines (g) { var yRefLine = g.select('path.' + Y_AXIS_REF_LINE_CLASS).empty() ? g.append('path').attr('class', Y_AXIS_REF_LINE_CLASS) : g.select('path.' + Y_AXIS_REF_LINE_CLASS); yRefLine.style('display', 'none').attr('stroke-dasharray', '5,5'); var xRefLine = g.select('path.' + X_AXIS_REF_LINE_CLASS).empty() ? g.append('path').attr('class', X_AXIS_REF_LINE_CLASS) : g.select('path.' + X_AXIS_REF_LINE_CLASS); xRefLine.style('display', 'none').attr('stroke-dasharray', '5,5'); } function showDot (dot) { dot.style('fill-opacity', 0.8); dot.style('stroke-opacity', 0.8); dot.attr('r', _dotRadius); return dot; } function showRefLines (dot, g) { var x = dot.attr('cx'); var y = dot.attr('cy'); var yAxisX = (_chart._yAxisX() - _chart.margins().left); var yAxisRefPathD = 'M' + yAxisX + ' ' + y + 'L' + (x) + ' ' + (y); var xAxisRefPathD = 'M' + x + ' ' + _chart.yAxisHeight() + 'L' + x + ' ' + y; g.select('path.' + Y_AXIS_REF_LINE_CLASS).style('display', '').attr('d', yAxisRefPathD); g.select('path.' + X_AXIS_REF_LINE_CLASS).style('display', '').attr('d', xAxisRefPathD); } function getDotRadius () { return _dataPointRadius || _dotRadius; } function hideDot (dot) { dot.style('fill-opacity', _dataPointFillOpacity) .style('stroke-opacity', _dataPointStrokeOpacity) .attr('r', getDotRadius()); } function hideRefLines (g) { g.select('path.' + Y_AXIS_REF_LINE_CLASS).style('display', 'none'); g.select('path.' + X_AXIS_REF_LINE_CLASS).style('display', 'none'); } function renderTitle (dot, d) { if (_chart.renderTitle()) { dot.select('title').remove(); dot.append('title').text(dc.pluck('data', _chart.title(d.name))); } } /** * Turn on/off the mouseover behavior of an individual data point which renders a circle and x/y axis * dashed lines back to each respective axis. This is ignored if the chart * {@link dc.coordinateGridMixin#brushOn brush} is on * @method xyTipsOn * @memberof dc.lineChart * @instance * @param {Boolean} [xyTipsOn=false] * @returns {Boolean|dc.lineChart} */ _chart.xyTipsOn = function (xyTipsOn) { if (!arguments.length) { return _xyTipsOn; } _xyTipsOn = xyTipsOn; return _chart; }; /** * Get or set the radius (in px) for dots displayed on the data points. * @method dotRadius * @memberof dc.lineChart * @instance * @param {Number} [dotRadius=5] * @returns {Number|dc.lineChart} */ _chart.dotRadius = function (dotRadius) { if (!arguments.length) { return _dotRadius; } _dotRadius = dotRadius; return _chart; }; /** * Always show individual dots for each datapoint. * * If `options` is falsy, it disables data point rendering. If no `options` are provided, the * current `options` values are instead returned. * @method renderDataPoints * @memberof dc.lineChart * @instance * @example * chart.renderDataPoints({radius: 2, fillOpacity: 0.8, strokeOpacity: 0.8}) * @param {{fillOpacity: Number, strokeOpacity: Number, radius: Number}} [options={fillOpacity: 0.8, strokeOpacity: 0.8, radius: 2}] * @returns {{fillOpacity: Number, strokeOpacity: Number, radius: Number}|dc.lineChart} */ _chart.renderDataPoints = function (options) { if (!arguments.length) { return { fillOpacity: _dataPointFillOpacity, strokeOpacity: _dataPointStrokeOpacity, radius: _dataPointRadius }; } else if (!options) { _dataPointFillOpacity = DEFAULT_DOT_OPACITY; _dataPointStrokeOpacity = DEFAULT_DOT_OPACITY; _dataPointRadius = null; } else { _dataPointFillOpacity = options.fillOpacity || 0.8; _dataPointStrokeOpacity = options.strokeOpacity || 0.8; _dataPointRadius = options.radius || 2; } return _chart; }; function colorFilter (color, dashstyle, inv) { return function () { var item = d3.select(this); var match = (item.attr('stroke') === color && item.attr('stroke-dasharray') === ((dashstyle instanceof Array) ? dashstyle.join(',') : null)) || item.attr('fill') === color; return inv ? !match : match; }; } _chart.legendHighlight = function (d) { if (!_chart.isLegendableHidden(d)) { _chart.g().selectAll('path.line, path.area') .classed('highlight', colorFilter(d.color, d.dashstyle)) .classed('fadeout', colorFilter(d.color, d.dashstyle, true)); } }; _chart.legendReset = function () { _chart.g().selectAll('path.line, path.area') .classed('highlight', false) .classed('fadeout', false); }; dc.override(_chart, 'legendables', function () { var legendables = _chart._legendables(); if (!_dashStyle) { return legendables; } return legendables.map(function (l) { l.dashstyle = _dashStyle; return l; }); }); return _chart.anchor(parent, chartGroup); }; /** * The data count widget is a simple widget designed to display the number of records selected by the * current filters out of the total number of records in the data set. Once created the data count widget * will automatically update the text content of child elements with the following classes: * * * `.total-count` - total number of records * * `.filter-count` - number of records matched by the current filters * * Note: this widget works best for the specific case of showing the number of records out of a * total. If you want a more general-purpose numeric display, please use the * {@link dc.numberDisplay} widget instead. * * Examples: * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index} * @class dataCount * @memberof dc * @mixes dc.baseMixin * @example * var ndx = crossfilter(data); * var all = ndx.groupAll(); * * dc.dataCount('.dc-data-count') * .dimension(ndx) * .group(all); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.dataCount} */ dc.dataCount = function (parent, chartGroup) { var _formatNumber = d3.format(',d'); var _chart = dc.baseMixin({}); var _html = {some: '', all: ''}; /** * Gets or sets an optional object specifying HTML templates to use depending how many items are * selected. The text `%total-count` will replaced with the total number of records, and the text * `%filter-count` will be replaced with the number of selected records. * - all: HTML template to use if all items are selected * - some: HTML template to use if not all items are selected * @method html * @memberof dc.dataCount * @instance * @example * counter.html({ * some: '%filter-count out of %total-count records selected', * all: 'All records selected. Click on charts to apply filters' * }) * @param {{some:String, all: String}} [options] * @returns {{some:String, all: String}|dc.dataCount} */ _chart.html = function (options) { if (!arguments.length) { return _html; } if (options.all) { _html.all = options.all; } if (options.some) { _html.some = options.some; } return _chart; }; /** * Gets or sets an optional function to format the filter count and total count. * @method formatNumber * @memberof dc.dataCount * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md d3.format} * @example * counter.formatNumber(d3.format('.2g')) * @param {Function} [formatter=d3.format('.2g')] * @returns {Function|dc.dataCount} */ _chart.formatNumber = function (formatter) { if (!arguments.length) { return _formatNumber; } _formatNumber = formatter; return _chart; }; _chart._doRender = function () { var tot = _chart.dimension().size(), val = _chart.group().value(); var all = _formatNumber(tot); var selected = _formatNumber(val); if ((tot === val) && (_html.all !== '')) { _chart.root().html(_html.all.replace('%total-count', all).replace('%filter-count', selected)); } else if (_html.some !== '') { _chart.root().html(_html.some.replace('%total-count', all).replace('%filter-count', selected)); } else { _chart.selectAll('.total-count').text(all); _chart.selectAll('.filter-count').text(selected); } return _chart; }; _chart._doRedraw = function () { return _chart._doRender(); }; return _chart.anchor(parent, chartGroup); }; /** * The data table is a simple widget designed to list crossfilter focused data set (rows being * filtered) in a good old tabular fashion. * * Note: Unlike other charts, the data table (and data grid chart) use the {@link dc.dataTable#group group} attribute as a * keying function for {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#nest nesting} the data * together in groups. Do not pass in a crossfilter group as this will not work. * * Another interesting feature of the data table is that you can pass a crossfilter group to the `dimension`, as * long as you specify the {@link dc.dataTable#order order} as `d3.descending`, since the data * table will use `dimension.top()` to fetch the data in that case, and the method is equally * supported on the crossfilter group as the crossfilter dimension. * * Examples: * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index} * - {@link http://dc-js.github.io/dc.js/examples/table-on-aggregated-data.html dataTable on a crossfilter group} * ({@link https://github.com/dc-js/dc.js/blob/develop/web/examples/table-on-aggregated-data.html source}) * @class dataTable * @memberof dc * @mixes dc.baseMixin * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.dataTable} */ dc.dataTable = function (parent, chartGroup) { var LABEL_CSS_CLASS = 'dc-table-label'; var ROW_CSS_CLASS = 'dc-table-row'; var COLUMN_CSS_CLASS = 'dc-table-column'; var GROUP_CSS_CLASS = 'dc-table-group'; var HEAD_CSS_CLASS = 'dc-table-head'; var _chart = dc.baseMixin({}); var _size = 25; var _columns = []; var _sortBy = function (d) { return d; }; var _order = d3.ascending; var _beginSlice = 0; var _endSlice; var _showGroups = true; _chart._doRender = function () { _chart.selectAll('tbody').remove(); renderRows(renderGroups()); return _chart; }; _chart._doColumnValueFormat = function (v, d) { return ((typeof v === 'function') ? v(d) : // v as function ((typeof v === 'string') ? d[v] : // v is field name string v.format(d) // v is Object, use fn (element 2) ) ); }; _chart._doColumnHeaderFormat = function (d) { // if 'function', convert to string representation // show a string capitalized // if an object then display its label string as-is. return (typeof d === 'function') ? _chart._doColumnHeaderFnToString(d) : ((typeof d === 'string') ? _chart._doColumnHeaderCapitalize(d) : String(d.label)); }; _chart._doColumnHeaderCapitalize = function (s) { // capitalize return s.charAt(0).toUpperCase() + s.slice(1); }; _chart._doColumnHeaderFnToString = function (f) { // columnString(f) { var s = String(f); var i1 = s.indexOf('return '); if (i1 >= 0) { var i2 = s.lastIndexOf(';'); if (i2 >= 0) { s = s.substring(i1 + 7, i2); var i3 = s.indexOf('numberFormat'); if (i3 >= 0) { s = s.replace('numberFormat', ''); } } } return s; }; function renderGroups () { // The 'original' example uses all 'functions'. // If all 'functions' are used, then don't remove/add a header, and leave // the html alone. This preserves the functionality of earlier releases. // A 2nd option is a string representing a field in the data. // A third option is to supply an Object such as an array of 'information', and // supply your own _doColumnHeaderFormat and _doColumnValueFormat functions to // create what you need. var bAllFunctions = true; _columns.forEach(function (f) { bAllFunctions = bAllFunctions & (typeof f === 'function'); }); if (!bAllFunctions) { // ensure one thead var thead = _chart.selectAll('thead').data([0]); thead.enter().append('thead'); thead.exit().remove(); // with one tr var headrow = thead.selectAll('tr').data([0]); headrow.enter().append('tr'); headrow.exit().remove(); // with a th for each column var headcols = headrow.selectAll('th') .data(_columns); headcols.enter().append('th'); headcols.exit().remove(); headcols .attr('class', HEAD_CSS_CLASS) .html(function (d) { return (_chart._doColumnHeaderFormat(d)); }); } var groups = _chart.root().selectAll('tbody') .data(nestEntries(), function (d) { return _chart.keyAccessor()(d); }); var rowGroup = groups .enter() .append('tbody'); if (_showGroups === true) { rowGroup .append('tr') .attr('class', GROUP_CSS_CLASS) .append('td') .attr('class', LABEL_CSS_CLASS) .attr('colspan', _columns.length) .html(function (d) { return _chart.keyAccessor()(d); }); } groups.exit().remove(); return rowGroup; } function nestEntries () { var entries; if (_order === d3.ascending) { entries = _chart.dimension().bottom(_size); } else { entries = _chart.dimension().top(_size); } return d3.nest() .key(_chart.group()) .sortKeys(_order) .entries(entries.sort(function (a, b) { return _order(_sortBy(a), _sortBy(b)); }).slice(_beginSlice, _endSlice)); } function renderRows (groups) { var rows = groups.order() .selectAll('tr.' + ROW_CSS_CLASS) .data(function (d) { return d.values; }); var rowEnter = rows.enter() .append('tr') .attr('class', ROW_CSS_CLASS); _columns.forEach(function (v, i) { rowEnter.append('td') .attr('class', COLUMN_CSS_CLASS + ' _' + i) .html(function (d) { return _chart._doColumnValueFormat(v, d); }); }); rows.exit().remove(); return rows; } _chart._doRedraw = function () { return _chart._doRender(); }; /** * Get or set the group function for the data table. The group function takes a data row and * returns the key to specify to {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_nest d3.nest} * to split rows into groups. * * Do not pass in a crossfilter group as this will not work. * @method group * @memberof dc.dataTable * @instance * @example * // group rows by the value of their field * chart * .group(function(d) { return d.field; }) * @param {Function} groupFunction Function taking a row of data and returning the nest key. * @returns {Function|dc.dataTable} */ /** * Get or set the table size which determines the number of rows displayed by the widget. * @method size * @memberof dc.dataTable * @instance * @param {Number} [size=25] * @returns {Number|dc.dataTable} */ _chart.size = function (size) { if (!arguments.length) { return _size; } _size = size; return _chart; }; /** * Get or set the index of the beginning slice which determines which entries get displayed * by the widget. Useful when implementing pagination. * * Note: the sortBy function will determine how the rows are ordered for pagination purposes. * See the {@link http://dc-js.github.io/dc.js/examples/table-pagination.html table pagination example} * to see how to implement the pagination user interface using `beginSlice` and `endSlice`. * @method beginSlice * @memberof dc.dataTable * @instance * @param {Number} [beginSlice=0] * @returns {Number|dc.dataTable} */ _chart.beginSlice = function (beginSlice) { if (!arguments.length) { return _beginSlice; } _beginSlice = beginSlice; return _chart; }; /** * Get or set the index of the end slice which determines which entries get displayed by the * widget. Useful when implementing pagination. See {@link dc.dataTable#beginSlice `beginSlice`} for more information. * @method endSlice * @memberof dc.dataTable * @instance * @param {Number|undefined} [endSlice=undefined] * @returns {Number|dc.dataTable} */ _chart.endSlice = function (endSlice) { if (!arguments.length) { return _endSlice; } _endSlice = endSlice; return _chart; }; /** * Get or set column functions. The data table widget supports several methods of specifying the * columns to display. * * The original method uses an array of functions to generate dynamic columns. Column functions * are simple javascript functions with only one input argument `d` which represents a row in * the data set. The return value of these functions will be used to generate the content for * each cell. However, this method requires the HTML for the table to have a fixed set of column * headers. * * <pre><code>chart.columns([ * function(d) { return d.date; }, * function(d) { return d.open; }, * function(d) { return d.close; }, * function(d) { return numberFormat(d.close - d.open); }, * function(d) { return d.volume; } * ]); * </code></pre> * * In the second method, you can list the columns to read from the data without specifying it as * a function, except where necessary (ie, computed columns). Note the data element name is * capitalized when displayed in the table header. You can also mix in functions as necessary, * using the third `{label, format}` form, as shown below. * * <pre><code>chart.columns([ * "date", // d["date"], ie, a field accessor; capitalized automatically * "open", // ... * "close", // ... * { * label: "Change", * format: function (d) { * return numberFormat(d.close - d.open); * } * }, * "volume" // d["volume"], ie, a field accessor; capitalized automatically * ]); * </code></pre> * * In the third example, we specify all fields using the `{label, format}` method: * <pre><code>chart.columns([ * { * label: "Date", * format: function (d) { return d.date; } * }, * { * label: "Open", * format: function (d) { return numberFormat(d.open); } * }, * { * label: "Close", * format: function (d) { return numberFormat(d.close); } * }, * { * label: "Change", * format: function (d) { return numberFormat(d.close - d.open); } * }, * { * label: "Volume", * format: function (d) { return d.volume; } * } * ]); * </code></pre> * * You may wish to override the dataTable functions `_doColumnHeaderCapitalize` and * `_doColumnHeaderFnToString`, which are used internally to translate the column information or * function into a displayed header. The first one is used on the "string" column specifier; the * second is used to transform a stringified function into something displayable. For the Stock * example, the function for Change becomes the table header **d.close - d.open**. * * Finally, you can even specify a completely different form of column definition. To do this, * override `_chart._doColumnHeaderFormat` and `_chart._doColumnValueFormat` Be aware that * fields without numberFormat specification will be displayed just as they are stored in the * data, unformatted. * @method columns * @memberof dc.dataTable * @instance * @param {Array<Function>} [columns=[]] * @returns {Array<Function>}|dc.dataTable} */ _chart.columns = function (columns) { if (!arguments.length) { return _columns; } _columns = columns; return _chart; }; /** * Get or set sort-by function. This function works as a value accessor at row level and returns a * particular field to be sorted by. * @method sortBy * @memberof dc.dataTable * @instance * @example * chart.sortBy(function(d) { * return d.date; * }); * @param {Function} [sortBy=identity function] * @returns {Function|dc.dataTable} */ _chart.sortBy = function (sortBy) { if (!arguments.length) { return _sortBy; } _sortBy = sortBy; return _chart; }; /** * Get or set sort order. If the order is `d3.ascending`, the data table will use * `dimension().bottom()` to fetch the data; otherwise it will use `dimension().top()` * @method order * @memberof dc.dataTable * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_ascending d3.ascending} * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_descending d3.descending} * @example * chart.order(d3.descending); * @param {Function} [order=d3.ascending] * @returns {Function|dc.dataTable} */ _chart.order = function (order) { if (!arguments.length) { return _order; } _order = order; return _chart; }; /** * Get or set if group rows will be shown. The dataTable {@link dc.dataTable#group group} * function must be specified even if groups are not shown. * @method showGroups * @memberof dc.dataTable * @instance * @example * chart * .group([value], [name]) * .showGroups(true|false); * @param {Boolean} [showGroups=true] * @returns {Boolean|dc.dataTable} */ _chart.showGroups = function (showGroups) { if (!arguments.length) { return _showGroups; } _showGroups = showGroups; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * Data grid is a simple widget designed to list the filtered records, providing * a simple way to define how the items are displayed. * * Note: Unlike other charts, the data grid chart (and data table) use the {@link dc.dataGrid#group group} attribute as a keying function * for {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#nest nesting} the data together in groups. * Do not pass in a crossfilter group as this will not work. * * Examples: * - {@link http://europarl.me/dc.js/web/ep/index.html List of members of the european parliament} * @class dataGrid * @memberof dc * @mixes dc.baseMixin * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.dataGrid} */ dc.dataGrid = function (parent, chartGroup) { var LABEL_CSS_CLASS = 'dc-grid-label'; var ITEM_CSS_CLASS = 'dc-grid-item'; var GROUP_CSS_CLASS = 'dc-grid-group'; var GRID_CSS_CLASS = 'dc-grid-top'; var _chart = dc.baseMixin({}); var _size = 999; // shouldn't be needed, but you might var _html = function (d) { return 'you need to provide an html() handling param: ' + JSON.stringify(d); }; var _sortBy = function (d) { return d; }; var _order = d3.ascending; var _beginSlice = 0, _endSlice; var _htmlGroup = function (d) { return '<div class=\'' + GROUP_CSS_CLASS + '\'><h1 class=\'' + LABEL_CSS_CLASS + '\'>' + _chart.keyAccessor()(d) + '</h1></div>'; }; _chart._doRender = function () { _chart.selectAll('div.' + GRID_CSS_CLASS).remove(); renderItems(renderGroups()); return _chart; }; function renderGroups () { var groups = _chart.root().selectAll('div.' + GRID_CSS_CLASS) .data(nestEntries(), function (d) { return _chart.keyAccessor()(d); }); var itemGroup = groups .enter() .append('div') .attr('class', GRID_CSS_CLASS); if (_htmlGroup) { itemGroup .html(function (d) { return _htmlGroup(d); }); } groups.exit().remove(); return itemGroup; } function nestEntries () { var entries = _chart.dimension().top(_size); return d3.nest() .key(_chart.group()) .sortKeys(_order) .entries(entries.sort(function (a, b) { return _order(_sortBy(a), _sortBy(b)); }).slice(_beginSlice, _endSlice)); } function renderItems (groups) { var items = groups.order() .selectAll('div.' + ITEM_CSS_CLASS) .data(function (d) { return d.values; }); items.enter() .append('div') .attr('class', ITEM_CSS_CLASS) .html(function (d) { return _html(d); }); items.exit().remove(); return items; } _chart._doRedraw = function () { return _chart._doRender(); }; /** * Get or set the group function for the data grid. The group function takes a data row and * returns the key to specify to {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_nest d3.nest} * to split rows into groups. * * Do not pass in a crossfilter group as this will not work. * @method group * @memberof dc.dataGrid * @instance * @example * // group rows by the value of their field * chart * .group(function(d) { return d.field; }) * @param {Function} groupFunction Function taking a row of data and returning the nest key. * @returns {Function|dc.dataTable} */ /** * Get or set the index of the beginning slice which determines which entries get displayed by the widget. * Useful when implementing pagination. * @method beginSlice * @memberof dc.dataGrid * @instance * @param {Number} [beginSlice=0] * @returns {Number|dc.dataGrid} */ _chart.beginSlice = function (beginSlice) { if (!arguments.length) { return _beginSlice; } _beginSlice = beginSlice; return _chart; }; /** * Get or set the index of the end slice which determines which entries get displayed by the widget. * Useful when implementing pagination. * @method endSlice * @memberof dc.dataGrid * @instance * @param {Number} [endSlice] * @returns {Number|dc.dataGrid} */ _chart.endSlice = function (endSlice) { if (!arguments.length) { return _endSlice; } _endSlice = endSlice; return _chart; }; /** * Get or set the grid size which determines the number of items displayed by the widget. * @method size * @memberof dc.dataGrid * @instance * @param {Number} [size=999] * @returns {Number|dc.dataGrid} */ _chart.size = function (size) { if (!arguments.length) { return _size; } _size = size; return _chart; }; /** * Get or set the function that formats an item. The data grid widget uses a * function to generate dynamic html. Use your favourite templating engine or * generate the string directly. * @method html * @memberof dc.dataGrid * @instance * @example * chart.html(function (d) { return '<div class='item '+data.exampleCategory+''>'+data.exampleString+'</div>';}); * @param {Function} [html] * @returns {Function|dc.dataGrid} */ _chart.html = function (html) { if (!arguments.length) { return _html; } _html = html; return _chart; }; /** * Get or set the function that formats a group label. * @method htmlGroup * @memberof dc.dataGrid * @instance * @example * chart.htmlGroup (function (d) { return '<h2>'.d.key . 'with ' . d.values.length .' items</h2>'}); * @param {Function} [htmlGroup] * @returns {Function|dc.dataGrid} */ _chart.htmlGroup = function (htmlGroup) { if (!arguments.length) { return _htmlGroup; } _htmlGroup = htmlGroup; return _chart; }; /** * Get or set sort-by function. This function works as a value accessor at the item * level and returns a particular field to be sorted. * @method sortBy * @memberof dc.dataGrid * @instance * @example * chart.sortBy(function(d) { * return d.date; * }); * @param {Function} [sortByFunction] * @returns {Function|dc.dataGrid} */ _chart.sortBy = function (sortByFunction) { if (!arguments.length) { return _sortBy; } _sortBy = sortByFunction; return _chart; }; /** * Get or set sort the order function. * @method order * @memberof dc.dataGrid * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_ascending d3.ascending} * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_descending d3.descending} * @example * chart.order(d3.descending); * @param {Function} [order=d3.ascending] * @returns {Function|dc.dataGrid} */ _chart.order = function (order) { if (!arguments.length) { return _order; } _order = order; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * A concrete implementation of a general purpose bubble chart that allows data visualization using the * following dimensions: * - x axis position * - y axis position * - bubble radius * - color * * Examples: * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index} * - {@link http://dc-js.github.com/dc.js/vc/index.html US Venture Capital Landscape 2011} * @class bubbleChart * @memberof dc * @mixes dc.bubbleMixin * @mixes dc.coordinateGridMixin * @example * // create a bubble chart under #chart-container1 element using the default global chart group * var bubbleChart1 = dc.bubbleChart('#chart-container1'); * // create a bubble chart under #chart-container2 element using chart group A * var bubbleChart2 = dc.bubbleChart('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.bubbleChart} */ dc.bubbleChart = function (parent, chartGroup) { var _chart = dc.bubbleMixin(dc.coordinateGridMixin({})); var _elasticRadius = false; var _sortBubbleSize = false; _chart.transitionDuration(750); _chart.transitionDelay(0); var bubbleLocator = function (d) { return 'translate(' + (bubbleX(d)) + ',' + (bubbleY(d)) + ')'; }; /** * Turn on or off the elastic bubble radius feature, or return the value of the flag. If this * feature is turned on, then bubble radii will be automatically rescaled to fit the chart better. * @method elasticRadius * @memberof dc.bubbleChart * @instance * @param {Boolean} [elasticRadius=false] * @returns {Boolean|dc.bubbleChart} */ _chart.elasticRadius = function (elasticRadius) { if (!arguments.length) { return _elasticRadius; } _elasticRadius = elasticRadius; return _chart; }; /** * Turn on or off the bubble sorting feature, or return the value of the flag. If enabled, * bubbles will be sorted by their radius, with smaller bubbles in front. * @method sortBubbleSize * @memberof dc.bubbleChart * @instance * @param {Boolean} [sortBubbleSize=false] * @returns {Boolean|dc.bubbleChart} */ _chart.sortBubbleSize = function (sortBubbleSize) { if (!arguments.length) { return _sortBubbleSize; } _sortBubbleSize = sortBubbleSize; return _chart; }; _chart.plotData = function () { if (_elasticRadius) { _chart.r().domain([_chart.rMin(), _chart.rMax()]); } _chart.r().range([_chart.MIN_RADIUS, _chart.xAxisLength() * _chart.maxBubbleRelativeSize()]); var data = _chart.data(); if (_sortBubbleSize) { // sort descending so smaller bubbles are on top var radiusAccessor = _chart.radiusValueAccessor(); data.sort(function (a, b) { return d3.descending(radiusAccessor(a), radiusAccessor(b)); }); } var bubbleG = _chart.chartBodyG().selectAll('g.' + _chart.BUBBLE_NODE_CLASS) .data(data, function (d) { return d.key; }); if (_sortBubbleSize) { // Call order here to update dom order based on sort bubbleG.order(); } renderNodes(bubbleG); updateNodes(bubbleG); removeNodes(bubbleG); _chart.fadeDeselectedArea(); }; function renderNodes (bubbleG) { var bubbleGEnter = bubbleG.enter().append('g'); bubbleGEnter .attr('class', _chart.BUBBLE_NODE_CLASS) .attr('transform', bubbleLocator) .append('circle').attr('class', function (d, i) { return _chart.BUBBLE_CLASS + ' _' + i; }) .on('click', _chart.onClick) .attr('fill', _chart.getColor) .attr('r', 0); dc.transition(bubbleG, _chart.transitionDuration(), _chart.transitionDelay()) .select('circle.' + _chart.BUBBLE_CLASS) .attr('r', function (d) { return _chart.bubbleR(d); }) .attr('opacity', function (d) { return (_chart.bubbleR(d) > 0) ? 1 : 0; }); _chart._doRenderLabel(bubbleGEnter); _chart._doRenderTitles(bubbleGEnter); } function updateNodes (bubbleG) { dc.transition(bubbleG, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', bubbleLocator) .select('circle.' + _chart.BUBBLE_CLASS) .attr('fill', _chart.getColor) .attr('r', function (d) { return _chart.bubbleR(d); }) .attr('opacity', function (d) { return (_chart.bubbleR(d) > 0) ? 1 : 0; }); _chart.doUpdateLabels(bubbleG); _chart.doUpdateTitles(bubbleG); } function removeNodes (bubbleG) { bubbleG.exit().remove(); } function bubbleX (d) { var x = _chart.x()(_chart.keyAccessor()(d)); if (isNaN(x)) { x = 0; } return x; } function bubbleY (d) { var y = _chart.y()(_chart.valueAccessor()(d)); if (isNaN(y)) { y = 0; } return y; } _chart.renderBrush = function () { // override default x axis brush from parent chart }; _chart.redrawBrush = function () { // override default x axis brush from parent chart _chart.fadeDeselectedArea(); }; return _chart.anchor(parent, chartGroup); }; /** * Composite charts are a special kind of chart that render multiple charts on the same Coordinate * Grid. You can overlay (compose) different bar/line/area charts in a single composite chart to * achieve some quite flexible charting effects. * @class compositeChart * @memberof dc * @mixes dc.coordinateGridMixin * @example * // create a composite chart under #chart-container1 element using the default global chart group * var compositeChart1 = dc.compositeChart('#chart-container1'); * // create a composite chart under #chart-container2 element using chart group A * var compositeChart2 = dc.compositeChart('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.compositeChart} */ dc.compositeChart = function (parent, chartGroup) { var SUB_CHART_CLASS = 'sub'; var DEFAULT_RIGHT_Y_AXIS_LABEL_PADDING = 12; var _chart = dc.coordinateGridMixin({}); var _children = []; var _childOptions = {}; var _shareColors = false, _shareTitle = true, _alignYAxes = false; var _rightYAxis = d3.svg.axis(), _rightYAxisLabel = 0, _rightYAxisLabelPadding = DEFAULT_RIGHT_Y_AXIS_LABEL_PADDING, _rightY, _rightAxisGridLines = false; _chart._mandatoryAttributes([]); _chart.transitionDuration(500); _chart.transitionDelay(0); dc.override(_chart, '_generateG', function () { var g = this.__generateG(); for (var i = 0; i < _children.length; ++i) { var child = _children[i]; generateChildG(child, i); if (!child.dimension()) { child.dimension(_chart.dimension()); } if (!child.group()) { child.group(_chart.group()); } child.chartGroup(_chart.chartGroup()); child.svg(_chart.svg()); child.xUnits(_chart.xUnits()); child.transitionDuration(_chart.transitionDuration(), _chart.transitionDelay()); child.brushOn(_chart.brushOn()); child.renderTitle(_chart.renderTitle()); child.elasticX(_chart.elasticX()); } return g; }); _chart._brushing = function () { var extent = _chart.extendBrush(); var brushIsEmpty = _chart.brushIsEmpty(extent); for (var i = 0; i < _children.length; ++i) { _children[i].replaceFilter(brushIsEmpty ? null : extent); } }; _chart._prepareYAxis = function () { var left = (leftYAxisChildren().length !== 0); var right = (rightYAxisChildren().length !== 0); var ranges = calculateYAxisRanges(left, right); if (left) { prepareLeftYAxis(ranges); } if (right) { prepareRightYAxis(ranges); } if (leftYAxisChildren().length > 0 && !_rightAxisGridLines) { _chart._renderHorizontalGridLinesForAxis(_chart.g(), _chart.y(), _chart.yAxis()); } else if (rightYAxisChildren().length > 0) { _chart._renderHorizontalGridLinesForAxis(_chart.g(), _rightY, _rightYAxis); } }; _chart.renderYAxis = function () { if (leftYAxisChildren().length !== 0) { _chart.renderYAxisAt('y', _chart.yAxis(), _chart.margins().left); _chart.renderYAxisLabel('y', _chart.yAxisLabel(), -90); } if (rightYAxisChildren().length !== 0) { _chart.renderYAxisAt('yr', _chart.rightYAxis(), _chart.width() - _chart.margins().right); _chart.renderYAxisLabel('yr', _chart.rightYAxisLabel(), 90, _chart.width() - _rightYAxisLabelPadding); } }; function calculateYAxisRanges (left, right) { var lyAxisMin, lyAxisMax, ryAxisMin, ryAxisMax; var ranges; if (left) { lyAxisMin = yAxisMin(); lyAxisMax = yAxisMax(); } if (right) { ryAxisMin = rightYAxisMin(); ryAxisMax = rightYAxisMax(); } if (_chart.alignYAxes() && left && right) { ranges = alignYAxisRanges(lyAxisMin, lyAxisMax, ryAxisMin, ryAxisMax); } return ranges || { lyAxisMin: lyAxisMin, lyAxisMax: lyAxisMax, ryAxisMin: ryAxisMin, ryAxisMax: ryAxisMax }; } function alignYAxisRanges (lyAxisMin, lyAxisMax, ryAxisMin, ryAxisMax) { // since the two series will share a zero, each Y is just a multiple // of the other. and the ratio should be the ratio of the ranges of the // input data, so that they come out the same height. so we just min/max // note: both ranges already include zero due to the stack mixin (#667) // if #667 changes, we can reconsider whether we want data height or // height from zero to be equal. and it will be possible for the axes // to be aligned but not visible. var extentRatio = (ryAxisMax - ryAxisMin) / (lyAxisMax - lyAxisMin); return { lyAxisMin: Math.min(lyAxisMin, ryAxisMin / extentRatio), lyAxisMax: Math.max(lyAxisMax, ryAxisMax / extentRatio), ryAxisMin: Math.min(ryAxisMin, lyAxisMin * extentRatio), ryAxisMax: Math.max(ryAxisMax, lyAxisMax * extentRatio) }; } function prepareRightYAxis (ranges) { var needDomain = _chart.rightY() === undefined || _chart.elasticY(), needRange = needDomain || _chart.resizing(); if (_chart.rightY() === undefined) { _chart.rightY(d3.scale.linear()); } if (needDomain) { _chart.rightY().domain([ranges.ryAxisMin, ranges.ryAxisMax]); } if (needRange) { _chart.rightY().rangeRound([_chart.yAxisHeight(), 0]); } _chart.rightY().range([_chart.yAxisHeight(), 0]); _chart.rightYAxis(_chart.rightYAxis().scale(_chart.rightY())); _chart.rightYAxis().orient('right'); } function prepareLeftYAxis (ranges) { var needDomain = _chart.y() === undefined || _chart.elasticY(), needRange = needDomain || _chart.resizing(); if (_chart.y() === undefined) { _chart.y(d3.scale.linear()); } if (needDomain) { _chart.y().domain([ranges.lyAxisMin, ranges.lyAxisMax]); } if (needRange) { _chart.y().rangeRound([_chart.yAxisHeight(), 0]); } _chart.y().range([_chart.yAxisHeight(), 0]); _chart.yAxis(_chart.yAxis().scale(_chart.y())); _chart.yAxis().orient('left'); } function generateChildG (child, i) { child._generateG(_chart.g()); child.g().attr('class', SUB_CHART_CLASS + ' _' + i); } _chart.plotData = function () { for (var i = 0; i < _children.length; ++i) { var child = _children[i]; if (!child.g()) { generateChildG(child, i); } if (_shareColors) { child.colors(_chart.colors()); } child.x(_chart.x()); child.xAxis(_chart.xAxis()); if (child.useRightYAxis()) { child.y(_chart.rightY()); child.yAxis(_chart.rightYAxis()); } else { child.y(_chart.y()); child.yAxis(_chart.yAxis()); } child.plotData(); child._activateRenderlets(); } }; /** * Get or set whether to draw gridlines from the right y axis. Drawing from the left y axis is the * default behavior. This option is only respected when subcharts with both left and right y-axes * are present. * @method useRightAxisGridLines * @memberof dc.compositeChart * @instance * @param {Boolean} [useRightAxisGridLines=false] * @returns {Boolean|dc.compositeChart} */ _chart.useRightAxisGridLines = function (useRightAxisGridLines) { if (!arguments) { return _rightAxisGridLines; } _rightAxisGridLines = useRightAxisGridLines; return _chart; }; /** * Get or set chart-specific options for all child charts. This is equivalent to calling * {@link dc.baseMixin#options .options} on each child chart. * @method childOptions * @memberof dc.compositeChart * @instance * @param {Object} [childOptions] * @returns {Object|dc.compositeChart} */ _chart.childOptions = function (childOptions) { if (!arguments.length) { return _childOptions; } _childOptions = childOptions; _children.forEach(function (child) { child.options(_childOptions); }); return _chart; }; _chart.fadeDeselectedArea = function () { for (var i = 0; i < _children.length; ++i) { var child = _children[i]; child.brush(_chart.brush()); child.fadeDeselectedArea(); } }; /** * Set or get the right y axis label. * @method rightYAxisLabel * @memberof dc.compositeChart * @instance * @param {String} [rightYAxisLabel] * @param {Number} [padding] * @returns {String|dc.compositeChart} */ _chart.rightYAxisLabel = function (rightYAxisLabel, padding) { if (!arguments.length) { return _rightYAxisLabel; } _rightYAxisLabel = rightYAxisLabel; _chart.margins().right -= _rightYAxisLabelPadding; _rightYAxisLabelPadding = (padding === undefined) ? DEFAULT_RIGHT_Y_AXIS_LABEL_PADDING : padding; _chart.margins().right += _rightYAxisLabelPadding; return _chart; }; /** * Combine the given charts into one single composite coordinate grid chart. * @method compose * @memberof dc.compositeChart * @instance * @example * moveChart.compose([ * // when creating sub-chart you need to pass in the parent chart * dc.lineChart(moveChart) * .group(indexAvgByMonthGroup) // if group is missing then parent's group will be used * .valueAccessor(function (d){return d.value.avg;}) * // most of the normal functions will continue to work in a composed chart * .renderArea(true) * .stack(monthlyMoveGroup, function (d){return d.value;}) * .title(function (d){ * var value = d.value.avg?d.value.avg:d.value; * if(isNaN(value)) value = 0; * return dateFormat(d.key) + '\n' + numberFormat(value); * }), * dc.barChart(moveChart) * .group(volumeByMonthGroup) * .centerBar(true) * ]); * @param {Array<Chart>} [subChartArray] * @returns {dc.compositeChart} */ _chart.compose = function (subChartArray) { _children = subChartArray; _children.forEach(function (child) { child.height(_chart.height()); child.width(_chart.width()); child.margins(_chart.margins()); if (_shareTitle) { child.title(_chart.title()); } child.options(_childOptions); }); return _chart; }; /** * Returns the child charts which are composed into the composite chart. * @method children * @memberof dc.compositeChart * @instance * @returns {Array<dc.baseMixin>} */ _chart.children = function () { return _children; }; /** * Get or set color sharing for the chart. If set, the {@link dc.colorMixin#colors .colors()} value from this chart * will be shared with composed children. Additionally if the child chart implements * Stackable and has not set a custom .colorAccessor, then it will generate a color * specific to its order in the composition. * @method shareColors * @memberof dc.compositeChart * @instance * @param {Boolean} [shareColors=false] * @returns {Boolean|dc.compositeChart} */ _chart.shareColors = function (shareColors) { if (!arguments.length) { return _shareColors; } _shareColors = shareColors; return _chart; }; /** * Get or set title sharing for the chart. If set, the {@link dc.baseMixin#title .title()} value from * this chart will be shared with composed children. * @method shareTitle * @memberof dc.compositeChart * @instance * @param {Boolean} [shareTitle=true] * @returns {Boolean|dc.compositeChart} */ _chart.shareTitle = function (shareTitle) { if (!arguments.length) { return _shareTitle; } _shareTitle = shareTitle; return _chart; }; /** * Get or set the y scale for the right axis. The right y scale is typically automatically * generated by the chart implementation. * @method rightY * @memberof dc.compositeChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Scales.md d3.scale} * @param {d3.scale} [yScale] * @returns {d3.scale|dc.compositeChart} */ _chart.rightY = function (yScale) { if (!arguments.length) { return _rightY; } _rightY = yScale; _chart.rescale(); return _chart; }; /** * Get or set alignment between left and right y axes. A line connecting '0' on both y axis * will be parallel to x axis. This only has effect when {@link #dc.coordinateGridMixin+elasticY elasticY} is true. * @method alignYAxes * @memberof dc.compositeChart * @instance * @param {Boolean} [alignYAxes=false] * @returns {Chart} */ _chart.alignYAxes = function (alignYAxes) { if (!arguments.length) { return _alignYAxes; } _alignYAxes = alignYAxes; _chart.rescale(); return _chart; }; function leftYAxisChildren () { return _children.filter(function (child) { return !child.useRightYAxis(); }); } function rightYAxisChildren () { return _children.filter(function (child) { return child.useRightYAxis(); }); } function getYAxisMin (charts) { return charts.map(function (c) { return c.yAxisMin(); }); } delete _chart.yAxisMin; function yAxisMin () { return d3.min(getYAxisMin(leftYAxisChildren())); } function rightYAxisMin () { return d3.min(getYAxisMin(rightYAxisChildren())); } function getYAxisMax (charts) { return charts.map(function (c) { return c.yAxisMax(); }); } delete _chart.yAxisMax; function yAxisMax () { return dc.utils.add(d3.max(getYAxisMax(leftYAxisChildren())), _chart.yAxisPadding()); } function rightYAxisMax () { return dc.utils.add(d3.max(getYAxisMax(rightYAxisChildren())), _chart.yAxisPadding()); } function getAllXAxisMinFromChildCharts () { return _children.map(function (c) { return c.xAxisMin(); }); } dc.override(_chart, 'xAxisMin', function () { return dc.utils.subtract(d3.min(getAllXAxisMinFromChildCharts()), _chart.xAxisPadding()); }); function getAllXAxisMaxFromChildCharts () { return _children.map(function (c) { return c.xAxisMax(); }); } dc.override(_chart, 'xAxisMax', function () { return dc.utils.add(d3.max(getAllXAxisMaxFromChildCharts()), _chart.xAxisPadding()); }); _chart.legendables = function () { return _children.reduce(function (items, child) { if (_shareColors) { child.colors(_chart.colors()); } items.push.apply(items, child.legendables()); return items; }, []); }; _chart.legendHighlight = function (d) { for (var j = 0; j < _children.length; ++j) { var child = _children[j]; child.legendHighlight(d); } }; _chart.legendReset = function (d) { for (var j = 0; j < _children.length; ++j) { var child = _children[j]; child.legendReset(d); } }; _chart.legendToggle = function () { console.log('composite should not be getting legendToggle itself'); }; /** * Set or get the right y axis used by the composite chart. This function is most useful when y * axis customization is required. The y axis in dc.js is an instance of a [d3 axis * object](https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#axis) therefore it supports any valid * d3 axis manipulation. * * **Caution**: The y axis is usually generated internally by dc; resetting it may cause * unexpected results. * @method rightYAxis * @memberof dc.compositeChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#axis d3.svg.axis} * @example * // customize y axis tick format * chart.rightYAxis().tickFormat(function (v) {return v + '%';}); * // customize y axis tick values * chart.rightYAxis().tickValues([0, 100, 200, 300]); * @param {d3.svg.axis} [rightYAxis] * @returns {d3.svg.axis|dc.compositeChart} */ _chart.rightYAxis = function (rightYAxis) { if (!arguments.length) { return _rightYAxis; } _rightYAxis = rightYAxis; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * A series chart is a chart that shows multiple series of data overlaid on one chart, where the * series is specified in the data. It is a specialization of Composite Chart and inherits all * composite features other than recomposing the chart. * * Examples: * - {@link http://dc-js.github.io/dc.js/examples/series.html Series Chart} * @class seriesChart * @memberof dc * @mixes dc.compositeChart * @example * // create a series chart under #chart-container1 element using the default global chart group * var seriesChart1 = dc.seriesChart("#chart-container1"); * // create a series chart under #chart-container2 element using chart group A * var seriesChart2 = dc.seriesChart("#chart-container2", "chartGroupA"); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.seriesChart} */ dc.seriesChart = function (parent, chartGroup) { var _chart = dc.compositeChart(parent, chartGroup); function keySort (a, b) { return d3.ascending(_chart.keyAccessor()(a), _chart.keyAccessor()(b)); } var _charts = {}; var _chartFunction = dc.lineChart; var _seriesAccessor; var _seriesSort = d3.ascending; var _valueSort = keySort; _chart._mandatoryAttributes().push('seriesAccessor', 'chart'); _chart.shareColors(true); _chart._preprocessData = function () { var keep = []; var childrenChanged; var nester = d3.nest().key(_seriesAccessor); if (_seriesSort) { nester.sortKeys(_seriesSort); } if (_valueSort) { nester.sortValues(_valueSort); } var nesting = nester.entries(_chart.data()); var children = nesting.map(function (sub, i) { var subChart = _charts[sub.key] || _chartFunction.call(_chart, _chart, chartGroup, sub.key, i); if (!_charts[sub.key]) { childrenChanged = true; } _charts[sub.key] = subChart; keep.push(sub.key); return subChart .dimension(_chart.dimension()) .group({all: d3.functor(sub.values)}, sub.key) .keyAccessor(_chart.keyAccessor()) .valueAccessor(_chart.valueAccessor()) .brushOn(_chart.brushOn()); }); // this works around the fact compositeChart doesn't really // have a removal interface Object.keys(_charts) .filter(function (c) {return keep.indexOf(c) === -1;}) .forEach(function (c) { clearChart(c); childrenChanged = true; }); _chart._compose(children); if (childrenChanged && _chart.legend()) { _chart.legend().render(); } }; function clearChart (c) { if (_charts[c].g()) { _charts[c].g().remove(); } delete _charts[c]; } function resetChildren () { Object.keys(_charts).map(clearChart); _charts = {}; } /** * Get or set the chart function, which generates the child charts. * @method chart * @memberof dc.seriesChart * @instance * @example * // put interpolation on the line charts used for the series * chart.chart(function(c) { return dc.lineChart(c).interpolate('basis'); }) * // do a scatter series chart * chart.chart(dc.scatterPlot) * @param {Function} [chartFunction=dc.lineChart] * @returns {Function|dc.seriesChart} */ _chart.chart = function (chartFunction) { if (!arguments.length) { return _chartFunction; } _chartFunction = chartFunction; resetChildren(); return _chart; }; /** * **mandatory** * * Get or set accessor function for the displayed series. Given a datum, this function * should return the series that datum belongs to. * @method seriesAccessor * @memberof dc.seriesChart * @instance * @example * // simple series accessor * chart.seriesAccessor(function(d) { return "Expt: " + d.key[0]; }) * @param {Function} [accessor] * @returns {Function|dc.seriesChart} */ _chart.seriesAccessor = function (accessor) { if (!arguments.length) { return _seriesAccessor; } _seriesAccessor = accessor; resetChildren(); return _chart; }; /** * Get or set a function to sort the list of series by, given series values. * @method seriesSort * @memberof dc.seriesChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_ascending d3.ascending} * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_descending d3.descending} * @example * chart.seriesSort(d3.descending); * @param {Function} [sortFunction=d3.ascending] * @returns {Function|dc.seriesChart} */ _chart.seriesSort = function (sortFunction) { if (!arguments.length) { return _seriesSort; } _seriesSort = sortFunction; resetChildren(); return _chart; }; /** * Get or set a function to sort each series values by. By default this is the key accessor which, * for example, will ensure a lineChart series connects its points in increasing key/x order, * rather than haphazardly. * @method valueSort * @memberof dc.seriesChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_ascending d3.ascending} * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Arrays.md#d3_descending d3.descending} * @example * // Default value sort * _chart.valueSort(function keySort (a, b) { * return d3.ascending(_chart.keyAccessor()(a), _chart.keyAccessor()(b)); * }); * @param {Function} [sortFunction] * @returns {Function|dc.seriesChart} */ _chart.valueSort = function (sortFunction) { if (!arguments.length) { return _valueSort; } _valueSort = sortFunction; resetChildren(); return _chart; }; // make compose private _chart._compose = _chart.compose; delete _chart.compose; return _chart; }; /** * The geo choropleth chart is designed as an easy way to create a crossfilter driven choropleth map * from GeoJson data. This chart implementation was inspired by * {@link http://bl.ocks.org/4060606 the great d3 choropleth example}. * * Examples: * - {@link http://dc-js.github.com/dc.js/vc/index.html US Venture Capital Landscape 2011} * @class geoChoroplethChart * @memberof dc * @mixes dc.colorMixin * @mixes dc.baseMixin * @example * // create a choropleth chart under '#us-chart' element using the default global chart group * var chart1 = dc.geoChoroplethChart('#us-chart'); * // create a choropleth chart under '#us-chart2' element using chart group A * var chart2 = dc.compositeChart('#us-chart2', 'chartGroupA'); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.geoChoroplethChart} */ dc.geoChoroplethChart = function (parent, chartGroup) { var _chart = dc.colorMixin(dc.baseMixin({})); _chart.colorAccessor(function (d) { return d || 0; }); var _geoPath = d3.geo.path(); var _projectionFlag; var _geoJsons = []; _chart._doRender = function () { _chart.resetSvg(); for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { var states = _chart.svg().append('g') .attr('class', 'layer' + layerIndex); var regionG = states.selectAll('g.' + geoJson(layerIndex).name) .data(geoJson(layerIndex).data) .enter() .append('g') .attr('class', geoJson(layerIndex).name); regionG .append('path') .attr('fill', 'white') .attr('d', _geoPath); regionG.append('title'); plotData(layerIndex); } _projectionFlag = false; }; function plotData (layerIndex) { var data = generateLayeredData(); if (isDataLayer(layerIndex)) { var regionG = renderRegionG(layerIndex); renderPaths(regionG, layerIndex, data); renderTitle(regionG, layerIndex, data); } } function generateLayeredData () { var data = {}; var groupAll = _chart.data(); for (var i = 0; i < groupAll.length; ++i) { data[_chart.keyAccessor()(groupAll[i])] = _chart.valueAccessor()(groupAll[i]); } return data; } function isDataLayer (layerIndex) { return geoJson(layerIndex).keyAccessor; } function renderRegionG (layerIndex) { var regionG = _chart.svg() .selectAll(layerSelector(layerIndex)) .classed('selected', function (d) { return isSelected(layerIndex, d); }) .classed('deselected', function (d) { return isDeselected(layerIndex, d); }) .attr('class', function (d) { var layerNameClass = geoJson(layerIndex).name; var regionClass = dc.utils.nameToId(geoJson(layerIndex).keyAccessor(d)); var baseClasses = layerNameClass + ' ' + regionClass; if (isSelected(layerIndex, d)) { baseClasses += ' selected'; } if (isDeselected(layerIndex, d)) { baseClasses += ' deselected'; } return baseClasses; }); return regionG; } function layerSelector (layerIndex) { return 'g.layer' + layerIndex + ' g.' + geoJson(layerIndex).name; } function isSelected (layerIndex, d) { return _chart.hasFilter() && _chart.hasFilter(getKey(layerIndex, d)); } function isDeselected (layerIndex, d) { return _chart.hasFilter() && !_chart.hasFilter(getKey(layerIndex, d)); } function getKey (layerIndex, d) { return geoJson(layerIndex).keyAccessor(d); } function geoJson (index) { return _geoJsons[index]; } function renderPaths (regionG, layerIndex, data) { var paths = regionG .select('path') .attr('fill', function () { var currentFill = d3.select(this).attr('fill'); if (currentFill) { return currentFill; } return 'none'; }) .on('click', function (d) { return _chart.onClick(d, layerIndex); }); dc.transition(paths, _chart.transitionDuration(), _chart.transitionDelay()).attr('fill', function (d, i) { return _chart.getColor(data[geoJson(layerIndex).keyAccessor(d)], i); }); } _chart.onClick = function (d, layerIndex) { var selectedRegion = geoJson(layerIndex).keyAccessor(d); dc.events.trigger(function () { _chart.filter(selectedRegion); _chart.redrawGroup(); }); }; function renderTitle (regionG, layerIndex, data) { if (_chart.renderTitle()) { regionG.selectAll('title').text(function (d) { var key = getKey(layerIndex, d); var value = data[key]; return _chart.title()({key: key, value: value}); }); } } _chart._doRedraw = function () { for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { plotData(layerIndex); if (_projectionFlag) { _chart.svg().selectAll('g.' + geoJson(layerIndex).name + ' path').attr('d', _geoPath); } } _projectionFlag = false; }; /** * **mandatory** * * Use this function to insert a new GeoJson map layer. This function can be invoked multiple times * if you have multiple GeoJson data layers to render on top of each other. If you overlay multiple * layers with the same name the new overlay will override the existing one. * @method overlayGeoJson * @memberof dc.geoChoroplethChart * @instance * @see {@link http://geojson.org/ GeoJSON} * @see {@link https://github.com/topojson/topojson/wiki TopoJSON} * @see {@link https://github.com/topojson/topojson-1.x-api-reference/blob/master/API-Reference.md#wiki-feature topojson.feature} * @example * // insert a layer for rendering US states * chart.overlayGeoJson(statesJson.features, 'state', function(d) { * return d.properties.name; * }); * @param {geoJson} json - a geojson feed * @param {String} name - name of the layer * @param {Function} keyAccessor - accessor function used to extract 'key' from the GeoJson data. The key extracted by * this function should match the keys returned by the crossfilter groups. * @returns {dc.geoChoroplethChart} */ _chart.overlayGeoJson = function (json, name, keyAccessor) { for (var i = 0; i < _geoJsons.length; ++i) { if (_geoJsons[i].name === name) { _geoJsons[i].data = json; _geoJsons[i].keyAccessor = keyAccessor; return _chart; } } _geoJsons.push({name: name, data: json, keyAccessor: keyAccessor}); return _chart; }; /** * Set custom geo projection function. See the available * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Geo-Projections.md d3 geo projection functions}. * @method projection * @memberof dc.geoChoroplethChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Geo-Projections.md d3.geo.projection} * @see {@link https://github.com/d3/d3-geo-projection Extended d3.geo.projection} * @param {d3.projection} [projection=d3.geo.albersUsa()] * @returns {dc.geoChoroplethChart} */ _chart.projection = function (projection) { _geoPath.projection(projection); _projectionFlag = true; return _chart; }; /** * Returns all GeoJson layers currently registered with this chart. The returned array is a * reference to this chart's internal data structure, so any modification to this array will also * modify this chart's internal registration. * @method geoJsons * @memberof dc.geoChoroplethChart * @instance * @returns {Array<{name:String, data: Object, accessor: Function}>} */ _chart.geoJsons = function () { return _geoJsons; }; /** * Returns the {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Geo-Paths.md#path d3.geo.path} object used to * render the projection and features. Can be useful for figuring out the bounding box of the * feature set and thus a way to calculate scale and translation for the projection. * @method geoPath * @memberof dc.geoChoroplethChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Geo-Paths.md#path d3.geo.path} * @returns {d3.geo.path} */ _chart.geoPath = function () { return _geoPath; }; /** * Remove a GeoJson layer from this chart by name * @method removeGeoJson * @memberof dc.geoChoroplethChart * @instance * @param {String} name * @returns {dc.geoChoroplethChart} */ _chart.removeGeoJson = function (name) { var geoJsons = []; for (var i = 0; i < _geoJsons.length; ++i) { var layer = _geoJsons[i]; if (layer.name !== name) { geoJsons.push(layer); } } _geoJsons = geoJsons; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * The bubble overlay chart is quite different from the typical bubble chart. With the bubble overlay * chart you can arbitrarily place bubbles on an existing svg or bitmap image, thus changing the * typical x and y positioning while retaining the capability to visualize data using bubble radius * and coloring. * * Examples: * - {@link http://dc-js.github.com/dc.js/crime/index.html Canadian City Crime Stats} * @class bubbleOverlay * @memberof dc * @mixes dc.bubbleMixin * @mixes dc.baseMixin * @example * // create a bubble overlay chart on top of the '#chart-container1 svg' element using the default global chart group * var bubbleChart1 = dc.bubbleOverlayChart('#chart-container1').svg(d3.select('#chart-container1 svg')); * // create a bubble overlay chart on top of the '#chart-container2 svg' element using chart group A * var bubbleChart2 = dc.compositeChart('#chart-container2', 'chartGroupA').svg(d3.select('#chart-container2 svg')); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.bubbleOverlay} */ dc.bubbleOverlay = function (parent, chartGroup) { var BUBBLE_OVERLAY_CLASS = 'bubble-overlay'; var BUBBLE_NODE_CLASS = 'node'; var BUBBLE_CLASS = 'bubble'; /** * **mandatory** * * Set the underlying svg image element. Unlike other dc charts this chart will not generate a svg * element; therefore the bubble overlay chart will not work if this function is not invoked. If the * underlying image is a bitmap, then an empty svg will need to be created on top of the image. * @method svg * @memberof dc.bubbleOverlay * @instance * @example * // set up underlying svg element * chart.svg(d3.select('#chart svg')); * @param {SVGElement|d3.selection} [imageElement] * @returns {dc.bubbleOverlay} */ var _chart = dc.bubbleMixin(dc.baseMixin({})); var _g; var _points = []; _chart.transitionDuration(750); _chart.transitionDelay(0); _chart.radiusValueAccessor(function (d) { return d.value; }); /** * **mandatory** * * Set up a data point on the overlay. The name of a data point should match a specific 'key' among * data groups generated using keyAccessor. If a match is found (point name <-> data group key) * then a bubble will be generated at the position specified by the function. x and y * value specified here are relative to the underlying svg. * @method point * @memberof dc.bubbleOverlay * @instance * @param {String} name * @param {Number} x * @param {Number} y * @returns {dc.bubbleOverlay} */ _chart.point = function (name, x, y) { _points.push({name: name, x: x, y: y}); return _chart; }; _chart._doRender = function () { _g = initOverlayG(); _chart.r().range([_chart.MIN_RADIUS, _chart.width() * _chart.maxBubbleRelativeSize()]); initializeBubbles(); _chart.fadeDeselectedArea(); return _chart; }; function initOverlayG () { _g = _chart.select('g.' + BUBBLE_OVERLAY_CLASS); if (_g.empty()) { _g = _chart.svg().append('g').attr('class', BUBBLE_OVERLAY_CLASS); } return _g; } function initializeBubbles () { var data = mapData(); _points.forEach(function (point) { var nodeG = getNodeG(point, data); var circle = nodeG.select('circle.' + BUBBLE_CLASS); if (circle.empty()) { circle = nodeG.append('circle') .attr('class', BUBBLE_CLASS) .attr('r', 0) .attr('fill', _chart.getColor) .on('click', _chart.onClick); } dc.transition(circle, _chart.transitionDuration(), _chart.transitionDelay()) .attr('r', function (d) { return _chart.bubbleR(d); }); _chart._doRenderLabel(nodeG); _chart._doRenderTitles(nodeG); }); } function mapData () { var data = {}; _chart.data().forEach(function (datum) { data[_chart.keyAccessor()(datum)] = datum; }); return data; } function getNodeG (point, data) { var bubbleNodeClass = BUBBLE_NODE_CLASS + ' ' + dc.utils.nameToId(point.name); var nodeG = _g.select('g.' + dc.utils.nameToId(point.name)); if (nodeG.empty()) { nodeG = _g.append('g') .attr('class', bubbleNodeClass) .attr('transform', 'translate(' + point.x + ',' + point.y + ')'); } nodeG.datum(data[point.name]); return nodeG; } _chart._doRedraw = function () { updateBubbles(); _chart.fadeDeselectedArea(); return _chart; }; function updateBubbles () { var data = mapData(); _points.forEach(function (point) { var nodeG = getNodeG(point, data); var circle = nodeG.select('circle.' + BUBBLE_CLASS); dc.transition(circle, _chart.transitionDuration(), _chart.transitionDelay()) .attr('r', function (d) { return _chart.bubbleR(d); }) .attr('fill', _chart.getColor); _chart.doUpdateLabels(nodeG); _chart.doUpdateTitles(nodeG); }); } _chart.debug = function (flag) { if (flag) { var debugG = _chart.select('g.' + dc.constants.DEBUG_GROUP_CLASS); if (debugG.empty()) { debugG = _chart.svg() .append('g') .attr('class', dc.constants.DEBUG_GROUP_CLASS); } var debugText = debugG.append('text') .attr('x', 10) .attr('y', 20); debugG .append('rect') .attr('width', _chart.width()) .attr('height', _chart.height()) .on('mousemove', function () { var position = d3.mouse(debugG.node()); var msg = position[0] + ', ' + position[1]; debugText.text(msg); }); } else { _chart.selectAll('.debug').remove(); } return _chart; }; _chart.anchor(parent, chartGroup); return _chart; }; /** * Concrete row chart implementation. * * Examples: * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index} * @class rowChart * @memberof dc * @mixes dc.capMixin * @mixes dc.marginMixin * @mixes dc.colorMixin * @mixes dc.baseMixin * @example * // create a row chart under #chart-container1 element using the default global chart group * var chart1 = dc.rowChart('#chart-container1'); * // create a row chart under #chart-container2 element using chart group A * var chart2 = dc.rowChart('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.rowChart} */ dc.rowChart = function (parent, chartGroup) { var _g; var _labelOffsetX = 10; var _labelOffsetY = 15; var _hasLabelOffsetY = false; var _dyOffset = '0.35em'; // this helps center labels https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#svg_text var _titleLabelOffsetX = 2; var _gap = 5; var _fixedBarHeight = false; var _rowCssClass = 'row'; var _titleRowCssClass = 'titlerow'; var _renderTitleLabel = false; var _chart = dc.capMixin(dc.marginMixin(dc.colorMixin(dc.baseMixin({})))); var _x; var _elasticX; var _xAxis = d3.svg.axis().orient('bottom'); var _rowData; _chart.rowsCap = _chart.cap; function calculateAxisScale () { if (!_x || _elasticX) { var extent = d3.extent(_rowData, _chart.cappedValueAccessor); if (extent[0] > 0) { extent[0] = 0; } if (extent[1] < 0) { extent[1] = 0; } _x = d3.scale.linear().domain(extent) .range([0, _chart.effectiveWidth()]); } _xAxis.scale(_x); } function drawAxis () { var axisG = _g.select('g.axis'); calculateAxisScale(); if (axisG.empty()) { axisG = _g.append('g').attr('class', 'axis'); } axisG.attr('transform', 'translate(0, ' + _chart.effectiveHeight() + ')'); dc.transition(axisG, _chart.transitionDuration(), _chart.transitionDelay()) .call(_xAxis); } _chart._doRender = function () { _chart.resetSvg(); _g = _chart.svg() .append('g') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); drawChart(); return _chart; }; _chart.title(function (d) { return _chart.cappedKeyAccessor(d) + ': ' + _chart.cappedValueAccessor(d); }); _chart.label(_chart.cappedKeyAccessor); /** * Gets or sets the x scale. The x scale can be any d3 * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Quantitative-Scales.md quantitive scale}. * @method x * @memberof dc.rowChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Quantitative-Scales.md quantitive scale} * @param {d3.scale} [scale] * @returns {d3.scale|dc.rowChart} */ _chart.x = function (scale) { if (!arguments.length) { return _x; } _x = scale; return _chart; }; function drawGridLines () { _g.selectAll('g.tick') .select('line.grid-line') .remove(); _g.selectAll('g.tick') .append('line') .attr('class', 'grid-line') .attr('x1', 0) .attr('y1', 0) .attr('x2', 0) .attr('y2', function () { return -_chart.effectiveHeight(); }); } function drawChart () { _rowData = _chart.data(); drawAxis(); drawGridLines(); var rows = _g.selectAll('g.' + _rowCssClass) .data(_rowData); createElements(rows); removeElements(rows); updateElements(rows); } function createElements (rows) { var rowEnter = rows.enter() .append('g') .attr('class', function (d, i) { return _rowCssClass + ' _' + i; }); rowEnter.append('rect').attr('width', 0); createLabels(rowEnter); } function removeElements (rows) { rows.exit().remove(); } function rootValue () { var root = _x(0); return (root === -Infinity || root !== root) ? _x(1) : root; } function updateElements (rows) { var n = _rowData.length; var height; if (!_fixedBarHeight) { height = (_chart.effectiveHeight() - (n + 1) * _gap) / n; } else { height = _fixedBarHeight; } // vertically align label in center unless they override the value via property setter if (!_hasLabelOffsetY) { _labelOffsetY = height / 2; } var rect = rows.attr('transform', function (d, i) { return 'translate(0,' + ((i + 1) * _gap + i * height) + ')'; }).select('rect') .attr('height', height) .attr('fill', _chart.getColor) .on('click', onClick) .classed('deselected', function (d) { return (_chart.hasFilter()) ? !isSelectedRow(d) : false; }) .classed('selected', function (d) { return (_chart.hasFilter()) ? isSelectedRow(d) : false; }); dc.transition(rect, _chart.transitionDuration(), _chart.transitionDelay()) .attr('width', function (d) { return Math.abs(rootValue() - _x(_chart.valueAccessor()(d))); }) .attr('transform', translateX); createTitles(rows); updateLabels(rows); } function createTitles (rows) { if (_chart.renderTitle()) { rows.select('title').remove(); rows.append('title').text(_chart.title()); } } function createLabels (rowEnter) { if (_chart.renderLabel()) { rowEnter.append('text') .on('click', onClick); } if (_chart.renderTitleLabel()) { rowEnter.append('text') .attr('class', _titleRowCssClass) .on('click', onClick); } } function updateLabels (rows) { if (_chart.renderLabel()) { var lab = rows.select('text') .attr('x', _labelOffsetX) .attr('y', _labelOffsetY) .attr('dy', _dyOffset) .on('click', onClick) .attr('class', function (d, i) { return _rowCssClass + ' _' + i; }) .text(function (d) { return _chart.label()(d); }); dc.transition(lab, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', translateX); } if (_chart.renderTitleLabel()) { var titlelab = rows.select('.' + _titleRowCssClass) .attr('x', _chart.effectiveWidth() - _titleLabelOffsetX) .attr('y', _labelOffsetY) .attr('dy', _dyOffset) .attr('text-anchor', 'end') .on('click', onClick) .attr('class', function (d, i) { return _titleRowCssClass + ' _' + i ; }) .text(function (d) { return _chart.title()(d); }); dc.transition(titlelab, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', translateX); } } /** * Turn on/off Title label rendering (values) using SVG style of text-anchor 'end'. * @method renderTitleLabel * @memberof dc.rowChart * @instance * @param {Boolean} [renderTitleLabel=false] * @returns {Boolean|dc.rowChart} */ _chart.renderTitleLabel = function (renderTitleLabel) { if (!arguments.length) { return _renderTitleLabel; } _renderTitleLabel = renderTitleLabel; return _chart; }; function onClick (d) { _chart.onClick(d); } function translateX (d) { var x = _x(_chart.cappedValueAccessor(d)), x0 = rootValue(), s = x > x0 ? x0 : x; return 'translate(' + s + ',0)'; } _chart._doRedraw = function () { drawChart(); return _chart; }; /** * Get the x axis for the row chart instance. Note: not settable for row charts. * See the {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#axis d3 axis object} * documention for more information. * @method xAxis * @memberof dc.rowChart * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#axis d3.svg.axis} * @example * // customize x axis tick format * chart.xAxis().tickFormat(function (v) {return v + '%';}); * // customize x axis tick values * chart.xAxis().tickValues([0, 100, 200, 300]); * @returns {d3.svg.axis} */ _chart.xAxis = function () { return _xAxis; }; /** * Get or set the fixed bar height. Default is [false] which will auto-scale bars. * For example, if you want to fix the height for a specific number of bars (useful in TopN charts) * you could fix height as follows (where count = total number of bars in your TopN and gap is * your vertical gap space). * @method fixedBarHeight * @memberof dc.rowChart * @instance * @example * chart.fixedBarHeight( chartheight - (count + 1) * gap / count); * @param {Boolean|Number} [fixedBarHeight=false] * @returns {Boolean|Number|dc.rowChart} */ _chart.fixedBarHeight = function (fixedBarHeight) { if (!arguments.length) { return _fixedBarHeight; } _fixedBarHeight = fixedBarHeight; return _chart; }; /** * Get or set the vertical gap space between rows on a particular row chart instance. * @method gap * @memberof dc.rowChart * @instance * @param {Number} [gap=5] * @returns {Number|dc.rowChart} */ _chart.gap = function (gap) { if (!arguments.length) { return _gap; } _gap = gap; return _chart; }; /** * Get or set the elasticity on x axis. If this attribute is set to true, then the x axis will rescle to auto-fit the * data range when filtered. * @method elasticX * @memberof dc.rowChart * @instance * @param {Boolean} [elasticX] * @returns {Boolean|dc.rowChart} */ _chart.elasticX = function (elasticX) { if (!arguments.length) { return _elasticX; } _elasticX = elasticX; return _chart; }; /** * Get or set the x offset (horizontal space to the top left corner of a row) for labels on a particular row chart. * @method labelOffsetX * @memberof dc.rowChart * @instance * @param {Number} [labelOffsetX=10] * @returns {Number|dc.rowChart} */ _chart.labelOffsetX = function (labelOffsetX) { if (!arguments.length) { return _labelOffsetX; } _labelOffsetX = labelOffsetX; return _chart; }; /** * Get or set the y offset (vertical space to the top left corner of a row) for labels on a particular row chart. * @method labelOffsetY * @memberof dc.rowChart * @instance * @param {Number} [labelOffsety=15] * @returns {Number|dc.rowChart} */ _chart.labelOffsetY = function (labelOffsety) { if (!arguments.length) { return _labelOffsetY; } _labelOffsetY = labelOffsety; _hasLabelOffsetY = true; return _chart; }; /** * Get of set the x offset (horizontal space between right edge of row and right edge or text. * @method titleLabelOffsetX * @memberof dc.rowChart * @instance * @param {Number} [titleLabelOffsetX=2] * @returns {Number|dc.rowChart} */ _chart.titleLabelOffsetX = function (titleLabelOffsetX) { if (!arguments.length) { return _titleLabelOffsetX; } _titleLabelOffsetX = titleLabelOffsetX; return _chart; }; function isSelectedRow (d) { return _chart.hasFilter(_chart.cappedKeyAccessor(d)); } return _chart.anchor(parent, chartGroup); }; /** * Legend is a attachable widget that can be added to other dc charts to render horizontal legend * labels. * * Examples: * - {@link http://dc-js.github.com/dc.js/ Nasdaq 100 Index} * - {@link http://dc-js.github.com/dc.js/crime/index.html Canadian City Crime Stats} * @class legend * @memberof dc * @example * chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) * @returns {dc.legend} */ dc.legend = function () { var LABEL_GAP = 2; var _legend = {}, _parent, _x = 0, _y = 0, _itemHeight = 12, _gap = 5, _horizontal = false, _legendWidth = 560, _itemWidth = 70, _autoItemWidth = false, _legendText = dc.pluck('name'), _maxItems; var _g; _legend.parent = function (p) { if (!arguments.length) { return _parent; } _parent = p; return _legend; }; _legend.render = function () { _parent.svg().select('g.dc-legend').remove(); _g = _parent.svg().append('g') .attr('class', 'dc-legend') .attr('transform', 'translate(' + _x + ',' + _y + ')'); var legendables = _parent.legendables(); if (_maxItems !== undefined) { legendables = legendables.slice(0, _maxItems); } var itemEnter = _g.selectAll('g.dc-legend-item') .data(legendables) .enter() .append('g') .attr('class', 'dc-legend-item') .on('mouseover', function (d) { _parent.legendHighlight(d); }) .on('mouseout', function (d) { _parent.legendReset(d); }) .on('click', function (d) { d.chart.legendToggle(d); }); _g.selectAll('g.dc-legend-item') .classed('fadeout', function (d) { return d.chart.isLegendableHidden(d); }); if (legendables.some(dc.pluck('dashstyle'))) { itemEnter .append('line') .attr('x1', 0) .attr('y1', _itemHeight / 2) .attr('x2', _itemHeight) .attr('y2', _itemHeight / 2) .attr('stroke-width', 2) .attr('stroke-dasharray', dc.pluck('dashstyle')) .attr('stroke', dc.pluck('color')); } else { itemEnter .append('rect') .attr('width', _itemHeight) .attr('height', _itemHeight) .attr('fill', function (d) {return d ? d.color : 'blue';}); } itemEnter.append('text') .text(_legendText) .attr('x', _itemHeight + LABEL_GAP) .attr('y', function () { return _itemHeight / 2 + (this.clientHeight ? this.clientHeight : 13) / 2 - 2; }); var _cumulativeLegendTextWidth = 0; var row = 0; itemEnter.attr('transform', function (d, i) { if (_horizontal) { var itemWidth = _autoItemWidth === true ? this.getBBox().width + _gap : _itemWidth; if ((_cumulativeLegendTextWidth + itemWidth) > _legendWidth && _cumulativeLegendTextWidth > 0) { ++row; _cumulativeLegendTextWidth = 0; } var translateBy = 'translate(' + _cumulativeLegendTextWidth + ',' + row * legendItemHeight() + ')'; _cumulativeLegendTextWidth += itemWidth; return translateBy; } else { return 'translate(0,' + i * legendItemHeight() + ')'; } }); }; function legendItemHeight () { return _gap + _itemHeight; } /** * Set or get x coordinate for legend widget. * @method x * @memberof dc.legend * @instance * @param {Number} [x=0] * @returns {Number|dc.legend} */ _legend.x = function (x) { if (!arguments.length) { return _x; } _x = x; return _legend; }; /** * Set or get y coordinate for legend widget. * @method y * @memberof dc.legend * @instance * @param {Number} [y=0] * @returns {Number|dc.legend} */ _legend.y = function (y) { if (!arguments.length) { return _y; } _y = y; return _legend; }; /** * Set or get gap between legend items. * @method gap * @memberof dc.legend * @instance * @param {Number} [gap=5] * @returns {Number|dc.legend} */ _legend.gap = function (gap) { if (!arguments.length) { return _gap; } _gap = gap; return _legend; }; /** * Set or get legend item height. * @method itemHeight * @memberof dc.legend * @instance * @param {Number} [itemHeight=12] * @returns {Number|dc.legend} */ _legend.itemHeight = function (itemHeight) { if (!arguments.length) { return _itemHeight; } _itemHeight = itemHeight; return _legend; }; /** * Position legend horizontally instead of vertically. * @method horizontal * @memberof dc.legend * @instance * @param {Boolean} [horizontal=false] * @returns {Boolean|dc.legend} */ _legend.horizontal = function (horizontal) { if (!arguments.length) { return _horizontal; } _horizontal = horizontal; return _legend; }; /** * Maximum width for horizontal legend. * @method legendWidth * @memberof dc.legend * @instance * @param {Number} [legendWidth=500] * @returns {Number|dc.legend} */ _legend.legendWidth = function (legendWidth) { if (!arguments.length) { return _legendWidth; } _legendWidth = legendWidth; return _legend; }; /** * Legend item width for horizontal legend. * @method itemWidth * @memberof dc.legend * @instance * @param {Number} [itemWidth=70] * @returns {Number|dc.legend} */ _legend.itemWidth = function (itemWidth) { if (!arguments.length) { return _itemWidth; } _itemWidth = itemWidth; return _legend; }; /** * Turn automatic width for legend items on or off. If true, {@link dc.legend#itemWidth itemWidth} is ignored. * This setting takes into account the {@link dc.legend#gap gap}. * @method autoItemWidth * @memberof dc.legend * @instance * @param {Boolean} [autoItemWidth=false] * @returns {Boolean|dc.legend} */ _legend.autoItemWidth = function (autoItemWidth) { if (!arguments.length) { return _autoItemWidth; } _autoItemWidth = autoItemWidth; return _legend; }; /** * Set or get the legend text function. The legend widget uses this function to render the legend * text for each item. If no function is specified the legend widget will display the names * associated with each group. * @method legendText * @memberof dc.legend * @instance * @param {Function} [legendText] * @returns {Function|dc.legend} * @example * // default legendText * legend.legendText(dc.pluck('name')) * * // create numbered legend items * chart.legend(dc.legend().legendText(function(d, i) { return i + '. ' + d.name; })) * * // create legend displaying group counts * chart.legend(dc.legend().legendText(function(d) { return d.name + ': ' d.data; })) **/ _legend.legendText = function (legendText) { if (!arguments.length) { return _legendText; } _legendText = legendText; return _legend; }; /** * Maximum number of legend items to display * @method maxItems * @memberof dc.legend * @instance * @param {Number} [maxItems] * @return {dc.legend} */ _legend.maxItems = function (maxItems) { if (!arguments.length) { return _maxItems; } _maxItems = dc.utils.isNumber(maxItems) ? maxItems : undefined; return _legend; }; return _legend; }; /** * A scatter plot chart * * Examples: * - {@link http://dc-js.github.io/dc.js/examples/scatter.html Scatter Chart} * - {@link http://dc-js.github.io/dc.js/examples/multi-scatter.html Multi-Scatter Chart} * @class scatterPlot * @memberof dc * @mixes dc.coordinateGridMixin * @example * // create a scatter plot under #chart-container1 element using the default global chart group * var chart1 = dc.scatterPlot('#chart-container1'); * // create a scatter plot under #chart-container2 element using chart group A * var chart2 = dc.scatterPlot('#chart-container2', 'chartGroupA'); * // create a sub-chart under a composite parent chart * var chart3 = dc.scatterPlot(compositeChart); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.scatterPlot} */ dc.scatterPlot = function (parent, chartGroup) { var _chart = dc.coordinateGridMixin({}); var _symbol = d3.svg.symbol(); var _existenceAccessor = function (d) { return d.value; }; var originalKeyAccessor = _chart.keyAccessor(); _chart.keyAccessor(function (d) { return originalKeyAccessor(d)[0]; }); _chart.valueAccessor(function (d) { return originalKeyAccessor(d)[1]; }); _chart.colorAccessor(function () { return _chart._groupName; }); _chart.title(function (d) { // this basically just counteracts the setting of its own key/value accessors // see https://github.com/dc-js/dc.js/issues/702 return _chart.keyAccessor()(d) + ',' + _chart.valueAccessor()(d) + ': ' + _chart.existenceAccessor()(d); }); var _locator = function (d) { return 'translate(' + _chart.x()(_chart.keyAccessor()(d)) + ',' + _chart.y()(_chart.valueAccessor()(d)) + ')'; }; var _highlightedSize = 7; var _symbolSize = 5; var _excludedSize = 3; var _excludedColor = null; var _excludedOpacity = 1.0; var _emptySize = 0; var _emptyOpacity = 0; var _nonemptyOpacity = 1; var _emptyColor = null; var _filtered = []; _symbol.size(function (d, i) { if (!_existenceAccessor(d)) { return Math.pow(_emptySize, 2); } else if (_filtered[i]) { return Math.pow(_symbolSize, 2); } else { return Math.pow(_excludedSize, 2); } }); dc.override(_chart, '_filter', function (filter) { if (!arguments.length) { return _chart.__filter(); } return _chart.__filter(dc.filters.RangedTwoDimensionalFilter(filter)); }); _chart.plotData = function () { var symbols = _chart.chartBodyG().selectAll('path.symbol') .data(_chart.data()); symbols .enter() .append('path') .attr('class', 'symbol') .attr('opacity', 0) .attr('fill', _chart.getColor) .attr('transform', _locator); symbols.call(renderTitles, _chart.data()); symbols.each(function (d, i) { _filtered[i] = !_chart.filter() || _chart.filter().isFiltered([d.key[0], d.key[1]]); }); dc.transition(symbols, _chart.transitionDuration(), _chart.transitionDelay()) .attr('opacity', function (d, i) { if (!_existenceAccessor(d)) { return _emptyOpacity; } else if (_filtered[i]) { return _nonemptyOpacity; } else { return _chart.excludedOpacity(); } }) .attr('fill', function (d, i) { if (_emptyColor && !_existenceAccessor(d)) { return _emptyColor; } else if (_chart.excludedColor() && !_filtered[i]) { return _chart.excludedColor(); } else { return _chart.getColor(d); } }) .attr('transform', _locator) .attr('d', _symbol); dc.transition(symbols.exit(), _chart.transitionDuration(), _chart.transitionDelay()) .attr('opacity', 0).remove(); }; function renderTitles (symbol, d) { if (_chart.renderTitle()) { symbol.selectAll('title').remove(); symbol.append('title').text(function (d) { return _chart.title()(d); }); } } /** * Get or set the existence accessor. If a point exists, it is drawn with * {@link dc.scatterPlot#symbolSize symbolSize} radius and * opacity 1; if it does not exist, it is drawn with * {@link dc.scatterPlot#emptySize emptySize} radius and opacity 0. By default, * the existence accessor checks if the reduced value is truthy. * @method existenceAccessor * @memberof dc.scatterPlot * @instance * @see {@link dc.scatterPlot#symbolSize symbolSize} * @see {@link dc.scatterPlot#emptySize emptySize} * @example * // default accessor * chart.existenceAccessor(function (d) { return d.value; }); * @param {Function} [accessor] * @returns {Function|dc.scatterPlot} */ _chart.existenceAccessor = function (accessor) { if (!arguments.length) { return _existenceAccessor; } _existenceAccessor = accessor; return this; }; /** * Get or set the symbol type used for each point. By default the symbol is a circle. * Type can be a constant or an accessor. * @method symbol * @memberof dc.scatterPlot * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#symbol_type d3.svg.symbol.type} * @example * // Circle type * chart.symbol('circle'); * // Square type * chart.symbol('square'); * @param {String|Function} [type='circle'] * @returns {String|Function|dc.scatterPlot} */ _chart.symbol = function (type) { if (!arguments.length) { return _symbol.type(); } _symbol.type(type); return _chart; }; /** * Set or get radius for symbols. * @method symbolSize * @memberof dc.scatterPlot * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#symbol_size d3.svg.symbol.size} * @param {Number} [symbolSize=3] * @returns {Number|dc.scatterPlot} */ _chart.symbolSize = function (symbolSize) { if (!arguments.length) { return _symbolSize; } _symbolSize = symbolSize; return _chart; }; /** * Set or get radius for highlighted symbols. * @method highlightedSize * @memberof dc.scatterPlot * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#symbol_size d3.svg.symbol.size} * @param {Number} [highlightedSize=5] * @returns {Number|dc.scatterPlot} */ _chart.highlightedSize = function (highlightedSize) { if (!arguments.length) { return _highlightedSize; } _highlightedSize = highlightedSize; return _chart; }; /** * Set or get size for symbols excluded from this chart's filter. If null, no * special size is applied for symbols based on their filter status. * @method excludedSize * @memberof dc.scatterPlot * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#symbol_size d3.svg.symbol.size} * @param {Number} [excludedSize=null] * @returns {Number|dc.scatterPlot} */ _chart.excludedSize = function (excludedSize) { if (!arguments.length) { return _excludedSize; } _excludedSize = excludedSize; return _chart; }; /** * Set or get color for symbols excluded from this chart's filter. If null, no * special color is applied for symbols based on their filter status. * @method excludedColor * @memberof dc.scatterPlot * @instance * @param {Number} [excludedColor=null] * @returns {Number|dc.scatterPlot} */ _chart.excludedColor = function (excludedColor) { if (!arguments.length) { return _excludedColor; } _excludedColor = excludedColor; return _chart; }; /** * Set or get opacity for symbols excluded from this chart's filter. * @method excludedOpacity * @memberof dc.scatterPlot * @instance * @param {Number} [excludedOpacity=1.0] * @returns {Number|dc.scatterPlot} */ _chart.excludedOpacity = function (excludedOpacity) { if (!arguments.length) { return _excludedOpacity; } _excludedOpacity = excludedOpacity; return _chart; }; /** * Set or get radius for symbols when the group is empty. * @method emptySize * @memberof dc.scatterPlot * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Shapes.md#symbol_size d3.svg.symbol.size} * @param {Number} [emptySize=0] * @returns {Number|dc.scatterPlot} */ _chart.hiddenSize = _chart.emptySize = function (emptySize) { if (!arguments.length) { return _emptySize; } _emptySize = emptySize; return _chart; }; /** * Set or get color for symbols when the group is empty. If null, just use the * {@link dc.colorMixin#colors colorMixin.colors} color scale zero value. * @name emptyColor * @memberof dc.scatterPlot * @instance * @param {String} [emptyColor=null] * @return {String} * @return {dc.scatterPlot}/ */ _chart.emptyColor = function (emptyColor) { if (!arguments.length) { return _emptyColor; } _emptyColor = emptyColor; return _chart; }; /** * Set or get opacity for symbols when the group is empty. * @name emptyOpacity * @memberof dc.scatterPlot * @instance * @param {Number} [emptyOpacity=0] * @return {Number} * @return {dc.scatterPlot} */ _chart.emptyOpacity = function (emptyOpacity) { if (!arguments.length) { return _emptyOpacity; } _emptyOpacity = emptyOpacity; return _chart; }; /** * Set or get opacity for symbols when the group is not empty. * @name nonemptyOpacity * @memberof dc.scatterPlot * @instance * @param {Number} [nonemptyOpacity=1] * @return {Number} * @return {dc.scatterPlot} */ _chart.nonemptyOpacity = function (nonemptyOpacity) { if (!arguments.length) { return _emptyOpacity; } _nonemptyOpacity = nonemptyOpacity; return _chart; }; _chart.legendables = function () { return [{chart: _chart, name: _chart._groupName, color: _chart.getColor()}]; }; _chart.legendHighlight = function (d) { resizeSymbolsWhere(function (symbol) { return symbol.attr('fill') === d.color; }, _highlightedSize); _chart.selectAll('.chart-body path.symbol').filter(function () { return d3.select(this).attr('fill') !== d.color; }).classed('fadeout', true); }; _chart.legendReset = function (d) { resizeSymbolsWhere(function (symbol) { return symbol.attr('fill') === d.color; }, _symbolSize); _chart.selectAll('.chart-body path.symbol').filter(function () { return d3.select(this).attr('fill') !== d.color; }).classed('fadeout', false); }; function resizeSymbolsWhere (condition, size) { var symbols = _chart.selectAll('.chart-body path.symbol').filter(function () { return condition(d3.select(this)); }); var oldSize = _symbol.size(); _symbol.size(Math.pow(size, 2)); dc.transition(symbols, _chart.transitionDuration(), _chart.transitionDelay()).attr('d', _symbol); _symbol.size(oldSize); } _chart.setHandlePaths = function () { // no handle paths for poly-brushes }; _chart.extendBrush = function () { var extent = _chart.brush().extent(); if (_chart.round()) { extent[0] = extent[0].map(_chart.round()); extent[1] = extent[1].map(_chart.round()); _chart.g().select('.brush') .call(_chart.brush().extent(extent)); } return extent; }; _chart.brushIsEmpty = function (extent) { return _chart.brush().empty() || !extent || extent[0][0] >= extent[1][0] || extent[0][1] >= extent[1][1]; }; _chart._brushing = function () { var extent = _chart.extendBrush(); _chart.redrawBrush(_chart.g()); if (_chart.brushIsEmpty(extent)) { dc.events.trigger(function () { _chart.filter(null); _chart.redrawGroup(); }); } else { var ranged2DFilter = dc.filters.RangedTwoDimensionalFilter(extent); dc.events.trigger(function () { _chart.filter(null); _chart.filter(ranged2DFilter); _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); } }; _chart.setBrushY = function (gBrush) { gBrush.call(_chart.brush().y(_chart.y())); }; return _chart.anchor(parent, chartGroup); }; /** * A display of a single numeric value. * Unlike other charts, you do not need to set a dimension. Instead a group object must be provided and * a valueAccessor that returns a single value. * @class numberDisplay * @memberof dc * @mixes dc.baseMixin * @example * // create a number display under #chart-container1 element using the default global chart group * var display1 = dc.numberDisplay('#chart-container1'); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.numberDisplay} */ dc.numberDisplay = function (parent, chartGroup) { var SPAN_CLASS = 'number-display'; var _formatNumber = d3.format('.2s'); var _chart = dc.baseMixin({}); var _html = {one: '', some: '', none: ''}; var _lastValue; // dimension not required _chart._mandatoryAttributes(['group']); /** * Gets or sets an optional object specifying HTML templates to use depending on the number * displayed. The text `%number` will be replaced with the current value. * - one: HTML template to use if the number is 1 * - zero: HTML template to use if the number is 0 * - some: HTML template to use otherwise * @method html * @memberof dc.numberDisplay * @instance * @example * numberWidget.html({ * one:'%number record', * some:'%number records', * none:'no records'}) * @param {{one:String, some:String, none:String}} [html={one: '', some: '', none: ''}] * @returns {{one:String, some:String, none:String}|dc.numberDisplay} */ _chart.html = function (html) { if (!arguments.length) { return _html; } if (html.none) { _html.none = html.none;//if none available } else if (html.one) { _html.none = html.one;//if none not available use one } else if (html.some) { _html.none = html.some;//if none and one not available use some } if (html.one) { _html.one = html.one;//if one available } else if (html.some) { _html.one = html.some;//if one not available use some } if (html.some) { _html.some = html.some;//if some available } else if (html.one) { _html.some = html.one;//if some not available use one } return _chart; }; /** * Calculate and return the underlying value of the display. * @method value * @memberof dc.numberDisplay * @instance * @returns {Number} */ _chart.value = function () { return _chart.data(); }; _chart.data(function (group) { var valObj = group.value ? group.value() : group.top(1)[0]; return _chart.valueAccessor()(valObj); }); _chart.transitionDuration(250); // good default _chart.transitionDelay(0); _chart._doRender = function () { var newValue = _chart.value(), span = _chart.selectAll('.' + SPAN_CLASS); if (span.empty()) { span = span.data([0]) .enter() .append('span') .attr('class', SPAN_CLASS); } span.transition() .duration(_chart.transitionDuration()) .delay(_chart.transitionDelay()) .ease('quad-out-in') .tween('text', function () { // [XA] don't try and interpolate from Infinity, else this breaks. var interpStart = isFinite(_lastValue) ? _lastValue : 0; var interp = d3.interpolateNumber(interpStart || 0, newValue); _lastValue = newValue; return function (t) { var html = null, num = _chart.formatNumber()(interp(t)); if (newValue === 0 && (_html.none !== '')) { html = _html.none; } else if (newValue === 1 && (_html.one !== '')) { html = _html.one; } else if (_html.some !== '') { html = _html.some; } this.innerHTML = html ? html.replace('%number', num) : num; }; }); }; _chart._doRedraw = function () { return _chart._doRender(); }; /** * Get or set a function to format the value for the display. * @method formatNumber * @memberof dc.numberDisplay * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md d3.format} * @param {Function} [formatter=d3.format('.2s')] * @returns {Function|dc.numberDisplay} */ _chart.formatNumber = function (formatter) { if (!arguments.length) { return _formatNumber; } _formatNumber = formatter; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * A heat map is matrix that represents the values of two dimensions of data using colors. * @class heatMap * @memberof dc * @mixes dc.colorMixin * @mixes dc.marginMixin * @mixes dc.baseMixin * @example * // create a heat map under #chart-container1 element using the default global chart group * var heatMap1 = dc.heatMap('#chart-container1'); * // create a heat map under #chart-container2 element using chart group A * var heatMap2 = dc.heatMap('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.heatMap} */ dc.heatMap = function (parent, chartGroup) { var DEFAULT_BORDER_RADIUS = 6.75; var _chartBody; var _cols; var _rows; var _colOrdering = d3.ascending; var _rowOrdering = d3.ascending; var _colScale = d3.scale.ordinal(); var _rowScale = d3.scale.ordinal(); var _xBorderRadius = DEFAULT_BORDER_RADIUS; var _yBorderRadius = DEFAULT_BORDER_RADIUS; var _chart = dc.colorMixin(dc.marginMixin(dc.baseMixin({}))); _chart._mandatoryAttributes(['group']); _chart.title(_chart.colorAccessor()); var _colsLabel = function (d) { return d; }; var _rowsLabel = function (d) { return d; }; /** * Set or get the column label function. The chart class uses this function to render * column labels on the X axis. It is passed the column name. * @method colsLabel * @memberof dc.heatMap * @instance * @example * // the default label function just returns the name * chart.colsLabel(function(d) { return d; }); * @param {Function} [labelFunction=function(d) { return d; }] * @returns {Function|dc.heatMap} */ _chart.colsLabel = function (labelFunction) { if (!arguments.length) { return _colsLabel; } _colsLabel = labelFunction; return _chart; }; /** * Set or get the row label function. The chart class uses this function to render * row labels on the Y axis. It is passed the row name. * @method rowsLabel * @memberof dc.heatMap * @instance * @example * // the default label function just returns the name * chart.rowsLabel(function(d) { return d; }); * @param {Function} [labelFunction=function(d) { return d; }] * @returns {Function|dc.heatMap} */ _chart.rowsLabel = function (labelFunction) { if (!arguments.length) { return _rowsLabel; } _rowsLabel = labelFunction; return _chart; }; var _xAxisOnClick = function (d) { filterAxis(0, d); }; var _yAxisOnClick = function (d) { filterAxis(1, d); }; var _boxOnClick = function (d) { var filter = d.key; dc.events.trigger(function () { _chart.filter(filter); _chart.redrawGroup(); }); }; function filterAxis (axis, value) { var cellsOnAxis = _chart.selectAll('.box-group').filter(function (d) { return d.key[axis] === value; }); var unfilteredCellsOnAxis = cellsOnAxis.filter(function (d) { return !_chart.hasFilter(d.key); }); dc.events.trigger(function () { var selection = unfilteredCellsOnAxis.empty() ? cellsOnAxis : unfilteredCellsOnAxis; var filters = selection.data().map(function (kv) { return dc.filters.TwoDimensionalFilter(kv.key); }); _chart._filter([filters]); _chart.redrawGroup(); }); } dc.override(_chart, 'filter', function (filter) { if (!arguments.length) { return _chart._filter(); } return _chart._filter(dc.filters.TwoDimensionalFilter(filter)); }); /** * Gets or sets the values used to create the rows of the heatmap, as an array. By default, all * the values will be fetched from the data using the value accessor. * @method rows * @memberof dc.heatMap * @instance * @param {Array<String|Number>} [rows] * @returns {Array<String|Number>|dc.heatMap} */ _chart.rows = function (rows) { if (!arguments.length) { return _rows; } _rows = rows; return _chart; }; /** #### .rowOrdering([orderFunction]) Get or set an accessor to order the rows. Default is d3.ascending. */ _chart.rowOrdering = function (_) { if (!arguments.length) { return _rowOrdering; } _rowOrdering = _; return _chart; }; /** * Gets or sets the keys used to create the columns of the heatmap, as an array. By default, all * the values will be fetched from the data using the key accessor. * @method cols * @memberof dc.heatMap * @instance * @param {Array<String|Number>} [cols] * @returns {Array<String|Number>|dc.heatMap} */ _chart.cols = function (cols) { if (!arguments.length) { return _cols; } _cols = cols; return _chart; }; /** #### .colOrdering([orderFunction]) Get or set an accessor to order the cols. Default is ascending. */ _chart.colOrdering = function (_) { if (!arguments.length) { return _colOrdering; } _colOrdering = _; return _chart; }; _chart._doRender = function () { _chart.resetSvg(); _chartBody = _chart.svg() .append('g') .attr('class', 'heatmap') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); return _chart._doRedraw(); }; _chart._doRedraw = function () { var data = _chart.data(), rows = _chart.rows() || data.map(_chart.valueAccessor()), cols = _chart.cols() || data.map(_chart.keyAccessor()); if (_rowOrdering) { rows = rows.sort(_rowOrdering); } if (_colOrdering) { cols = cols.sort(_colOrdering); } rows = _rowScale.domain(rows); cols = _colScale.domain(cols); var rowCount = rows.domain().length, colCount = cols.domain().length, boxWidth = Math.floor(_chart.effectiveWidth() / colCount), boxHeight = Math.floor(_chart.effectiveHeight() / rowCount); cols.rangeRoundBands([0, _chart.effectiveWidth()]); rows.rangeRoundBands([_chart.effectiveHeight(), 0]); var boxes = _chartBody.selectAll('g.box-group').data(_chart.data(), function (d, i) { return _chart.keyAccessor()(d, i) + '\0' + _chart.valueAccessor()(d, i); }); var gEnter = boxes.enter().append('g') .attr('class', 'box-group'); gEnter.append('rect') .attr('class', 'heat-box') .attr('fill', 'white') .on('click', _chart.boxOnClick()); if (_chart.renderTitle()) { gEnter.append('title'); boxes.select('title').text(_chart.title()); } dc.transition(boxes.select('rect'), _chart.transitionDuration(), _chart.transitionDelay()) .attr('x', function (d, i) { return cols(_chart.keyAccessor()(d, i)); }) .attr('y', function (d, i) { return rows(_chart.valueAccessor()(d, i)); }) .attr('rx', _xBorderRadius) .attr('ry', _yBorderRadius) .attr('fill', _chart.getColor) .attr('width', boxWidth) .attr('height', boxHeight); boxes.exit().remove(); var gCols = _chartBody.select('g.cols'); if (gCols.empty()) { gCols = _chartBody.append('g').attr('class', 'cols axis'); } var gColsText = gCols.selectAll('text').data(cols.domain()); gColsText.enter().append('text') .attr('x', function (d) { return cols(d) + boxWidth / 2; }) .style('text-anchor', 'middle') .attr('y', _chart.effectiveHeight()) .attr('dy', 12) .on('click', _chart.xAxisOnClick()) .text(_chart.colsLabel()); dc.transition(gColsText, _chart.transitionDuration(), _chart.transitionDelay()) .text(_chart.colsLabel()) .attr('x', function (d) { return cols(d) + boxWidth / 2; }) .attr('y', _chart.effectiveHeight()); gColsText.exit().remove(); var gRows = _chartBody.select('g.rows'); if (gRows.empty()) { gRows = _chartBody.append('g').attr('class', 'rows axis'); } var gRowsText = gRows.selectAll('text').data(rows.domain()); gRowsText.enter().append('text') .attr('dy', 6) .style('text-anchor', 'end') .attr('x', 0) .attr('dx', -2) .on('click', _chart.yAxisOnClick()) .text(_chart.rowsLabel()); dc.transition(gRowsText, _chart.transitionDuration(), _chart.transitionDelay()) .text(_chart.rowsLabel()) .attr('y', function (d) { return rows(d) + boxHeight / 2; }); gRowsText.exit().remove(); if (_chart.hasFilter()) { _chart.selectAll('g.box-group').each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll('g.box-group').each(function () { _chart.resetHighlight(this); }); } return _chart; }; /** * Gets or sets the handler that fires when an individual cell is clicked in the heatmap. * By default, filtering of the cell will be toggled. * @method boxOnClick * @memberof dc.heatMap * @instance * @example * // default box on click handler * chart.boxOnClick(function (d) { * var filter = d.key; * dc.events.trigger(function () { * _chart.filter(filter); * _chart.redrawGroup(); * }); * }); * @param {Function} [handler] * @returns {Function|dc.heatMap} */ _chart.boxOnClick = function (handler) { if (!arguments.length) { return _boxOnClick; } _boxOnClick = handler; return _chart; }; /** * Gets or sets the handler that fires when a column tick is clicked in the x axis. * By default, if any cells in the column are unselected, the whole column will be selected, * otherwise the whole column will be unselected. * @method xAxisOnClick * @memberof dc.heatMap * @instance * @param {Function} [handler] * @returns {Function|dc.heatMap} */ _chart.xAxisOnClick = function (handler) { if (!arguments.length) { return _xAxisOnClick; } _xAxisOnClick = handler; return _chart; }; /** * Gets or sets the handler that fires when a row tick is clicked in the y axis. * By default, if any cells in the row are unselected, the whole row will be selected, * otherwise the whole row will be unselected. * @method yAxisOnClick * @memberof dc.heatMap * @instance * @param {Function} [handler] * @returns {Function|dc.heatMap} */ _chart.yAxisOnClick = function (handler) { if (!arguments.length) { return _yAxisOnClick; } _yAxisOnClick = handler; return _chart; }; /** * Gets or sets the X border radius. Set to 0 to get full rectangles. * @method xBorderRadius * @memberof dc.heatMap * @instance * @param {Number} [xBorderRadius=6.75] * @returns {Number|dc.heatMap} */ _chart.xBorderRadius = function (xBorderRadius) { if (!arguments.length) { return _xBorderRadius; } _xBorderRadius = xBorderRadius; return _chart; }; /** * Gets or sets the Y border radius. Set to 0 to get full rectangles. * @method yBorderRadius * @memberof dc.heatMap * @instance * @param {Number} [yBorderRadius=6.75] * @returns {Number|dc.heatMap} */ _chart.yBorderRadius = function (yBorderRadius) { if (!arguments.length) { return _yBorderRadius; } _yBorderRadius = yBorderRadius; return _chart; }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(d.key); }; return _chart.anchor(parent, chartGroup); }; // https://github.com/d3/d3-plugins/blob/master/box/box.js (function () { // Inspired by http://informationandvisualization.de/blog/box-plot d3.box = function () { var width = 1, height = 1, duration = 0, delay = 0, domain = null, value = Number, whiskers = boxWhiskers, quartiles = boxQuartiles, tickFormat = null; // For each small multiple… function box (g) { g.each(function (d, i) { d = d.map(value).sort(d3.ascending); var g = d3.select(this), n = d.length, min = d[0], max = d[n - 1]; // Compute quartiles. Must return exactly 3 elements. var quartileData = d.quartiles = quartiles(d); // Compute whiskers. Must return exactly 2 elements, or null. var whiskerIndices = whiskers && whiskers.call(this, d, i), whiskerData = whiskerIndices && whiskerIndices.map(function (i) { return d[i]; }); // Compute outliers. If no whiskers are specified, all data are 'outliers'. // We compute the outliers as indices, so that we can join across transitions! var outlierIndices = whiskerIndices ? d3.range(0, whiskerIndices[0]).concat(d3.range(whiskerIndices[1] + 1, n)) : d3.range(n); // Compute the new x-scale. var x1 = d3.scale.linear() .domain(domain && domain.call(this, d, i) || [min, max]) .range([height, 0]); // Retrieve the old x-scale, if this is an update. var x0 = this.__chart__ || d3.scale.linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. this.__chart__ = x1; // Note: the box, median, and box tick elements are fixed in number, // so we only have to handle enter and update. In contrast, the outliers // and other elements are variable, so we need to exit them! Variable // elements also fade in and out. // Update center line: the vertical line spanning the whiskers. var center = g.selectAll('line.center') .data(whiskerData ? [whiskerData] : []); center.enter().insert('line', 'rect') .attr('class', 'center') .attr('x1', width / 2) .attr('y1', function (d) { return x0(d[0]); }) .attr('x2', width / 2) .attr('y2', function (d) { return x0(d[1]); }) .style('opacity', 1e-6) .transition() .duration(duration) .delay(delay) .style('opacity', 1) .attr('y1', function (d) { return x1(d[0]); }) .attr('y2', function (d) { return x1(d[1]); }); center.transition() .duration(duration) .delay(delay) .style('opacity', 1) .attr('x1', width / 2) .attr('x2', width / 2) .attr('y1', function (d) { return x1(d[0]); }) .attr('y2', function (d) { return x1(d[1]); }); center.exit().transition() .duration(duration) .delay(delay) .style('opacity', 1e-6) .attr('y1', function (d) { return x1(d[0]); }) .attr('y2', function (d) { return x1(d[1]); }) .remove(); // Update innerquartile box. var box = g.selectAll('rect.box') .data([quartileData]); box.enter().append('rect') .attr('class', 'box') .attr('x', 0) .attr('y', function (d) { return x0(d[2]); }) .attr('width', width) .attr('height', function (d) { return x0(d[0]) - x0(d[2]); }) .transition() .duration(duration) .delay(delay) .attr('y', function (d) { return x1(d[2]); }) .attr('height', function (d) { return x1(d[0]) - x1(d[2]); }); box.transition() .duration(duration) .delay(delay) .attr('width', width) .attr('y', function (d) { return x1(d[2]); }) .attr('height', function (d) { return x1(d[0]) - x1(d[2]); }); // Update median line. var medianLine = g.selectAll('line.median') .data([quartileData[1]]); medianLine.enter().append('line') .attr('class', 'median') .attr('x1', 0) .attr('y1', x0) .attr('x2', width) .attr('y2', x0) .transition() .duration(duration) .delay(delay) .attr('y1', x1) .attr('y2', x1); medianLine.transition() .duration(duration) .delay(delay) .attr('x1', 0) .attr('x2', width) .attr('y1', x1) .attr('y2', x1); // Update whiskers. var whisker = g.selectAll('line.whisker') .data(whiskerData || []); whisker.enter().insert('line', 'circle, text') .attr('class', 'whisker') .attr('x1', 0) .attr('y1', x0) .attr('x2', width) .attr('y2', x0) .style('opacity', 1e-6) .transition() .duration(duration) .delay(delay) .attr('y1', x1) .attr('y2', x1) .style('opacity', 1); whisker.transition() .duration(duration) .delay(delay) .attr('x1', 0) .attr('x2', width) .attr('y1', x1) .attr('y2', x1) .style('opacity', 1); whisker.exit().transition() .duration(duration) .delay(delay) .attr('y1', x1) .attr('y2', x1) .style('opacity', 1e-6) .remove(); // Update outliers. var outlier = g.selectAll('circle.outlier') .data(outlierIndices, Number); outlier.enter().insert('circle', 'text') .attr('class', 'outlier') .attr('r', 5) .attr('cx', width / 2) .attr('cy', function (i) { return x0(d[i]); }) .style('opacity', 1e-6) .transition() .duration(duration) .delay(delay) .attr('cy', function (i) { return x1(d[i]); }) .style('opacity', 1); outlier.transition() .duration(duration) .delay(delay) .attr('cx', width / 2) .attr('cy', function (i) { return x1(d[i]); }) .style('opacity', 1); outlier.exit().transition() .duration(duration) .delay(delay) .attr('cy', function (i) { return x1(d[i]); }) .style('opacity', 1e-6) .remove(); // Compute the tick format. var format = tickFormat || x1.tickFormat(8); // Update box ticks. var boxTick = g.selectAll('text.box') .data(quartileData); boxTick.enter().append('text') .attr('class', 'box') .attr('dy', '.3em') .attr('dx', function (d, i) { return i & 1 ? 6 : -6; }) .attr('x', function (d, i) { return i & 1 ? width : 0; }) .attr('y', x0) .attr('text-anchor', function (d, i) { return i & 1 ? 'start' : 'end'; }) .text(format) .transition() .duration(duration) .delay(delay) .attr('y', x1); boxTick.transition() .duration(duration) .delay(delay) .text(format) .attr('x', function (d, i) { return i & 1 ? width : 0; }) .attr('y', x1); // Update whisker ticks. These are handled separately from the box // ticks because they may or may not exist, and we want don't want // to join box ticks pre-transition with whisker ticks post-. var whiskerTick = g.selectAll('text.whisker') .data(whiskerData || []); whiskerTick.enter().append('text') .attr('class', 'whisker') .attr('dy', '.3em') .attr('dx', 6) .attr('x', width) .attr('y', x0) .text(format) .style('opacity', 1e-6) .transition() .duration(duration) .delay(delay) .attr('y', x1) .style('opacity', 1); whiskerTick.transition() .duration(duration) .delay(delay) .text(format) .attr('x', width) .attr('y', x1) .style('opacity', 1); whiskerTick.exit().transition() .duration(duration) .delay(delay) .attr('y', x1) .style('opacity', 1e-6) .remove(); }); d3.timer.flush(); } box.width = function (x) { if (!arguments.length) { return width; } width = x; return box; }; box.height = function (x) { if (!arguments.length) { return height; } height = x; return box; }; box.tickFormat = function (x) { if (!arguments.length) { return tickFormat; } tickFormat = x; return box; }; box.duration = function (x) { if (!arguments.length) { return duration; } duration = x; return box; }; box.domain = function (x) { if (!arguments.length) { return domain; } domain = x === null ? x : d3.functor(x); return box; }; box.value = function (x) { if (!arguments.length) { return value; } value = x; return box; }; box.whiskers = function (x) { if (!arguments.length) { return whiskers; } whiskers = x; return box; }; box.quartiles = function (x) { if (!arguments.length) { return quartiles; } quartiles = x; return box; }; return box; }; function boxWhiskers (d) { return [0, d.length - 1]; } function boxQuartiles (d) { return [ d3.quantile(d, 0.25), d3.quantile(d, 0.5), d3.quantile(d, 0.75) ]; } })(); /** * A box plot is a chart that depicts numerical data via their quartile ranges. * * Examples: * - {@link http://dc-js.github.io/dc.js/examples/box-plot-time.html Box plot time example} * - {@link http://dc-js.github.io/dc.js/examples/box-plot.html Box plot example} * @class boxPlot * @memberof dc * @mixes dc.coordinateGridMixin * @example * // create a box plot under #chart-container1 element using the default global chart group * var boxPlot1 = dc.boxPlot('#chart-container1'); * // create a box plot under #chart-container2 element using chart group A * var boxPlot2 = dc.boxPlot('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection} parent - Any valid * {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#selecting-elements d3 single selector} specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {dc.boxPlot} */ dc.boxPlot = function (parent, chartGroup) { var _chart = dc.coordinateGridMixin({}); // Returns a function to compute the interquartile range. function DEFAULT_WHISKERS_IQR (k) { return function (d) { var q1 = d.quartiles[0], q3 = d.quartiles[2], iqr = (q3 - q1) * k, i = -1, j = d.length; do { ++i; } while (d[i] < q1 - iqr); do { --j; } while (d[j] > q3 + iqr); return [i, j]; }; } var _whiskerIqrFactor = 1.5; var _whiskersIqr = DEFAULT_WHISKERS_IQR; var _whiskers = _whiskersIqr(_whiskerIqrFactor); var _box = d3.box(); var _tickFormat = null; var _boxWidth = function (innerChartWidth, xUnits) { if (_chart.isOrdinal()) { return _chart.x().rangeBand(); } else { return innerChartWidth / (1 + _chart.boxPadding()) / xUnits; } }; // default padding to handle min/max whisker text _chart.yAxisPadding(12); // default to ordinal _chart.x(d3.scale.ordinal()); _chart.xUnits(dc.units.ordinal); // valueAccessor should return an array of values that can be coerced into numbers // or if data is overloaded for a static array of arrays, it should be `Number`. // Empty arrays are not included. _chart.data(function (group) { return group.all().map(function (d) { d.map = function (accessor) { return accessor.call(d, d); }; return d; }).filter(function (d) { var values = _chart.valueAccessor()(d); return values.length !== 0; }); }); /** * Get or set the spacing between boxes as a fraction of box size. Valid values are within 0-1. * See the {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md#ordinal_rangeBands d3 docs} * for a visual description of how the padding is applied. * @method boxPadding * @memberof dc.boxPlot * @instance * @see {@link https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md#ordinal_rangeBands d3.scale.ordinal.rangeBands} * @param {Number} [padding=0.8] * @returns {Number|dc.boxPlot} */ _chart.boxPadding = _chart._rangeBandPadding; _chart.boxPadding(0.8); /** * Get or set the outer padding on an ordinal box chart. This setting has no effect on non-ordinal charts * or on charts with a custom {@link dc.boxPlot#boxWidth .boxWidth}. Will pad the width by * `padding * barWidth` on each side of the chart. * @method outerPadding * @memberof dc.boxPlot * @instance * @param {Number} [padding=0.5] * @returns {Number|dc.boxPlot} */ _chart.outerPadding = _chart._outerRangeBandPadding; _chart.outerPadding(0.5); /** * Get or set the numerical width of the boxplot box. The width may also be a function taking as * parameters the chart width excluding the right and left margins, as well as the number of x * units. * @example * // Using numerical parameter * chart.boxWidth(10); * // Using function * chart.boxWidth((innerChartWidth, xUnits) { ... }); * @method boxWidth * @memberof dc.boxPlot * @instance * @param {Number|Function} [boxWidth=0.5] * @returns {Number|Function|dc.boxPlot} */ _chart.boxWidth = function (boxWidth) { if (!arguments.length) { return _boxWidth; } _boxWidth = d3.functor(boxWidth); return _chart; }; var boxTransform = function (d, i) { var xOffset = _chart.x()(_chart.keyAccessor()(d, i)); return 'translate(' + xOffset + ', 0)'; }; _chart._preprocessData = function () { if (_chart.elasticX()) { _chart.x().domain([]); } }; _chart.plotData = function () { var _calculatedBoxWidth = _boxWidth(_chart.effectiveWidth(), _chart.xUnitCount()); _box.whiskers(_whiskers) .width(_calculatedBoxWidth) .height(_chart.effectiveHeight()) .value(_chart.valueAccessor()) .domain(_chart.y().domain()) .duration(_chart.transitionDuration()) .tickFormat(_tickFormat); var boxesG = _chart.chartBodyG().selectAll('g.box').data(_chart.data(), _chart.keyAccessor()); renderBoxes(boxesG); updateBoxes(boxesG); removeBoxes(boxesG); _chart.fadeDeselectedArea(); }; function renderBoxes (boxesG) { var boxesGEnter = boxesG.enter().append('g'); boxesGEnter .attr('class', 'box') .attr('transform', boxTransform) .call(_box) .on('click', function (d) { _chart.filter(_chart.keyAccessor()(d)); _chart.redrawGroup(); }); } function updateBoxes (boxesG) { dc.transition(boxesG, _chart.transitionDuration(), _chart.transitionDelay()) .attr('transform', boxTransform) .call(_box) .each(function () { d3.select(this).select('rect.box').attr('fill', _chart.getColor); }); } function removeBoxes (boxesG) { boxesG.exit().remove().call(_box); } _chart.fadeDeselectedArea = function () { if (_chart.hasFilter()) { if (_chart.isOrdinal()) { _chart.g().selectAll('g.box').each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { var extent = _chart.brush().extent(); var start = extent[0]; var end = extent[1]; var keyAccessor = _chart.keyAccessor(); _chart.g().selectAll('g.box').each(function (d) { var key = keyAccessor(d); if (key < start || key >= end) { _chart.fadeDeselected(this); } else { _chart.highlightSelected(this); } }); } } else { _chart.g().selectAll('g.box').each(function () { _chart.resetHighlight(this); }); } }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(_chart.keyAccessor()(d)); }; _chart.yAxisMin = function () { var min = d3.min(_chart.data(), function (e) { return d3.min(_chart.valueAccessor()(e)); }); return dc.utils.subtract(min, _chart.yAxisPadding()); }; _chart.yAxisMax = function () { var max = d3.max(_chart.data(), function (e) { return d3.max(_chart.valueAccessor()(e)); }); return dc.utils.add(max, _chart.yAxisPadding()); }; /** * Set the numerical format of the boxplot median, whiskers and quartile labels. Defaults to * integer formatting. * @example * // format ticks to 2 decimal places * chart.tickFormat(d3.format('.2f')); * @method tickFormat * @memberof dc.boxPlot * @instance * @param {Function} [tickFormat] * @returns {Number|Function|dc.boxPlot} */ _chart.tickFormat = function (tickFormat) { if (!arguments.length) { return _tickFormat; } _tickFormat = tickFormat; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * The select menu is a simple widget designed to filter a dimension by selecting an option from * an HTML `<select/>` menu. The menu can be optionally turned into a multiselect. * @class selectMenu * @memberof dc * @mixes dc.baseMixin * @example * // create a select menu under #select-container using the default global chart group * var select = dc.selectMenu('#select-container') * .dimension(states) * .group(stateGroup); * // the option text can be set via the title() function * // by default the option text is '`key`: `value`' * select.title(function (d){ * return 'STATE: ' + d.key; * }) * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. * @param {String} [chartGroup] - The name of the chart group this widget should be placed in. * Interaction with the widget will only trigger events and redraws within its group. * @returns {selectMenu} **/ dc.selectMenu = function (parent, chartGroup) { var SELECT_CSS_CLASS = 'dc-select-menu'; var OPTION_CSS_CLASS = 'dc-select-option'; var _chart = dc.baseMixin({}); var _select; var _promptText = 'Select all'; var _multiple = false; var _promptValue = null; var _numberVisible = null; var _order = function (a, b) { return _chart.keyAccessor()(a) > _chart.keyAccessor()(b) ? 1 : _chart.keyAccessor()(b) > _chart.keyAccessor()(a) ? -1 : 0; }; var _filterDisplayed = function (d) { return _chart.valueAccessor()(d) > 0; }; _chart.data(function (group) { return group.all().filter(_filterDisplayed); }); _chart._doRender = function () { _chart.select('select').remove(); _select = _chart.root().append('select') .classed(SELECT_CSS_CLASS, true); _select.append('option').text(_promptText).attr('value', ''); _chart._doRedraw(); return _chart; }; _chart._doRedraw = function () { setAttributes(); renderOptions(); // select the option(s) corresponding to current filter(s) if (_chart.hasFilter() && _multiple) { _select.selectAll('option') .property('selected', function (d) { return d && _chart.filters().indexOf(String(_chart.keyAccessor()(d))) >= 0; }); } else if (_chart.hasFilter()) { _select.property('value', _chart.filter()); } else { _select.property('value', ''); } return _chart; }; function renderOptions () { var options = _select.selectAll('option.' + OPTION_CSS_CLASS) .data(_chart.data(), function (d) { return _chart.keyAccessor()(d); }); options.enter() .append('option') .classed(OPTION_CSS_CLASS, true) .attr('value', function (d) { return _chart.keyAccessor()(d); }); options.text(_chart.title()); options.exit().remove(); _select.selectAll('option.' + OPTION_CSS_CLASS).sort(_order); _select.on('change', onChange); return options; } function onChange (d, i) { var values; var target = d3.event.target; if (target.selectedOptions) { var selectedOptions = Array.prototype.slice.call(target.selectedOptions); values = selectedOptions.map(function (d) { return d.value; }); } else { // IE and other browsers do not support selectedOptions // adapted from this polyfill: https://gist.github.com/brettz9/4212217 var options = [].slice.call(d3.event.target.options); values = options.filter(function (option) { return option.selected; }).map(function (option) { return option.value; }); } // console.log(values); // check if only prompt option is selected if (values.length === 1 && values[0] === '') { values = _promptValue || null; } else if (!_multiple && values.length === 1) { values = values[0]; } _chart.onChange(values); } _chart.onChange = function (val) { if (val && _multiple) { _chart.replaceFilter([val]); } else if (val) { _chart.replaceFilter(val); } else { _chart.filterAll(); } dc.events.trigger(function () { _chart.redrawGroup(); }); }; function setAttributes () { if (_multiple) { _select.attr('multiple', true); } else { _select.attr('multiple', null); } if (_numberVisible !== null) { _select.attr('size', _numberVisible); } else { _select.attr('size', null); } } /** * Get or set the function that controls the ordering of option tags in the * select menu. By default options are ordered by the group key in ascending * order. * @name order * @memberof dc.selectMenu * @instance * @param {Function} [order] * @example * // order by the group's value * chart.order(function (a,b) { * return a.value > b.value ? 1 : b.value > a.value ? -1 : 0; * }); **/ _chart.order = function (order) { if (!arguments.length) { return _order; } _order = order; return _chart; }; /** * Get or set the text displayed in the options used to prompt selection. * @name promptText * @memberof dc.selectMenu * @instance * @param {String} [promptText='Select all'] * @example * chart.promptText('All states'); **/ _chart.promptText = function (_) { if (!arguments.length) { return _promptText; } _promptText = _; return _chart; }; /** * Get or set the function that filters option tags prior to display. By default options * with a value of < 1 are not displayed. * @name filterDisplayed * @memberof dc.selectMenu * @instance * @param {function} [filterDisplayed] * @example * // display all options override the `filterDisplayed` function: * chart.filterDisplayed(function () { * return true; * }); **/ _chart.filterDisplayed = function (filterDisplayed) { if (!arguments.length) { return _filterDisplayed; } _filterDisplayed = filterDisplayed; return _chart; }; /** * Controls the type of select menu. Setting it to true converts the underlying * HTML tag into a multiple select. * @name multiple * @memberof dc.selectMenu * @instance * @param {boolean} [multiple=false] * @example * chart.multiple(true); **/ _chart.multiple = function (multiple) { if (!arguments.length) { return _multiple; } _multiple = multiple; return _chart; }; /** * Controls the default value to be used for * [dimension.filter](https://github.com/crossfilter/crossfilter/wiki/API-Reference#dimension_filter) * when only the prompt value is selected. If `null` (the default), no filtering will occur when * just the prompt is selected. * @name promptValue * @memberof dc.selectMenu * @instance * @param {?*} [promptValue=null] **/ _chart.promptValue = function (promptValue) { if (!arguments.length) { return _promptValue; } _promptValue = promptValue; return _chart; }; /** * Controls the number of items to show in the select menu, when `.multiple()` is true. This * controls the [`size` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#Attributes) of * the `select` element. If `null` (the default), uses the browser's default height. * @name numberItems * @memberof dc.selectMenu * @instance * @param {?number} [numberVisible=null] * @example * chart.numberVisible(10); **/ _chart.numberVisible = function (numberVisible) { if (!arguments.length) { return _numberVisible; } _numberVisible = numberVisible; return _chart; }; _chart.size = dc.logger.deprecate(_chart.numberVisible, 'selectMenu.size is ambiguous - use numberVisible instead'); return _chart.anchor(parent, chartGroup); }; // Renamed functions dc.abstractBubbleChart = dc.bubbleMixin; dc.baseChart = dc.baseMixin; dc.capped = dc.capMixin; dc.colorChart = dc.colorMixin; dc.coordinateGridChart = dc.coordinateGridMixin; dc.marginable = dc.marginMixin; dc.stackableChart = dc.stackMixin; // Expose d3 and crossfilter, so that clients in browserify // case can obtain them if they need them. dc.d3 = d3; dc.crossfilter = crossfilter; return dc;} if(typeof define === "function" && define.amd) { define(["d3", "crossfilter"], _dc); } else if(typeof module === "object" && module.exports) { var _d3 = require('d3'); var _crossfilter = require('crossfilter2'); // When using npm + browserify, 'crossfilter' is a function, // since package.json specifies index.js as main function, and it // does special handling. When using bower + browserify, // there's no main in bower.json (in fact, there's no bower.json), // so we need to fix it. if (typeof _crossfilter !== "function") { _crossfilter = _crossfilter.crossfilter; } module.exports = _dc(_d3, _crossfilter); } else { this.dc = _dc(d3, crossfilter); } } )(); //# sourceMappingURL=dc.js.map
src/components/Trend/Trend.js
Zoomdata/nhtsa-dashboard
import flowRight from 'lodash.flowright'; import React, { Component } from 'react'; import TrendChart from '../TrendChart/TrendChart'; import { observer, inject } from 'mobx-react'; import { toJS } from 'mobx'; class Trend extends Component { render() { const { store } = this.props; const data = toJS(store.chartData.yearData); const filterStatus = store.chartFilters.get('filterStatus'); return ( <div id="trend"> <TrendChart data={data} filterStatus={filterStatus} onBrushEnd={this.onBrushEnd} /> </div> ); } onBrushEnd = (selectedYears, changeFilterStatus) => { const { store } = this.props; store.queries.gridDataQuery.set(['offset'], 0); const filter = { path: 'year_string', operation: 'IN', value: selectedYears, }; store.chartFilters.set('year', selectedYears); store.queries.componentDataQuery.filters.remove(filter.path); store.queries.componentDataQuery.filters.add(filter); store.queries.metricDataQuery.filters.remove(filter.path); store.queries.metricDataQuery.filters.add(filter); store.queries.stateDataQuery.filters.remove(filter.path); store.queries.stateDataQuery.filters.add(filter); store.queries.gridDataQuery.filters.remove(filter.path); store.queries.gridDataQuery.filters.add(filter); if (changeFilterStatus) { store.chartFilters.set('filterStatus', 'FILTERS_APPLIED'); } }; } export default flowRight(inject('store'), observer)(Trend);
Examples/UIExplorer/js/AnimatedGratuitousApp/AnExApp.js
DanielMSchmidt/react-native
/** * 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. * * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @providesModule AnExApp * @flow */ 'use strict'; var React = require('react'); var ReactNative = require('react-native'); var { Animated, LayoutAnimation, PanResponder, StyleSheet, View, } = ReactNative; var AnExSet = require('AnExSet'); var CIRCLE_SIZE = 80; var CIRCLE_MARGIN = 18; var NUM_CIRCLES = 30; class Circle extends React.Component { state: any; props: any; longTimer: number; _onLongPress: () => void; _toggleIsActive: () => void; constructor(props: Object): void { super(); this._onLongPress = this._onLongPress.bind(this); this._toggleIsActive = this._toggleIsActive.bind(this); this.state = { isActive: false, pan: new Animated.ValueXY(), // Vectors reduce boilerplate. (step1: uncomment) pop: new Animated.Value(0), // Initial value. (step2a: uncomment) }; } _onLongPress(): void { var config = {tension: 40, friction: 3}; this.state.pan.addListener((value) => { // Async listener for state changes (step1: uncomment) this.props.onMove && this.props.onMove(value); }); Animated.spring(this.state.pop, { toValue: 1, // Pop to larger size. (step2b: uncomment) ...config, // Reuse config for convenient consistency (step2b: uncomment) }).start(); this.setState({panResponder: PanResponder.create({ onPanResponderMove: Animated.event([ null, // native event - ignore (step1: uncomment) {dx: this.state.pan.x, dy: this.state.pan.y}, // links pan to gestureState (step1: uncomment) ]), onPanResponderRelease: (e, gestureState) => { LayoutAnimation.easeInEaseOut(); // @flowfixme animates layout update as one batch (step3: uncomment) Animated.spring(this.state.pop, { toValue: 0, // Pop back to 0 (step2c: uncomment) ...config, }).start(); this.setState({panResponder: undefined}); this.props.onMove && this.props.onMove({ x: gestureState.dx + this.props.restLayout.x, y: gestureState.dy + this.props.restLayout.y, }); this.props.onDeactivate(); this.state.pan.removeAllListeners(); }, })}, () => { this.props.onActivate(); }); } render(): React.Element<any> { if (this.state.panResponder) { var handlers = this.state.panResponder.panHandlers; var dragStyle = { // Used to position while dragging position: 'absolute', // Hoist out of layout (step1: uncomment) ...this.state.pan.getLayout(), // Convenience converter (step1: uncomment) }; } else { handlers = { onStartShouldSetResponder: () => !this.state.isActive, onResponderGrant: () => { this.state.pan.setValue({x: 0, y: 0}); // reset (step1: uncomment) this.state.pan.setOffset(this.props.restLayout); // offset from onLayout (step1: uncomment) this.longTimer = setTimeout(this._onLongPress, 300); }, onResponderRelease: () => { if (!this.state.panResponder) { clearTimeout(this.longTimer); this._toggleIsActive(); } } }; } var animatedStyle: Object = { shadowOpacity: this.state.pop, // no need for interpolation (step2d: uncomment) transform: [ {scale: this.state.pop.interpolate({ inputRange: [0, 1], outputRange: [1, 1.3] // scale up from 1 to 1.3 (step2d: uncomment) })}, ], }; var openVal = this.props.openVal; if (this.props.dummy) { animatedStyle.opacity = 0; } else if (this.state.isActive) { var innerOpenStyle = [styles.open, { // (step4: uncomment) left: openVal.interpolate({inputRange: [0, 1], outputRange: [this.props.restLayout.x, 0]}), top: openVal.interpolate({inputRange: [0, 1], outputRange: [this.props.restLayout.y, 0]}), width: openVal.interpolate({inputRange: [0, 1], outputRange: [CIRCLE_SIZE, this.props.containerLayout.width]}), height: openVal.interpolate({inputRange: [0, 1], outputRange: [CIRCLE_SIZE, this.props.containerLayout.height]}), margin: openVal.interpolate({inputRange: [0, 1], outputRange: [CIRCLE_MARGIN, 0]}), borderRadius: openVal.interpolate({inputRange: [-0.15, 0, 0.5, 1], outputRange: [0, CIRCLE_SIZE / 2, CIRCLE_SIZE * 1.3, 0]}), }]; } return ( <Animated.View onLayout={this.props.onLayout} style={[styles.dragView, dragStyle, animatedStyle, this.state.isActive ? styles.open : null]} {...handlers}> <Animated.View style={[styles.circle, innerOpenStyle]}> <AnExSet containerLayout={this.props.containerLayout} id={this.props.id} isActive={this.state.isActive} openVal={this.props.openVal} onDismiss={this._toggleIsActive} /> </Animated.View> </Animated.View> ); } _toggleIsActive(velocity) { var config = {tension: 30, friction: 7}; if (this.state.isActive) { Animated.spring(this.props.openVal, {toValue: 0, ...config}).start(() => { // (step4: uncomment) this.setState({isActive: false}, this.props.onDeactivate); }); // (step4: uncomment) } else { this.props.onActivate(); this.setState({isActive: true, panResponder: undefined}, () => { // this.props.openVal.setValue(1); // (step4: comment) Animated.spring(this.props.openVal, {toValue: 1, ...config}).start(); // (step4: uncomment) }); } } } class AnExApp extends React.Component { state: any; props: any; static title = 'Animated - Gratuitous App'; static description = 'Bunch of Animations - tap a circle to ' + 'open a view with more animations, or longPress and drag to reorder circles.'; _onMove: (position: Point) => void; constructor(props: any): void { super(props); var keys = []; for (var idx = 0; idx < NUM_CIRCLES; idx++) { keys.push('E' + idx); } this.state = { keys, restLayouts: [], openVal: new Animated.Value(0), }; this._onMove = this._onMove.bind(this); } render(): React.Element<any> { var circles = this.state.keys.map((key, idx) => { if (key === this.state.activeKey) { return <Circle key={key + 'd'} dummy={true} />; } else { if (!this.state.restLayouts[idx]) { var onLayout = function(index, e) { var layout = e.nativeEvent.layout; this.setState((state) => { state.restLayouts[index] = layout; return state; }); }.bind(this, idx); } return ( <Circle key={key} id={key} openVal={this.state.openVal} onLayout={onLayout} restLayout={this.state.restLayouts[idx]} onActivate={this.setState.bind(this, { activeKey: key, activeInitialLayout: this.state.restLayouts[idx], })} /> ); } }); if (this.state.activeKey) { circles.push( <Animated.View key="dark" style={[styles.darkening, {opacity: this.state.openVal}]} /> ); circles.push( <Circle openVal={this.state.openVal} key={this.state.activeKey} id={this.state.activeKey} restLayout={this.state.activeInitialLayout} containerLayout={this.state.layout} onMove={this._onMove} onDeactivate={() => { this.setState({activeKey: undefined}); }} /> ); } return ( <View style={styles.container}> <View style={styles.grid} onLayout={(e) => this.setState({layout: e.nativeEvent.layout})}> {circles} </View> </View> ); } _onMove(position: Point): void { var newKeys = moveToClosest(this.state, position); if (newKeys !== this.state.keys) { LayoutAnimation.easeInEaseOut(); // animates layout update as one batch (step3: uncomment) this.setState({keys: newKeys}); } } } type Point = {x: number, y: number}; function distance(p1: Point, p2: Point): number { var dx = p1.x - p2.x; var dy = p1.y - p2.y; return dx * dx + dy * dy; } function moveToClosest({activeKey, keys, restLayouts}, position) { var activeIdx = -1; var closestIdx = activeIdx; var minDist = Infinity; var newKeys = []; keys.forEach((key, idx) => { var dist = distance(position, restLayouts[idx]); if (key === activeKey) { idx = activeIdx; } else { newKeys.push(key); } if (dist < minDist) { minDist = dist; closestIdx = idx; } }); if (closestIdx === activeIdx) { return keys; // nothing changed } else { newKeys.splice(closestIdx, 0, activeKey); return newKeys; } } var styles = StyleSheet.create({ container: { flex: 1, }, grid: { flex: 1, justifyContent: 'center', flexDirection: 'row', flexWrap: 'wrap', backgroundColor: 'transparent', }, circle: { width: CIRCLE_SIZE, height: CIRCLE_SIZE, borderRadius: CIRCLE_SIZE / 2, borderWidth: 1, borderColor: 'black', margin: CIRCLE_MARGIN, overflow: 'hidden', }, dragView: { shadowRadius: 10, shadowColor: 'rgba(0,0,0,0.7)', shadowOffset: {height: 8}, alignSelf: 'flex-start', backgroundColor: 'transparent', }, open: { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, width: undefined, // unset value from styles.circle height: undefined, // unset value from styles.circle borderRadius: 0, // unset value from styles.circle }, darkening: { backgroundColor: 'black', position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, }, }); module.exports = AnExApp;
test/header/DesktopHeader.spec.js
sk1981/react-header
import React from 'react'; import { shallow } from 'enzyme'; import {expect} from 'chai'; import DesktopHeader from '../../src/header/DesktopHeader.js'; import NavigationList from '../../src/navigation/NavigationList.js'; describe("Desktop Header ", function() { it('Adds a main menu prop to NavigationList', function() { const desktopHeaderWrapper = shallow( <DesktopHeader> <NavigationList> <div>child</div> </NavigationList> <div>another</div> </DesktopHeader> ); const navList = desktopHeaderWrapper.find(NavigationList); expect(navList.prop('isMainMenu')).to.equal(true); }); it('Adds keys to each child', function() { const desktopHeaderWrapper = shallow( <DesktopHeader> <NavigationList> <div>child 1</div> </NavigationList> <div>first item</div> <div>second item</div> </DesktopHeader> ); const desktopChild = desktopHeaderWrapper.children(); expect(desktopChild.at(0).key()).to.equal('nav'); expect(desktopChild.at(1).key()).to.equal('1'); expect(desktopChild.at(2).key()).to.equal('2'); }); });
src/components/nav-elements.js
ZhenxingXiao/zls-front-end
require('styles/gen.css'); import React from 'react'; class NavContainer extends React.Componet { render(){ return( <div>First Nav Container</div> ); } } NavContainer.defaultProps = { }; export default NavContainer;
ajax/libs/angular-data/0.5.0/angular-data.js
mohitbhatia1994/cdnjs
/** * @author Jason Dobry <jason.dobry@gmail.com> * @file angular-data.js * @version 0.5.0 - Homepage <http://jmdobry.github.io/angular-data/> * @copyright (c) 2014 Jason Dobry <https://github.com/jmdobry/angular-data> * @license MIT <https://github.com/jmdobry/angular-data/blob/master/LICENSE> * * @overview Data store for Angular.js. */ require=(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})({"u+GZEJ":[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};// Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. (function(global) { 'use strict'; function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var gotSplice = false; function callback(records) { if (records[0].type === 'splice' && records[1].type === 'splice') gotSplice = true; } var test = [0]; Array.observe(test, callback); test[1] = 1; test.length = 0; Object.deliverChangeRecords(callback); return gotSplice; } var hasObserve = detectObjectObserve(); var hasEval = false; try { var f = new Function('', 'return true;'); hasEval = f(); } catch (ex) { } function isObject(obj) { return obj === Object(obj); } var numberIsNaN = global.Number.isNaN || function isNaN(value) { return typeof value === 'number' && global.isNaN(value); } 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()) { observer.report(); cycles++; } } 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 diffObjectFromOldObject(object, oldObject) { var added = {}; var removed = {}; var changed = {}; var oldObjectHas = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } function copyObject(object, opt_copy) { var copy = opt_copy || (Array.isArray(object) ? [] : {}); for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; } function Observer(object, callback, target, token) { this.closed = false; this.object = object; this.callback = callback; // TODO(rafaelw): Hold this.target weakly when WeakRef is available. this.target = target; this.token = token; this.reporting = true; if (hasObserve) { var self = this; this.boundInternalCallback = function(records) { self.internalCallback(records); }; } addToAll(this); this.connect(); this.sync(true); } Observer.prototype = { internalCallback: function(records) { if (this.closed) return; if (this.reporting && this.check(records)) { this.report(); if (this.testingResults) this.testingResults.anyChanged = true; } }, close: function() { if (this.closed) return; if (this.object && typeof this.object.unobserved === 'function') this.object.unobserved(); this.disconnect(); this.object = undefined; this.closed = true; }, deliver: function(testingResults) { if (this.closed) return; if (hasObserve) { this.testingResults = testingResults; Object.deliverChangeRecords(this.boundInternalCallback); this.testingResults = undefined; } else { dirtyCheck(this); } }, report: function() { if (!this.reporting) return; this.sync(false); this.reportArgs.push(this.token); this.invokeCallback(this.reportArgs); this.reportArgs = undefined; }, invokeCallback: function(args) { try { this.callback.apply(this.target, args); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + ex); } }, reset: function() { if (this.closed) return; if (hasObserve) { this.reporting = false; Object.deliverChangeRecords(this.boundInternalCallback); this.reporting = true; } this.sync(true); } } var collectObservers = !hasObserve || global.forceCollectObservers; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { if (!collectObservers) return; allObservers.push(observer); Observer._allObserversCount++; } var runningMicrotaskCheckpoint = false; var hasDebugForceFullDelivery = typeof Object.deliverAllChangeRecords == 'function'; global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (hasDebugForceFullDelivery) { Object.deliverAllChangeRecords(); return; } if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var results = {}; do { cycles++; var toCheck = allObservers; allObservers = []; results.anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.closed) continue; if (hasObserve) { observer.deliver(results); } else if (observer.check()) { results.anyChanged = true; observer.report(); } allObservers.push(observer); } } while (cycles < MAX_DIRTY_CHECK_CYCLES && results.anyChanged); Observer._allObserversCount = allObservers.length; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object, callback, target, token) { Observer.call(this, object, callback, target, token); } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, connect: function() { if (hasObserve) Object.observe(this.object, this.boundInternalCallback); }, sync: function(hard) { if (!hasObserve) this.oldObject = copyObject(this.object); }, check: function(changeRecords) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.object, changeRecords, oldValues); } else { oldValues = this.oldObject; diff = diffObjectFromOldObject(this.object, this.oldObject); } if (diffIsEmpty(diff)) return false; this.reportArgs = [diff.added || {}, diff.removed || {}, diff.changed || {}]; this.reportArgs.push(function(property) { return oldValues[property]; }); return true; }, disconnect: function() { if (!hasObserve) this.oldObject = undefined; else if (this.object) Object.unobserve(this.object, this.boundInternalCallback); } }); function ObservedSet(callback) { this.arr = []; this.callback = callback; this.isObserved = true; } var objProto = Object.getPrototypeOf({}); var arrayProto = Object.getPrototypeOf([]); ObservedSet.prototype = { reset: function() { this.isObserved = !this.isObserved; }, observe: function(obj) { if (!isObject(obj) || obj === objProto || obj === arrayProto) return; var i = this.arr.indexOf(obj); if (i >= 0 && this.arr[i+1] === this.isObserved) return; if (i < 0) { i = this.arr.length; this.arr[i] = obj; Object.observe(obj, this.callback); } this.arr[i+1] = this.isObserved; this.observe(Object.getPrototypeOf(obj)); }, cleanup: function() { var i = 0, j = 0; var isObserved = this.isObserved; while(j < this.arr.length) { var obj = this.arr[j]; if (this.arr[j + 1] == isObserved) { if (i < j) { this.arr[i] = obj; this.arr[i + 1] = isObserved; } i += 2; } else { Object.unobserve(obj, this.callback); } j += 2; } this.arr.length = i; } }; var knownRecordTypes = { 'new': true, 'updated': true, 'deleted': true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!knownRecordTypes[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 == 'updated') continue; if (record.type == 'new') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'deleted' 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 }; } global.Observer = Observer; global.Observer.hasObjectObserve = hasObserve; global.ObjectObserver = ObjectObserver; })((exports.Number = { isNaN: window.isNaN }) ? exports : exports); },{}],"observejs":[function(require,module,exports){ module.exports=require('u+GZEJ'); },{}],3:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; },{"./indexOf":5}],4:[function(require,module,exports){ var makeIterator = require('../function/makeIterator_'); /** * Array filter */ function filter(arr, callback, thisObj) { callback = makeIterator(callback, thisObj); var results = []; if (arr == null) { return results; } var i = -1, len = arr.length, value; while (++i < len) { value = arr[i]; if (callback(value, i, arr)) { results.push(value); } } return results; } module.exports = filter; },{"../function/makeIterator_":11}],5:[function(require,module,exports){ /** * 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; },{}],6:[function(require,module,exports){ var filter = require('./filter'); function isValidString(val) { return (val != null && val !== ''); } /** * Joins strings with the specified separator inserted between each value. * Null values and empty strings will be excluded. */ function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); } module.exports = join; },{"./filter":4}],7:[function(require,module,exports){ var arrSlice = Array.prototype.slice; /** * Create slice of source array or array-like object */ function slice(arr, start, end){ return arrSlice.call(arr, start, end); } module.exports = slice; },{}],8:[function(require,module,exports){ /** * 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; },{}],9:[function(require,module,exports){ var isFunction = require('../lang/isFunction'); /** * Creates an object that holds a lookup for the objects in the array. */ function toLookup(arr, key) { var result = {}; if (arr == null) { return result; } var i = -1, len = arr.length, value; if (isFunction(key)) { while (++i < len) { value = arr[i]; result[key(value)] = value; } } else { while (++i < len) { value = arr[i]; result[value[key]] = value; } } return result; } module.exports = toLookup; },{"../lang/isFunction":15}],10:[function(require,module,exports){ /** * Returns the first argument provided to it. */ function identity(val){ return val; } module.exports = identity; },{}],11:[function(require,module,exports){ var identity = require('./identity'); var prop = require('./prop'); var deepMatches = require('../object/deepMatches'); /** * Converts argument into a valid iterator. * Used internally on most array/object/collection methods that receives a * callback/iterator providing a shortcut syntax. */ function makeIterator(src, thisObj){ if (src == null) { return identity; } switch(typeof src) { case 'function': // function is the first to improve perf (most common case) // also avoid using `Function#call` if not needed, which boosts // perf a lot in some cases return (typeof thisObj !== 'undefined')? function(val, i, arr){ return src.call(thisObj, val, i, arr); } : src; case 'object': return function(val){ return deepMatches(val, src); }; case 'string': case 'number': return prop(src); } } module.exports = makeIterator; },{"../object/deepMatches":20,"./identity":10,"./prop":12}],12:[function(require,module,exports){ /** * Returns a function that gets a property of the passed object */ function prop(name){ return function(obj){ return obj[name]; }; } module.exports = prop; },{}],13:[function(require,module,exports){ var isKind = require('./isKind'); /** */ var isArray = Array.isArray || function (val) { return isKind(val, 'Array'); }; module.exports = isArray; },{"./isKind":16}],14:[function(require,module,exports){ var forOwn = require('../object/forOwn'); var isArray = require('./isArray'); function isEmpty(val){ if (val == null) { // typeof null == 'object' so we check it first return false; } else if ( typeof val === 'string' || isArray(val) ) { return !val.length; } else if ( typeof val === 'object' || typeof val === 'function' ) { var result = true; forOwn(val, function(){ result = false; return false; // break loop }); return result; } else { return false; } } module.exports = isEmpty; },{"../object/forOwn":23,"./isArray":13}],15:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isFunction(val) { return isKind(val, 'Function'); } module.exports = isFunction; },{"./isKind":16}],16:[function(require,module,exports){ var kindOf = require('./kindOf'); /** * Check if value is from a specific "kind". */ function isKind(val, kind){ return kindOf(val) === kind; } module.exports = isKind; },{"./kindOf":18}],17:[function(require,module,exports){ /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; },{}],18:[function(require,module,exports){ var _rKind = /^\[object (.*)\]$/, _toString = Object.prototype.toString, UNDEF; /** * Gets the "kind" of value. (e.g. "String", "Number", etc) */ function kindOf(val) { if (val === null) { return 'Null'; } else if (val === UNDEF) { return 'Undefined'; } else { return _rKind.exec( _toString.call(val) )[1]; } } module.exports = kindOf; },{}],19:[function(require,module,exports){ /** * 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; },{}],20:[function(require,module,exports){ var forOwn = require('./forOwn'); var isArray = require('../lang/isArray'); function containsMatch(array, pattern) { var i = -1, length = array.length; while (++i < length) { if (deepMatches(array[i], pattern)) { return true; } } return false; } function matchArray(target, pattern) { var i = -1, patternLength = pattern.length; while (++i < patternLength) { if (!containsMatch(target, pattern[i])) { return false; } } return true; } function matchObject(target, pattern) { var result = true; forOwn(pattern, function(val, key) { if (!deepMatches(target[key], val)) { // Return false to break out of forOwn early return (result = false); } }); return result; } /** * Recursively check if the objects match. */ function deepMatches(target, pattern){ if (target && typeof target === 'object') { if (isArray(target) && isArray(pattern)) { return matchArray(target, pattern); } else { return matchObject(target, pattern); } } else { return target === pattern; } } module.exports = deepMatches; },{"../lang/isArray":13,"./forOwn":23}],21:[function(require,module,exports){ var forOwn = require('./forOwn'); var isPlainObject = require('../lang/isPlainObject'); /** * 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; },{"../lang/isPlainObject":17,"./forOwn":23}],22:[function(require,module,exports){ 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) { while (key = _dontEnums[i++]) { // since we aren't using hasOwn check we need to make sure the // property was overwritten if (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; },{}],23:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var forIn = require('./forIn'); /** * 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; },{"./forIn":22,"./hasOwn":24}],24:[function(require,module,exports){ /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; },{}],25:[function(require,module,exports){ var join = require('../array/join'); var slice = require('../array/slice'); /** * Group arguments as path segments, if any of the args is `null` or an * empty string it will be ignored from resulting path. */ function makePath(var_args){ var result = join(slice(arguments), '/'); // need to disconsider duplicate '/' after protocol (eg: 'http://') return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); } module.exports = makePath; },{"../array/join":6,"../array/slice":7}],26:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; },{"../lang/toString":19}],"clHM+W":[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'); function _$http(deferred, config) { var start = new Date().getTime(); services.$http(config).success(function (data, status, headers, config) { services.$log.debug(config.method + ' request:' + config.url + ' Time taken: ' + (new Date().getTime() - start) + 'ms', arguments); deferred.resolve(data); }).error(function (data, status, headers, config) { services.$log.error(arguments); deferred.reject(data); }); } /** * @doc method * @id DS.async_methods:HTTP * @name HTTP * @description * Wrapper for `$http()`. * * ## Signature: * ```js * DS.HTTP(config) * ``` * * ## Example: * * ```js * works the same as $http() * ``` * * @param {object} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function HTTP(config) { var deferred = services.$q.defer(); try { if (!services.$rootScope.$$phase) { services.$rootScope.$apply(function () { _$http(deferred, config); }); } else { _$http(deferred, config); } } catch (err) { deferred.reject(new errors.UnhandledError(err)); } return deferred.promise; } /** * @doc method * @id DS.async_methods:GET * @name GET * @description * Wrapper for `$http.get()`. * * ## Signature: * ```js * DS.GET(url[, config]) * ``` * * ## Example: * * ```js * Works the same as $http.get() * ``` * * @param {string} url The url of the request. * @param {object=} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function GET(url, config) { config = config || {}; return HTTP(utils.deepMixIn(config, { url: url, method: 'GET' })); } /** * @doc method * @id DS.async_methods:PUT * @name PUT * @description * Wrapper for `$http.put()`. * * ## Signature: * ```js * DS.PUT(url[, attrs][, config]) * ``` * * ## Example: * * ```js * Works the same as $http.put() * ``` * * @param {string} url The url of the request. * @param {object=} attrs Request payload. * @param {object=} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function PUT(url, attrs, config) { config = config || {}; return HTTP(utils.deepMixIn(config, { url: url, data: attrs, method: 'PUT' })); } /** * @doc method * @id DS.async_methods:POST * @name POST * @description * Wrapper for `$http.post()`. * * ## Signature: * ```js * DS.POST(url[, attrs][, config]) * ``` * * ## Example: * * ```js * Works the same as $http.post() * ``` * * @param {string} url The url of the request. * @param {object=} attrs Request payload. * @param {object=} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function POST(url, attrs, config) { config = config || {}; return HTTP(utils.deepMixIn(config, { url: url, data: attrs, method: 'POST' })); } /** * @doc method * @id DS.async_methods:DEL * @name DEL * @description * Wrapper for `$http.delete()`. * * ## Signature: * ```js * DS.DEL(url[, config]) * ``` * * ## Example: * * ```js * Works the same as $http.delete * ``` * * @param {string} url The url of the request. * @param {object} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function DEL(url, config) { config = config || {}; return HTTP(utils.deepMixIn(config, { url: url, method: 'DELETE' })); } module.exports = { /** * @doc method * @id DS.async_methods:HTTP * @name HTTP * @methodOf DS * @description * See [DS.HTTP](/documentation/api/api/DS.async_methods:HTTP). */ HTTP: HTTP, /** * @doc method * @id DS.async_methods:GET * @name GET * @methodOf DS * @description * See [DS.GET](/documentation/api/api/DS.async_methods:GET). */ GET: GET, /** * @doc method * @id DS.async_methods:POST * @name POST * @methodOf DS * @description * See [DS.POST](/documentation/api/api/DS.async_methods:POST). */ POST: POST, /** * @doc method * @id DS.async_methods:PUT * @name PUT * @methodOf DS * @description * See [DS.PUT](/documentation/api/api/DS.async_methods:PUT). */ PUT: PUT, /** * @doc method * @id DS.async_methods:DEL * @name DEL * @methodOf DS * @description * See [DS.DEL](/documentation/api/api/DS.async_methods:DEL). */ DEL: DEL }; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],"HttpAdapter":[function(require,module,exports){ module.exports=require('clHM+W'); },{}],29:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.create(resourceName, attrs): '; /** * @doc method * @id DS.async_methods:create * @name create * @description * Create a new resource and save it to the server. * * ## Signature: * ```js * DS.create(resourceName, attrs) * ``` * * ## Example: * * ```js * DS.create('document', { author: 'John Anderson' }) * .then(function (document) { * document; // { id: 'aab7ff66-e21e-46e2-8be8-264d82aee535', author: 'John Anderson' } * * // The new document is already in the data store * DS.get('document', document.id); // { id: 'aab7ff66-e21e-46e2-8be8-264d82aee535', author: 'John Anderson' } * }, function (err) { * // handle error * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} attrs The attributes with which to update the item of the type specified by `resourceName` that has * the primary key specified by `id`. * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - A reference to the newly created item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function create(resourceName, attrs) { var deferred = services.$q.defer(), promise = deferred.promise; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isObject(attrs)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'attrs: Must be an object!', { attrs: { actual: typeof attrs, expected: 'object' } })); } else { try { var resource = services.store[resourceName], _this = this; promise = promise .then(function (attrs) { return services.$q.promisify(resource.beforeValidate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.validate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.afterValidate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.beforeCreate)(resourceName, attrs); }) .then(function (attrs) { return services.adapters[resource.defaultAdapter].POST.apply(_this, [utils.makePath(resource.baseUrl, resource.endpoint), attrs, null]); }) .then(function (data) { return services.$q.promisify(resource.afterCreate)(resourceName, data); }) .then(function (data) { return _this.inject(resource.name, data); }); deferred.resolve(attrs); } catch (err) { deferred.reject(new errors.UnhandledError(err)); } } return promise; } module.exports = create; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],30:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.destroy(resourceName, id): '; /** * @doc method * @id DS.async_methods:destroy * @name destroy * @description * Delete the item of the type specified by `resourceName` with the primary key specified by `id` from the data store * and the server. * * ## Signature: * ```js * DS.destroy(resourceName, id); * ``` * * ## Example: * * ```js * DS.destroy('document', 'aab7ff66-e21e-46e2-8be8-264d82aee535') * .then(function (id) { * id; // 'aab7ff66-e21e-46e2-8be8-264d82aee535' * * // The document is gone * DS.get('document', 'aab7ff66-e21e-46e2-8be8-264d82aee535'); // undefined * }, function (err) { * // Handle error * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to remove. * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{string|number}` - `id` - The primary key of the destroyed item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function destroy(resourceName, id) { var deferred = services.$q.defer(), promise = deferred.promise; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isString(id) && !utils.isNumber(id)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } })); } else { var resource = services.store[resourceName], _this = this; promise = promise .then(function (attrs) { return services.$q.promisify(resource.beforeDestroy)(resourceName, attrs); }) .then(function () { return services.adapters[resource.defaultAdapter].DEL(utils.makePath(resource.baseUrl, resource.endpoint, id), null); }) .then(function () { return services.$q.promisify(resource.afterDestroy)(resourceName, resource.index[id]); }) .then(function () { _this.eject(resourceName, id); return id; }); deferred.resolve(resource.index[id]); } return promise; } module.exports = destroy; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],31:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.find(resourceName, id[, options]): '; /** * @doc method * @id DS.async_methods:find * @name find * @description * Asynchronously return the resource with the given id from the server. The result will be added to the data * store when it returns from the server. * * ## Signature: * ```js * DS.find(resourceName, id[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5); // undefined * DS.find('document', 5).then(function (document) { * document; // { id: 5, author: 'John Anderson' } * * DS.get('document', 5); // { id: 5, author: 'John Anderson' } * }, function (err) { * // Handled errors * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Properties: * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * - `{string=}` - `mergeStrategy` - If `findAll` is called, specify the merge strategy that should be used when the new * items are injected into the data store. Default: `"mergeWithExisting"`. * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The item with the primary key specified by `id`. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function find(resourceName, id, options) { var deferred = services.$q.defer(), promise = deferred.promise; options = options || {}; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isString(id) && !utils.isNumber(id)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } })); } else if (!utils.isObject(options)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } })); } else { try { var resource = services.store[resourceName], _this = this; if (options.bypassCache) { delete resource.completedQueries[id]; } if (!(id in resource.completedQueries)) { if (!(id in resource.pendingQueries)) { promise = resource.pendingQueries[id] = services.adapters[resource.defaultAdapter].GET(utils.makePath(resource.baseUrl, resource.endpoint, id), null) .then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; resource.completedQueries[id] = new Date().getTime(); return _this.inject(resourceName, data); }); } return resource.pendingQueries[id]; } else { deferred.resolve(_this.get(resourceName, id)); } } catch (err) { deferred.reject(err); } } return promise; } module.exports = find; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],32:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.findAll(resourceName, params[, options]): '; function processResults(data, resourceName, queryHash) { var resource = services.store[resourceName]; data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = new Date().getTime(); // Merge the new values into the cache for (var i = 0; i < data.length; i++) { this.inject(resourceName, data[i]); } // Update the data store's index for this resource resource.index = utils.toLookup(resource.collection, resource.idAttribute); // Update modified timestamp of collection resource.collectionModified = utils.updateTimestamp(resource.collectionModified); return data; } function _findAll(resourceName, params, options) { var resource = services.store[resourceName], _this = this, queryHash = utils.toJson(params); if (options.bypassCache) { delete resource.completedQueries[queryHash]; } if (!(queryHash in resource.completedQueries)) { // This particular query has never been completed if (!(queryHash in resource.pendingQueries)) { // This particular query has never even been made resource.pendingQueries[queryHash] = services.adapters[resource.defaultAdapter].GET(utils.makePath(resource.baseUrl, resource.endpoint), { params: params }) .then(function (data) { try { return processResults.apply(_this, [data, resourceName, queryHash]); } catch (err) { throw new errors.UnhandledError(err); } }); } return resource.pendingQueries[queryHash]; } else { return this.filter(resourceName, params, options); } } /** * @doc method * @id DS.async_methods:findAll * @name findAll * @description * Asynchronously return the resource from the server filtered by the query. The results will be added to the data * store when it returns from the server. * * ## Signature: * ```js * DS.findAll(resourceName, params[, options]) * ``` * * ## Example: * * ```js * var query = { * where: { * author: { * '==': 'John Anderson' * } * } * }; * * DS.findAll('document', { * query: query * }).then(function (documents) { * documents; // [{ id: 'aab7ff66-e21e-46e2-8be8-264d82aee535', author: 'John Anderson', title: 'How to cook' }, * // { id: 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f', author: 'John Anderson', title: 'How NOT to cook' }] * * // The documents are now in the data store * DS.filter('document', { * query: query * }); // [{ id: 'aab7ff66-e21e-46e2-8be8-264d82aee535', author: 'John Anderson', title: 'How to cook' }, * // { id: 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f', author: 'John Anderson', title: 'How NOT to cook' }] * * }, function (err) { * // handle error * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is serialized into the query string. Properties: * * - `{object=}` - `query` - The query object by which to filter items of the type specified by `resourceName`. Properties: * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{skip=}` - `skip` - Skip clause. * - `{orderBy=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Properties: * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * - `{string=}` - `mergeStrategy` - If `findAll` is called, specify the merge strategy that should be used when the new * items are injected into the data store. Default `"mergeWithExisting"`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{array}` - `items` - The collection of items returned by the server. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function findAll(resourceName, params, options) { var deferred = services.$q.defer(), promise = deferred.promise, _this = this; options = options || {}; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isObject(params)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'params: Must be an object!', { params: { actual: typeof params, expected: 'object' } })); } else if (!utils.isObject(options)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } })); } else { try { promise = promise.then(function () { return _findAll.apply(_this, [resourceName, params, options]); }); deferred.resolve(); } catch (err) { deferred.reject(new errors.UnhandledError(err)); } } return promise; } module.exports = findAll; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],33:[function(require,module,exports){ module.exports = { /** * @doc method * @id DS.async_methods:create * @name create * @methodOf DS * @description * See [DS.create](/documentation/api/api/DS.async_methods:create). */ create: require('./create'), /** * @doc method * @id DS.async_methods:destroy * @name destroy * @methodOf DS * @description * See [DS.destroy](/documentation/api/api/DS.async_methods:destroy). */ destroy: require('./destroy'), /** * @doc method * @id DS.async_methods:find * @name find * @methodOf DS * @description * See [DS.find](/documentation/api/api/DS.async_methods:find). */ find: require('./find'), /** * @doc method * @id DS.async_methods:findAll * @name findAll * @methodOf DS * @description * See [DS.findAll](/documentation/api/api/DS.async_methods:findAll). */ findAll: require('./findAll'), /** * @doc method * @id DS.async_methods:refresh * @name refresh * @methodOf DS * @description * See [DS.refresh](/documentation/api/api/DS.async_methods:refresh). */ refresh: require('./refresh'), /** * @doc method * @id DS.async_methods:save * @name save * @methodOf DS * @description * See [DS.save](/documentation/api/api/DS.async_methods:save). */ save: require('./save') }; },{"./create":29,"./destroy":30,"./find":31,"./findAll":32,"./refresh":34,"./save":35}],34:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.refresh(resourceName, id[, options]): '; /** * @doc method * @id DS.async_methods:refresh * @name refresh * @description * Like find(), except the resource is only refreshed from the server if it already exists in the data store. * * ## Signature: * ```js * DS.refresh(resourceName, id) * ``` * ## Example: * * ```js * // Exists in the data store, but we want a fresh copy * DS.get('document', 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f'); * * DS.refresh('document', 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f') * .then(function (document) { * document; // The fresh copy * }); * * // Does not exist in the data store * DS.get('document', 'aab7ff66-e21e-46e2-8be8-264d82aee535'); * * DS.refresh('document', 'aab7ff66-e21e-46e2-8be8-264d82aee535'); // false * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to refresh from the server. * @param {object=} options Optional configuration. Properties: * - `{string=}` - `mergeStrategy` - Specify what merge strategy is to be used when the fresh item returns from the * server and needs to be inserted into the data store. Default `"mergeWithExisting"`. * @returns {false|Promise} `false` if the item doesn't already exist in the data store. A `Promise` if the item does * exist in the data store and is being refreshed. * * ## Resolves with: * * - `{object}` - `item` - A reference to the refreshed item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function refresh(resourceName, id, options) { options = options || {}; if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } else if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } }); } else { options.bypassCache = true; if (id in services.store[resourceName].index) { return this.find(resourceName, id, options); } else { return false; } } } module.exports = refresh; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],35:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.save(resourceName, id[, options]): '; /** * @doc method * @id DS.async_methods:save * @name save * @description * Save the item of the type specified by `resourceName` that has the primary key specified by `id`. * * ## Signature: * ```js * DS.save(resourceName, id[, options]) * ``` * * ## Example: * * ```js * var document = DS.get('document', 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f'); * * document.title = 'How to cook in style'; * * DS.save('document', 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f') * .then(function (document) { * document; // A reference to the document that's been saved to the server * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Properties: * - `{string=}` - `mergeStrategy` - When the updated item returns from the server, specify the merge strategy that * should be used when the updated item is injected into the data store. Default: `"mergeWithExisting"`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - A reference to the newly saved item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function save(resourceName, id, options) { var deferred = services.$q.defer(), promise = deferred.promise; options = options || {}; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isString(id) && !utils.isNumber(id)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } })); } else if (!utils.isObject(options)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } })); } else if (!(id in services.store[resourceName].index)) { deferred.reject(new errors.RuntimeError(errorPrefix + 'id: "' + id + '" not found!')); } else { var resource = services.store[resourceName], _this = this; promise = promise .then(function (attrs) { return services.$q.promisify(resource.beforeValidate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.validate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.afterValidate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.beforeUpdate)(resourceName, attrs); }) .then(function (attrs) { return services.adapters[resource.defaultAdapter].PUT(utils.makePath(resource.baseUrl, resource.endpoint, id), attrs, null); }) .then(function (data) { return services.$q.promisify(resource.afterUpdate)(resourceName, data); }) .then(function (data) { var saved = _this.inject(resource.name, data, options); resource.previous_attributes[id] = utils.deepMixIn({}, data); resource.saved[id] = utils.updateTimestamp(resource.saved[id]); return saved; }); deferred.resolve(resource.index[id]); } return promise; } module.exports = save; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],36:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), HttpAdapter = require('HttpAdapter'), configErrorPrefix = 'DSProvider.config(options): ', registerAdapterErrorPrefix = 'DSProvider.registerAdapter(name, adapter): '; /** * @doc method * @id DSProvider.methods:config * @name config * @description * Configure the DS service. * * ## Signature: * ```js * DSProvider.config(options) * ``` * * ## Example: * ```js * DSProvider.config({ * baseUrl: 'http://myapp.com/api', * idAttribute: '_id', * validate: function (resourceName, attrs, cb) { * console.log('looks good to me'); * cb(null, attrs); * } * }); * ``` * * ## Throws: * * - `{IllegalArgumentError}` * * @param {object} options Global configuration for the data store. Properties: * - `{string=}` - `baseUrl` - The default base url to be used by the data store. Can be overridden via `DS.defineResource`. * - `{string=}` - `idAttribute` - The default property that specifies the primary key of an object. Default: `"id"`. * - `{function=}` - `beforeValidate` - Global lifecycle hook. Signature: `beforeValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `validate` - Global lifecycle hook. Signature: `validate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterValidate` - Global lifecycle hook. Signature: `afterValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeCreate` - Global lifecycle hook. Signature: `beforeCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterCreate` - Global lifecycle hook. Signature: `afterCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeUpdate` - Global lifecycle hook. Signature: `beforeUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterUpdate` - Global lifecycle hook. Signature: `afterUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeDestroy` - Global lifecycle hook. Signature: `beforeDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterDestroy` - Global lifecycle hook. Signature: `afterDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. */ function config(options) { options = options || {}; if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options: Must be an object!', { actual: typeof options, expected: 'object' }); } else if ('baseUrl' in options && !utils.isString(options.baseUrl)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.baseUrl: Must be a string!', { baseUrl: { actual: typeof options.baseUrl, expected: 'string' } }); } else if ('idAttribute' in options && !utils.isString(options.idAttribute)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.idAttribute: Must be a string!', { idAttribute: { actual: typeof options.idAttribute, expected: 'string' } }); } else if ('mergeStrategy' in options && !utils.isString(options.mergeStrategy)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.mergeStrategy: Must be a string!', { mergeStrategy: { actual: typeof options.mergeStrategy, expected: 'string' } }); } else if ('beforeValidate' in options && !utils.isFunction(options.beforeValidate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.beforeValidate: Must be a function!', { beforeValidate: { actual: typeof options.beforeValidate, expected: 'function' } }); } else if ('validate' in options && !utils.isFunction(options.validate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.validate: Must be a function!', { validate: { actual: typeof options.validate, expected: 'function' } }); } else if ('afterValidate' in options && !utils.isFunction(options.afterValidate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.afterValidate: Must be a function!', { afterValidate: { actual: typeof options.afterValidate, expected: 'function' } }); } else if ('beforeCreate' in options && !utils.isFunction(options.beforeCreate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.beforeCreate: Must be a function!', { beforeCreate: { actual: typeof options.beforeCreate, expected: 'function' } }); } else if ('afterCreate' in options && !utils.isFunction(options.afterCreate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.afterCreate: Must be a function!', { afterCreate: { actual: typeof options.afterCreate, expected: 'function' } }); } else if ('beforeUpdate' in options && !utils.isFunction(options.beforeUpdate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.beforeUpdate: Must be a function!', { beforeUpdate: { actual: typeof options.beforeUpdate, expected: 'function' } }); } else if ('afterUpdate' in options && !utils.isFunction(options.afterUpdate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.afterUpdate: Must be a function!', { afterUpdate: { actual: typeof options.afterUpdate, expected: 'function' } }); } else if ('beforeDestroy' in options && !utils.isFunction(options.beforeDestroy)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.beforeDestroy: Must be a function!', { beforeDestroy: { actual: typeof options.beforeDestroy, expected: 'function' } }); } else if ('afterDestroy' in options && !utils.isFunction(options.afterDestroy)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.afterDestroy: Must be a function!', { afterDestroy: { actual: typeof options.afterDestroy, expected: 'function' } }); } else if ('defaultAdapter' in options && !utils.isString(options.defaultAdapter)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.defaultAdapter: Must be a function!', { defaultAdapter: { actual: typeof options.defaultAdapter, expected: 'string' } }); } services.config = new services.BaseConfig(options); } /** * @doc method * @id DSProvider.methods:registerAdapter * @name registerAdapter * @description * Register a new adapter. * * ## Signature: * ```js * DSProvider.registerAdapter(name, adapter); * ``` * * ## Example: * ```js * DSProvider.registerAdapter('IndexedDBAdapter', {...}); * ``` * * ## Throws: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * * @param {string} name The name of the new adapter. * @param {object} adapter New adapter. */ function registerAdapter(name, adapter) { if (!utils.isString(name)) { throw new errors.IllegalArgumentError(registerAdapterErrorPrefix + 'name: Must be a string!', { actual: typeof name, expected: 'string' }); } else if (!utils.isObject(adapter)) { throw new errors.IllegalArgumentError(registerAdapterErrorPrefix + 'adapter: Must be an object!', { actual: typeof adapter, expected: 'object' }); } else if (services.adapters[name]) { throw new errors.RuntimeError(registerAdapterErrorPrefix + name + ' is already registered!'); } services.adapters[name] = adapter; } /** * @doc interface * @id DSProvider * @name DSProvider */ function DSProvider() { /** * @doc method * @id DSProvider.methods:config * @name config * @methodOf DSProvider * @description * See [DSProvider.config](/documentation/api/api/DSProvider.methods:config). */ this.config = config; config({}); /** * @doc method * @id DSProvider.methods:registerAdapter * @name config * @methodOf DSProvider * @description * See [DSProvider.registerAdapter](/documentation/api/api/DSProvider.methods:registerAdapter). */ this.registerAdapter = registerAdapter; this.$get = ['$rootScope', '$log', '$http', '$q', function ($rootScope, $log, $http, $q) { services.$rootScope = $rootScope; services.$log = $log; services.$http = $http; services.$q = $q; services.store = {}; services.adapters = {}; registerAdapter('HttpAdapter', HttpAdapter); /** * @doc interface * @id DS * @name DS * @description * Data store */ var DS = { HttpAdapter: HttpAdapter, errors: errors }; utils.deepMixIn(DS, require('./sync_methods')); utils.deepMixIn(DS, require('./async_methods')); utils.deepFreeze(DS); var $dirtyCheckScope = $rootScope.$new(); $dirtyCheckScope.$watch(function () { // Throttle angular-data's digest loop to tenths of a second return new Date().getTime() / 100 | 0; }, function () { DS.digest(); }); return DS; }]; } module.exports = DSProvider; },{"./async_methods":33,"./sync_methods":46,"HttpAdapter":"clHM+W","errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],"cX8q+p":[function(require,module,exports){ function lifecycleNoop(resourceName, attrs, cb) { cb(null, attrs); } var services = module.exports = { store: {}, BaseConfig: function (options) { if ('idAttribute' in options) { this.idAttribute = options.idAttribute; } if ('baseUrl' in options) { this.baseUrl = options.baseUrl; } if ('beforeValidate' in options) { this.beforeValidate = options.beforeValidate; } if ('validate' in options) { this.validate = options.validate; } if ('afterValidate' in options) { this.afterValidate = options.afterValidate; } if ('beforeCreate' in options) { this.beforeCreate = options.beforeCreate; } if ('afterCreate' in options) { this.afterCreate = options.afterCreate; } if ('beforeUpdate' in options) { this.beforeUpdate = options.beforeUpdate; } if ('afterUpdate' in options) { this.afterUpdate = options.afterUpdate; } if ('beforeDestroy' in options) { this.beforeDestroy = options.beforeDestroy; } if ('afterDestroy' in options) { this.afterDestroy = options.afterDestroy; } if ('defaultAdapter' in options) { this.defaultAdapter = options.defaultAdapter; } } }; services.BaseConfig.prototype.idAttribute = 'id'; services.BaseConfig.prototype.defaultAdapter = 'HttpAdapter'; services.BaseConfig.prototype.baseUrl = ''; services.BaseConfig.prototype.endpoint = ''; services.BaseConfig.prototype.beforeValidate = lifecycleNoop; services.BaseConfig.prototype.validate = lifecycleNoop; services.BaseConfig.prototype.afterValidate = lifecycleNoop; services.BaseConfig.prototype.beforeCreate = lifecycleNoop; services.BaseConfig.prototype.afterCreate = lifecycleNoop; services.BaseConfig.prototype.beforeUpdate = lifecycleNoop; services.BaseConfig.prototype.afterUpdate = lifecycleNoop; services.BaseConfig.prototype.beforeDestroy = lifecycleNoop; services.BaseConfig.prototype.afterDestroy = lifecycleNoop; },{}],"services":[function(require,module,exports){ module.exports=require('cX8q+p'); },{}],39:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.changes(resourceName, id): '; /** * @doc method * @id DS.sync_methods:changes * @name changes * @description * Synchronously return the changes object of the item of the type specified by `resourceName` that has the primary key * specified by `id`. This object represents the diff between the item in its current state and the state of the item * the last time it was saved via an async adapter. * * ## Signature: * ```js * DS.changes(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * DS.changes('document', 5); // {...} Object describing changes * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item of the changes to retrieve. * @returns {object} The changes of the item of the type specified by `resourceName` with the primary key specified by `id`. */ function changes(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { return angular.copy(services.store[resourceName].changes[id]); } catch (err) { throw new errors.UnhandledError(err); } } module.exports = changes; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],40:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.defineResource(definition): '; function Resource(options) { services.BaseConfig.apply(this, [options]); if ('name' in options) { this.name = options.name; } if ('endpoint' in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } this.collection = []; this.completedQueries = {}; this.pendingQueries = {}; this.index = {}; this.modified = {}; this.changes = {}; this.previous_attributes = {}; this.saved = {}; this.observers = {}; this.collectionModified = 0; } Resource.prototype = services.config; /** * @doc method * @id DS.sync_methods:defineResource * @name defineResource * @description * Define a resource and register it with the data store. * * ## Signature: * ```js * DS.defineResource(definition) * ``` * * ## Example: * * ```js * DS.defineResource({ * name: 'document', * idAttribute: '_id', * endpoint: '/documents * baseUrl: 'http://myapp.com/api', * beforeDestroy: function (resourceName attrs, cb) { * console.log('looks good to me'); * cb(null, attrs); * } * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string|object} definition Name of resource or resource definition object: Properties: * * - `{string}` - `name` - The name by which this resource will be identified. * - `{string="id"}` - `idAttribute` - The attribute that specifies the primary key for this resource. * - `{string=}` - `endpoint` - The attribute that specifies the primary key for this resource. Default is the value of `name`. * - `{string=}` - `baseUrl` - The url relative to which all AJAX requests will be made. * - `{function=}` - `beforeValidate` - Lifecycle hook. Overrides global. Signature: `beforeValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `validate` - Lifecycle hook. Overrides global. Signature: `validate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterValidate` - Lifecycle hook. Overrides global. Signature: `afterValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeCreate` - Lifecycle hook. Overrides global. Signature: `beforeCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterCreate` - Lifecycle hook. Overrides global. Signature: `afterCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeUpdate` - Lifecycle hook. Overrides global. Signature: `beforeUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterUpdate` - Lifecycle hook. Overrides global. Signature: `afterUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeDestroy` - Lifecycle hook. Overrides global. Signature: `beforeDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterDestroy` - Lifecycle hook. Overrides global. Signature: `afterDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. */ function defineResource(definition) { if (utils.isString(definition)) { definition = { name: definition }; } if (!utils.isObject(definition)) { throw new errors.IllegalArgumentError(errorPrefix + 'definition: Must be an object!', { definition: { actual: typeof definition, expected: 'object' } }); } else if (!utils.isString(definition.name)) { throw new errors.IllegalArgumentError(errorPrefix + 'definition.name: Must be a string!', { definition: { name: { actual: typeof definition.name, expected: 'string' } } }); } else if (definition.idAttribute && !utils.isString(definition.idAttribute)) { throw new errors.IllegalArgumentError(errorPrefix + 'definition.idAttribute: Must be a string!', { definition: { idAttribute: { actual: typeof definition.idAttribute, expected: 'string' } } }); } else if (definition.endpoint && !utils.isString(definition.endpoint)) { throw new errors.IllegalArgumentError(errorPrefix + 'definition.endpoint: Must be a string!', { definition: { endpoint: { actual: typeof definition.endpoint, expected: 'string' } } }); } else if (services.store[definition.name]) { throw new errors.RuntimeError(errorPrefix + definition.name + ' is already registered!'); } try { services.store[definition.name] = new Resource(definition); } catch (err) { delete services.store[definition.name]; throw new errors.UnhandledError(err); } } module.exports = defineResource; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],41:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), observe = require('observejs'); /** * @doc method * @id DS.sync_methods:digest * @name digest * @description * Trigger a digest loop that checks for changes and updates the `lastModified` timestamp if an object has changed. * Anything $watching `DS.lastModified(...)` will detect the updated timestamp and execute the callback function. * * ## Signature: * ```js * DS.digest() * ``` * * ## Example: * * ```js * Works like $scope.$apply() * ``` * * ## Throws * * - `{UnhandledError}` */ function digest() { try { if (!services.$rootScope.$$phase) { services.$rootScope.$apply(function () { observe.Platform.performMicrotaskCheckpoint(); }); } else { observe.Platform.performMicrotaskCheckpoint(); } } catch (err) { throw new errors.UnhandledError(err); } } module.exports = digest; },{"errors":"hIh4e1","observejs":"u+GZEJ","services":"cX8q+p","utils":"uE/lJt"}],42:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.eject(resourceName, id): '; function _eject(resource, id) { if (id) { var found = false; for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][resource.idAttribute] == id) { found = true; break; } } if (found) { resource.collection.splice(i, 1); resource.observers[id].close(); delete resource.observers[id]; delete resource.index[id]; delete resource.changes[id]; delete resource.previous_attributes[id]; delete resource.modified[id]; delete resource.saved[id]; } } else { resource.collection = []; resource.index = {}; resource.modified = {}; resource.saved = {}; resource.changes = {}; resource.previous_attributes = {}; } resource.collectionModified = utils.updateTimestamp(resource.collectionModified); } /** * @doc method * @id DS.sync_methods:eject * @name eject * @description * Eject the item of the specified type that has the given primary key from the data store. If no primary key is * provided, eject all items of the specified type from the data store. Ejection only removes items from the data store * and does not attempt to delete items on the server. * * ## Signature: * ```js * DS.eject(resourceName[, id]) * ``` * * ## Examples: * * ```js * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * * DS.eject('document', 45); * * DS.get('document', 45); // undefined * ``` * * Eject all items of the specified type from the data store. * * ```js * DS.filter('document'); // [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ] * * DS.eject('document'); * * DS.filter('document'); // [ ] * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number=} id The primary key of the item to eject. */ function eject(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (id && !utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { if (!services.$rootScope.$$phase) { services.$rootScope.$apply(function () { _eject(services.store[resourceName], id); }); } else { _eject(services.store[resourceName], id); } } catch (err) { throw new errors.UnhandledError(err); } } module.exports = eject; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],43:[function(require,module,exports){ /* jshint loopfunc: true */ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.filter(resourceName, params[, options]): '; /** * @doc method * @id DS.sync_methods:filter * @name filter * @description * Synchronously filter items in the data store of the type specified by `resourceName`. * * ## Signature: * ```js * DS.filter(resourceName, params[, options]) * ``` * * ## Example: * * ```js * TODO: filter(resourceName, params[, options]) example * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is serialized into the query string. Properties: * * - `{object=}` - `query` - The query object by which to filter items of the type specified by `resourceName`. Properties: * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{skip=}` - `skip` - Skip clause. * - `{orderBy=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Properties: * - `{boolean=}` - `loadFromServer` - Send the query to server if it has not been sent yet. Default: `false`. * - `{string=}` - `mergeStrategy` - If `findAll` is called, specify the merge strategy that should be used when the new * items are injected into the data store. Default: `"mergeWithExisting"`. * * @returns {array} The filtered collection of items of the type specified by `resourceName`. */ function filter(resourceName, params, options) { options = options || {}; if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isObject(params)) { throw new errors.IllegalArgumentError(errorPrefix + 'params: Must be an object!', { params: { actual: typeof params, expected: 'object' } }); } else if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } }); } try { var resource = services.store[resourceName]; // Protect against null params.query = params.query || {}; var queryHash = utils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started this.findAll(resourceName, params, options); } } // The query has been completed, so hit the cache with the query var filtered = utils.filter(resource.collection, function (value) { var keep = true; // Apply 'where' clauses if (params.query.where) { if (!utils.isObject(params.query.where)) { throw new errors.IllegalArgumentError(errorPrefix + 'params.query.where: Must be an object!', { params: { query: { where: { actual: typeof params.query.where, expected: 'object' } } } }); } utils.forOwn(params.query.where, function (value2, key2) { if (utils.isString(value2)) { value2 = { '===': value2 }; } if ('==' in value2) { keep = keep && (value[key2] == value2['==']); } else if ('===' in value2) { keep = keep && (value[key2] === value2['===']); } else if ('!=' in value2) { keep = keep && (value[key2] != value2['!=']); } else if ('>' in value2) { keep = keep && (value[key2] > value2['>']); } else if ('>=' in value2) { keep = keep && (value[key2] >= value2['>=']); } else if ('<' in value2) { keep = keep && (value[key2] < value2['<']); } else if ('<=' in value2) { keep = keep && (value[key2] <= value2['<=']); } else if ('in' in value2) { keep = keep && utils.contains(value2['in'], value[key2]); } }); } return keep; }); // Apply 'orderBy' if (params.query.orderBy) { if (utils.isString(params.query.orderBy)) { params.query.orderBy = [ [params.query.orderBy, 'ASC'] ]; } if (utils.isArray(params.query.orderBy)) { for (var i = 0; i < params.query.orderBy.length; i++) { if (utils.isString(params.query.orderBy[i])) { params.query.orderBy[i] = [params.query.orderBy[i], 'ASC']; } else if (!utils.isArray(params.query.orderBy[i])) { throw new errors.IllegalArgumentError(errorPrefix + 'params.query.orderBy[' + i + ']: Must be a string or an array!', { params: { query: { 'orderBy[i]': { actual: typeof params.query.orderBy[i], expected: 'string|array' } } } }); } filtered = utils.sort(filtered, function (a, b) { var cA = a[params.query.orderBy[i][0]], cB = b[params.query.orderBy[i][0]]; if (utils.isString(cA)) { cA = utils.upperCase(cA); } if (utils.isString(cB)) { cB = utils.upperCase(cB); } if (params.query.orderBy[i][1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { return 0; } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { return 0; } } }); } } else { throw new errors.IllegalArgumentError(errorPrefix + 'params.query.orderBy: Must be a string or an array!', { params: { query: { orderBy: { actual: typeof params.query.orderBy, expected: 'string|array' } } } }); } } // Apply 'limit' and 'skip' if (utils.isNumber(params.query.limit) && utils.isNumber(params.query.skip)) { filtered = utils.slice(filtered, params.query.skip, params.query.skip + params.query.limit); } else if (utils.isNumber(params.query.limit)) { filtered = utils.slice(filtered, 0, params.query.limit); } else if (utils.isNumber(params.query.skip)) { filtered = utils.slice(filtered, params.query.skip); } return filtered; } catch (err) { if (err instanceof errors.IllegalArgumentError) { throw err; } else { throw new errors.UnhandledError(err); } } } module.exports = filter; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],44:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.get(resourceName, id[, options]): '; /** * @doc method * @id DS.sync_methods:get * @name get * @description * Synchronously return the resource with the given id. The data store will forward the request to the server if the * item is not in the cache and `loadFromServer` is set to `true` in the options hash. * * ## Signature: * ```js * DS.get(resourceName, id[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5'); // { author: 'John Anderson', id: 5 } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Properties: * - `{boolean=}` - `loadFromServer` - Send the query to server if it has not been sent yet. Default: `false`. * @returns {object} The item of the type specified by `resourceName` with the primary key specified by `id`. */ function get(resourceName, id, options) { options = options || {}; if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } else if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } }); } try { // cache miss, request resource from server if (!(id in services.store[resourceName].index) && options.loadFromServer) { this.find(resourceName, id).then(null, function (err) { throw err; }); } // return resource from cache return services.store[resourceName].index[id]; } catch (err) { throw new errors.UnhandledError(err); } } module.exports = get; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],45:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.hasChanges(resourceName, id): '; function diffIsEmpty(diff) { return !(utils.isEmpty(diff.added) && utils.isEmpty(diff.removed) && utils.isEmpty(diff.changed)); } /** * @doc method * @id DS.sync_methods:hasChanges * @name hasChanges * @description * Synchronously return whether object of the item of the type specified by `resourceName` that has the primary key * specified by `id` has changes. * * ## Signature: * ```js * DS.hasChanges(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * DS.hasChanges('document', 5); // true * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item. * @returns {boolean} Whether the item of the type specified by `resourceName` with the primary key specified by `id` has changes. */ function hasChanges(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { // return resource from cache if (id in services.store[resourceName].changes) { return diffIsEmpty(services.store[resourceName].changes[id]); } else { return false; } } catch (err) { throw new errors.UnhandledError(err); } } module.exports = hasChanges; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],46:[function(require,module,exports){ module.exports = { /** * @doc method * @id DS.sync_methods:defineResource * @name defineResource * @methodOf DS * @description * See [DS.defineResource](/documentation/api/api/DS.sync_methods:defineResource). */ defineResource: require('./defineResource'), /** * @doc method * @id DS.sync_methods:eject * @name eject * @methodOf DS * @description * See [DS.eject](/documentation/api/api/DS.sync_methods:eject). */ eject: require('./eject'), /** * @doc method * @id DS.sync_methods:filter * @name filter * @methodOf DS * @description * See [DS.filter](/documentation/api/api/DS.sync_methods:filter). */ filter: require('./filter'), /** * @doc method * @id DS.sync_methods:get * @name get * @methodOf DS * @description * See [DS.get](/documentation/api/api/DS.sync_methods:get). */ get: require('./get'), /** * @doc method * @id DS.sync_methods:inject * @name inject * @description * See [DS.inject](/documentation/api/api/DS.sync_methods:inject). */ inject: require('./inject'), /** * @doc method * @id DS.sync_methods:lastModified * @name lastModified * @methodOf DS * @description * See [DS.lastModified](/documentation/api/api/DS.sync_methods:lastModified). */ lastModified: require('./lastModified'), /** * @doc method * @id DS.sync_methods:lastSaved * @name lastSaved * @methodOf DS * @description * See [DS.lastSaved](/documentation/api/api/DS.sync_methods:lastSaved). */ lastSaved: require('./lastSaved'), /** * @doc method * @id DS.sync_methods:digest * @name digest * @methodOf DS * @description * See [DS.digest](/documentation/api/api/DS.sync_methods:digest). */ digest: require('./digest'), /** * @doc method * @id DS.sync_methods:changes * @name changes * @methodOf DS * @description * See [DS.changes](/documentation/api/api/DS.sync_methods:changes). */ changes: require('./changes'), /** * @doc method * @id DS.sync_methods:previous * @name previous * @methodOf DS * @description * See [DS.previous](/documentation/api/api/DS.sync_methods:previous). */ previous: require('./previous'), /** * @doc method * @id DS.sync_methods:hasChanges * @name hasChanges * @methodOf DS * @description * See [DS.hasChanges](/documentation/api/api/DS.sync_methods:hasChanges). */ hasChanges: require('./hasChanges') }; },{"./changes":39,"./defineResource":40,"./digest":41,"./eject":42,"./filter":43,"./get":44,"./hasChanges":45,"./inject":47,"./lastModified":48,"./lastSaved":49,"./previous":50}],47:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), observe = require('observejs'), errorPrefix = 'DS.inject(resourceName, attrs[, options]): '; function _inject(resource, attrs) { var _this = this; function _react(added, removed, changed, getOldValueFn) { try { var innerId = getOldValueFn(resource.idAttribute); resource.changes[innerId] = utils.diffObjectFromOldObject(resource.index[innerId], resource.previous_attributes[innerId]); resource.modified[innerId] = utils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = utils.updateTimestamp(resource.collectionModified); if (resource.idAttribute in changed) { services.$log.error('Doh! You just changed the primary key of an object! ' + 'I don\'t know how to handle this yet, so your data for the "' + resource.name + '" resource is now in an undefined (probably broken) state.'); } } catch (err) { throw new errors.UnhandledError(err); } } if (utils.isArray(attrs)) { for (var i = 0; i < attrs.length; i++) { _inject.call(_this, resource, attrs[i]); } } else { if (!(resource.idAttribute in attrs)) { throw new errors.RuntimeError(errorPrefix + 'attrs: Must contain the property specified by `idAttribute`!'); } else { var id = attrs[resource.idAttribute]; if (!(id in resource.index)) { resource.index[id] = {}; resource.previous_attributes[id] = {}; utils.deepMixIn(resource.index[id], attrs); utils.deepMixIn(resource.previous_attributes[id], attrs); resource.collection.push(resource.index[id]); resource.observers[id] = new observe.ObjectObserver(resource.index[id], _react); _react({}, {}, {}, function () { return id; }); } else { utils.deepMixIn(resource.index[id], attrs); resource.observers[id].deliver(); } } } } /** * @doc method * @id DS.sync_methods:inject * @name inject * @description * Inject the given item into the data store as the specified type. If `attrs` is an array, inject each item into the * data store. Injecting an item into the data store does not save it to the server. * * ## Signature: * ```js * DS.inject(resourceName, attrs[, options]) * ``` * * ## Examples: * * ```js * DS.get('document', 45); // undefined * * DS.inject('document', { title: 'How to Cook', id: 45 }); * * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * ``` * * Inject a collection into the data store: * * ```js * DS.filter('document'); // [ ] * * DS.inject('document', [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ]); * * DS.filter('document'); // [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ] * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object|array} attrs The item or collection of items to inject into the data store. * @param {object=} options Optional configuration. Properties: * - `{string=}` - `mergeStrategy` - Specify the merge strategy to use if the item is already in the cache. Default: `"mergeWithExisting"`. * @returns {object|array} A reference to the item that was injected into the data store or an array of references to * the items that were injected into the data store. */ function inject(resourceName, attrs, options) { options = options || {}; if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isObject(attrs) && !utils.isArray(attrs)) { throw new errors.IllegalArgumentError(errorPrefix + 'attrs: Must be an object or an array!', { attrs: { actual: typeof attrs, expected: 'object|array' } }); } else if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } }); } var resource = services.store[resourceName], _this = this; try { if (!services.$rootScope.$$phase) { services.$rootScope.$apply(function () { _inject.apply(_this, [services.store[resourceName], attrs]); }); } else { _inject.apply(_this, [services.store[resourceName], attrs]); } return attrs; } catch (err) { if (!(err instanceof errors.RuntimeError)) { throw new errors.UnhandledError(err); } else { throw err; } } } module.exports = inject; },{"errors":"hIh4e1","observejs":"u+GZEJ","services":"cX8q+p","utils":"uE/lJt"}],48:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.lastModified(resourceName[, id]): '; /** * @doc method * @id DS.sync_methods:lastModified * @name lastModified * @description * Return the timestamp of the last time either the collection for `resourceName` or the item of type `resourceName` * with the given primary key was modified. * * ## Signature: * ```js * DS.lastModified(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.lastModified('document', 5); // undefined * * DS.find('document', 5).then(function (document) { * DS.lastModified('document', 5); // 1234235825494 * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number=} id The primary key of the item to remove. * @returns {number} The timestamp of the last time either the collection for `resourceName` or the item of type * `resourceName` with the given primary key was modified. */ function lastModified(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (id && !utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { if (id) { if (!(id in services.store[resourceName].modified)) { services.store[resourceName].modified[id] = 0; } return services.store[resourceName].modified[id]; } return services.store[resourceName].collectionModified; } catch (err) { throw new errors.UnhandledError(err); } } module.exports = lastModified; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],49:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.lastSaved(resourceName[, id]): '; /** * @doc method * @id DS.sync_methods:lastSaved * @name lastSaved * @description * Return the timestamp of the last time either the collection for `resourceName` or the item of type `resourceName` * with the given primary key was saved via an async adapter. * * ## Signature: * ```js * DS.lastSaved(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.lastModified('document', 5); // undefined * DS.lastSaved('document', 5); // undefined * * DS.find('document', 5).then(function (document) { * DS.lastModified('document', 5); // 1234235825494 * DS.lastSaved('document', 5); // 1234235825494 * * document.author = 'Sally'; * * DS.lastModified('document', 5); // 1234304985344 - something different * DS.lastSaved('document', 5); // 1234235825494 - still the same * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number=} id The primary key of the item to remove. * @returns {number} The timestamp of the last time either the collection for `resourceName` or the item of type * `resourceName` with the given primary key was modified. */ function lastSaved(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (id && !utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { if (id) { if (!(id in services.store[resourceName].saved)) { services.store[resourceName].saved[id] = 0; } return services.store[resourceName].saved[id]; } return services.store[resourceName].collectionModified; } catch (err) { throw new errors.UnhandledError(err); } } module.exports = lastSaved; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],50:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.previous(resourceName, id): '; /** * @doc method * @id DS.sync_methods:previous * @name previous * @description * Synchronously return the previous attributes of the item of the type specified by `resourceName` that has the primary key * specified by `id`. This object represents the state of the item the last time it was saved via an async adapter. * * ## Signature: * ```js * DS.previous(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * d; // { author: 'Sally', id: 5 } * * DS.previous('document', 5); // { author: 'John Anderson', id: 5 } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item whose previous attributes are to be retrieved. * @returns {object} The previous attributes of the item of the type specified by `resourceName` with the primary key specified by `id`. */ function previous(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { // return resource from cache return angular.copy(services.store[resourceName].previous_attributes[id]); } catch (err) { throw new errors.UnhandledError(err); } } module.exports = previous; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],"errors":[function(require,module,exports){ module.exports=require('hIh4e1'); },{}],"hIh4e1":[function(require,module,exports){ /** * @doc function * @id errors.types:UnhandledError * @name UnhandledError * @description Error that is thrown/returned when Reheat encounters an uncaught/unknown exception. * @param {Error} error The originally thrown error. * @returns {UnhandledError} A new instance of `UnhandledError`. */ function UnhandledError(error) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } error = error || {}; /** * @doc property * @id errors.types:UnhandledError.type * @name type * @propertyOf errors.types:UnhandledError * @description Name of error type. Default: `"UnhandledError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:UnhandledError.originalError * @name originalError * @propertyOf errors.types:UnhandledError * @description A reference to the original error that was thrown. */ this.originalError = error; /** * @doc property * @id errors.types:UnhandledError.message * @name message * @propertyOf errors.types:UnhandledError * @description Message and stack trace. Same as `UnhandledError#stack`. */ this.message = 'UnhandledError: This is an uncaught exception. Please consider submitting an issue at https://github.com/jmdobry/angular-data/issues.\n\n' + 'Original Uncaught Exception:\n' + (error.stack ? error.stack.toString() : error.stack); /** * @doc property * @id errors.types:UnhandledError.stack * @name stack * @propertyOf errors.types:UnhandledError * @description Message and stack trace. Same as `UnhandledError#message`. */ this.stack = this.message; } UnhandledError.prototype = Object.create(Error.prototype); UnhandledError.prototype.constructor = UnhandledError; /** * @doc function * @id errors.types:IllegalArgumentError * @name IllegalArgumentError * @description Error that is thrown/returned when a caller does not honor the pre-conditions of a method/function. * @param {string=} message Error message. Default: `"Illegal Argument!"`. * @param {object=} errors Object containing information about the error. * @returns {IllegalArgumentError} A new instance of `IllegalArgumentError`. */ function IllegalArgumentError(message, errors) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:IllegalArgumentError.type * @name type * @propertyOf errors.types:IllegalArgumentError * @description Name of error type. Default: `"IllegalArgumentError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:IllegalArgumentError.errors * @name errors * @propertyOf errors.types:IllegalArgumentError * @description Object containing information about the error. */ this.errors = errors || {}; /** * @doc property * @id errors.types:IllegalArgumentError.message * @name message * @propertyOf errors.types:IllegalArgumentError * @description Error message. Default: `"Illegal Argument!"`. */ this.message = message || 'Illegal Argument!'; } IllegalArgumentError.prototype = Object.create(Error.prototype); IllegalArgumentError.prototype.constructor = IllegalArgumentError; /** * @doc function * @id errors.types:ValidationError * @name ValidationError * @description Error that is thrown/returned when validation of a schema fails. * @param {string=} message Error message. Default: `"Validation Error!"`. * @param {object=} errors Object containing information about the error. * @returns {ValidationError} A new instance of `ValidationError`. */ function ValidationError(message, errors) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:ValidationError.type * @name type * @propertyOf errors.types:ValidationError * @description Name of error type. Default: `"ValidationError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:ValidationError.errors * @name errors * @propertyOf errors.types:ValidationError * @description Object containing information about the error. */ this.errors = errors || {}; /** * @doc property * @id errors.types:ValidationError.message * @name message * @propertyOf errors.types:ValidationError * @description Error message. Default: `"Validation Error!"`. */ this.message = message || 'Validation Error!'; } ValidationError.prototype = Object.create(Error.prototype); ValidationError.prototype.constructor = ValidationError; /** * @doc function * @id errors.types:RuntimeError * @name RuntimeError * @description Error that is thrown/returned for invalid state during runtime. * @param {string=} message Error message. Default: `"Runtime Error!"`. * @param {object=} errors Object containing information about the error. * @returns {RuntimeError} A new instance of `RuntimeError`. */ function RuntimeError(message, errors) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:RuntimeError.type * @name type * @propertyOf errors.types:RuntimeError * @description Name of error type. Default: `"RuntimeError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:RuntimeError.errors * @name errors * @propertyOf errors.types:RuntimeError * @description Object containing information about the error. */ this.errors = errors || {}; /** * @doc property * @id errors.types:RuntimeError.message * @name message * @propertyOf errors.types:RuntimeError * @description Error message. Default: `"Runtime Error!"`. */ this.message = message || 'RuntimeError Error!'; } RuntimeError.prototype = Object.create(Error.prototype); RuntimeError.prototype.constructor = RuntimeError; /** * @doc interface * @id errors * @name angular-data error types * @description * `UnhandledError`, `IllegalArgumentError`, `RuntimeError` and `ValidationError`. * * References to the constructor functions of these errors can be found at `DS.errors`. */ module.exports = { UnhandledError: UnhandledError, IllegalArgumentError: IllegalArgumentError, ValidationError: ValidationError, RuntimeError: RuntimeError }; },{}],53:[function(require,module,exports){ (function (window, angular, undefined) { 'use strict'; // angular.module('jmdobry.binary-heap', []); // // /** // * @doc interface // * @id BinaryHeapProvider // * @name BinaryHeapProvider // */ // function BinaryHeapProvider() { // // var defaults = require('./binaryHeap/defaults'); // // /** // * @doc method // * @id BinaryHeapProvider.methods:setDefaultWeightFunction // * @name setDefaultWeightFunction // * @param {function} weightFunc New default weight function. // */ // function setDefaultWeightFunction(weightFunc) { // if (!angular.isFunction(weightFunc)) { // throw new Error('BinaryHeapProvider.setDefaultWeightFunction(weightFunc): weightFunc: Must be a function!'); // } // defaults.userProvidedDefaultWeightFunc = weightFunc; // } // // /** // * @doc method // * @id BinaryHeapProvider.methods:setDefaultWeightFunction // * @name setDefaultWeightFunction // * @methodOf BinaryHeapProvider // * @param {function} weightFunc New default weight function. // */ // this.setDefaultWeightFunction = setDefaultWeightFunction; // // this.$get = function () { // return require('./binaryHeap'); // }; // } // angular.module('jmdobry.binary-heap').provider('BinaryHeap', BinaryHeapProvider); angular.module('jmdobry.angular-data', ['ng'/*, 'jmdobry.binary-heap'*/]).config(['$provide', function ($provide) { $provide.decorator('$q', function ($delegate) { // do whatever you you want $delegate.promisify = function (fn, target) { var _this = this; return function () { var deferred = _this.defer(), args = Array.prototype.slice.apply(arguments); args.push(function (err, result) { if (err) { deferred.reject(err); } else { deferred.resolve(result); } }); try { fn.apply(target || this, args); } catch (err) { deferred.reject(err); } return deferred.promise; }; }; return $delegate; }); }]); angular.module('jmdobry.angular-data').provider('DS', require('./datastore')); })(window, window.angular); },{"./datastore":36}],"uE/lJt":[function(require,module,exports){ module.exports = { isString: angular.isString, isArray: angular.isArray, isObject: angular.isObject, isNumber: angular.isNumber, isFunction: angular.isFunction, isEmpty: require('mout/lang/isEmpty'), toJson: angular.toJson, makePath: require('mout/string/makePath'), upperCase: require('mout/string/upperCase'), deepMixIn: require('mout/object/deepMixIn'), forOwn: require('mout/object/forOwn'), contains: require('mout/array/contains'), filter: require('mout/array/filter'), toLookup: require('mout/array/toLookup'), slice: require('mout/array/slice'), sort: require('mout/array/sort'), updateTimestamp: function (timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, deepFreeze: function deepFreeze(o) { if (typeof Object.freeze === 'function') { var prop, propKey; Object.freeze(o); // First freeze the object. for (propKey in o) { prop = o[propKey]; if (!o.hasOwnProperty(propKey) || typeof prop !== 'object' || Object.isFrozen(prop)) { // If the object is on the prototype, not an object, or is already frozen, // skip it. Note that this might leave an unfrozen reference somewhere in the // object if there is an already frozen object containing an unfrozen object. continue; } deepFreeze(prop); // Recursively call deepFreeze. } } }, diffObjectFromOldObject: function (object, oldObject) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop2 in object) { if (prop2 in oldObject) continue; added[prop2] = object[prop2]; } return { added: added, removed: removed, changed: changed }; } }; },{"mout/array/contains":3,"mout/array/filter":4,"mout/array/slice":7,"mout/array/sort":8,"mout/array/toLookup":9,"mout/lang/isEmpty":14,"mout/object/deepMixIn":21,"mout/object/forOwn":23,"mout/string/makePath":25,"mout/string/upperCase":26}],"utils":[function(require,module,exports){ module.exports=require('uE/lJt'); },{}]},{},[53])
src/App.js
chandlera/react-hot-boilerplate
import React, { Component } from 'react'; import Board from './Board'; export default class App extends Component { render() { return ( <Board knightPosition={[4, 7]} /> ); } }
src/logs/LogForm.js
carab/Pinarium
import React from 'react'; import {observer} from 'mobx-react-lite'; import {Trans, useTranslation} from 'react-i18next/hooks'; import {makeStyles} from '@material-ui/styles'; import InputAdornment from '@material-ui/core/InputAdornment'; import FieldRow from '../form/FieldRow'; import TextField from '../form/TextField'; import AutocompleteField from '../form/AutocompleteField'; import DateField from '../form/DateFieldPicker'; import CellarField from '../form/CellarField'; import SelectField from '../form/SelectField'; import { StatusIcon, WhereIcon, WhoIcon, PriceIcon, RatingIcon, CellarIcon, WhyIcon, CommentIcon, } from '../ui/Icons'; import ratings from '../enums/ratings'; import statusesDef from '../enums/statuses'; const useStyles = makeStyles(theme => ({ sm: { flexBasis: '75px', flexGrow: '1', }, md: { flexBasis: '200px', flexGrow: '1', }, xl: { width: '100%', }, })); export default observer(function LogForm({log, statuses, onSave}) { const errors = {}; const classes = useStyles(); const [t] = useTranslation(); function handleChange(value, name) { log[name] = value; } const statusDef = statusesDef.find(status => status.name === log.status); const fields = { when: ( <DateField key="when" label={t('log.when')} name="when" value={log.when} onChange={handleChange} className={classes.md} /> ), where: ( <AutocompleteField key="where" label={t('log.where')} name="where" namespace="where" value={log.where} onChange={handleChange} className={classes.md} InputProps={{ startAdornment: ( <InputAdornment position="start"> <WhereIcon /> </InputAdornment> ), }} /> ), who: ( <AutocompleteField key="who" label={t('log.who')} name="who" namespace="who" value={log.who} onChange={handleChange} className={classes.md} InputProps={{ startAdornment: ( <InputAdornment position="start"> <WhoIcon /> </InputAdornment> ), }} /> ), price: ( <TextField key="price" label={t('log.price')} name="price" value={log.price} onChange={handleChange} className={classes.sm} InputProps={{ startAdornment: ( <InputAdornment position="start"> <PriceIcon /> </InputAdornment> ), }} /> ), rating: ( <SelectField key="rating" label={t('log.rating')} name="rating" value={log.rating} onChange={handleChange} empty={<em>None</em>} options={ratings.map(rating => ({ value: rating, label: rating, }))} className={classes.sm} InputProps={{ startAdornment: ( <InputAdornment position="start"> <RatingIcon /> </InputAdornment> ), }} /> ), cellar: ( <CellarField key="cellar" label={t('log.cellar')} name="cellar" value={log.cellar} required={true} onChange={handleChange} className={classes.md} InputProps={{ startAdornment: ( <InputAdornment position="start"> <CellarIcon /> </InputAdornment> ), }} /> ), why: ( <AutocompleteField key="why" label={t('log.why')} name="why" namespace="why" value={log.why} onChange={handleChange} className={classes.md} InputProps={{ startAdornment: ( <InputAdornment position="start"> <WhyIcon /> </InputAdornment> ), }} /> ), comment: ( <TextField key="comment" label={t('log.comment')} name="comment" value={log.comment} onChange={handleChange} className={classes.xl} InputProps={{ startAdornment: ( <InputAdornment position="start"> <CommentIcon /> </InputAdornment> ), }} /> ), }; return ( <FieldRow> {statuses ? ( <SelectField label={t('log.status')} name="status" value={log.status} required={true} onChange={handleChange} options={statuses.map(status => ({ value: status, label: t(`enum.status.${status}`), }))} className={classes.sm} InputProps={{ startAdornment: ( <InputAdornment position="start"> <StatusIcon /> </InputAdornment> ), }} /> ) : null} {statusDef ? statusDef.fields.map(field => fields[field]) : null} </FieldRow> ); });
client/src/__tests__/components/Dashboard.spec.js
Billmike/More-Recipes
import React from 'react'; import { shallow } from 'enzyme'; import sinon from 'sinon'; import { Dashboard, mapStateToProps } from '../../components/Dashboard'; import { RecipeEdit } from '../../components/RecipeEdit'; import recipes, { FavoritesRecipeProps, recipesLoading } from '../fixtures/recipes'; import auth from '../fixtures/authUser'; import state from '../fixtures/state'; import Loader from '../../components/Loader'; describe('<Dashboard />', () => { const getUserRecipesAction = jest.fn(); const getUserInformation = jest.fn(); it('Should render correctly', () => { const wrapper = shallow(<Dashboard getUserInformation={() => Promise.resolve()} getUserRecipesAction={() => Promise.resolve()} recipes={recipes[0]} user={auth} />); expect(wrapper).toMatchSnapshot(); expect(wrapper.find('div').length).toBe(3); }); it('Should render the RecipeEdit component as a child element', () => { const wrapper = shallow(<Dashboard getUserInformation={() => Promise.resolve()} getUserRecipesAction={() => Promise.resolve()} recipes={FavoritesRecipeProps} user={auth} > <div> <div className="container"> <h2 className="dashboard-h2">Welcome to your Dashboard</h2> <h4 className="dashboard-h4"> My Recipes</h4> <div className="row"> <RecipeEdit recipe={recipes[0]} /> </div> </div> </div> </Dashboard>); }); it('Should render the loader component', () => { const wrapper = shallow(<Dashboard isLoading={recipesLoading} recipes={FavoritesRecipeProps} user={auth} getUserInformation={() => Promise.resolve()} getUserRecipesAction={() => Promise.resolve()} > <Loader /> </Dashboard>); }); it('Should call mapStateToProps', () => { mapStateToProps(state); }); });
src/components/PageWrapper/PageWrapper.js
hahoocn/hahoo-admin
import React from 'react'; import styles from './PageWrapper.css'; class PageWrapper extends React.Component { static propTypes = { children: React.PropTypes.node, } state = {} render() { return ( <div className={styles.pagewrapper}> {this.props.children} <div className={styles.foot} /> </div> ); } } export default PageWrapper;
client/app/components/about.js
Terry-Breen/scrappedideas
import React from 'react'; export default class AboutPage extends React.Component { render(){ return ( <div className="container about-container"> <p>AAA</p> </div> ); } }
ajax/libs/formsy-react/0.6.0/formsy-react.min.js
redmunds/cdnjs
!function t(i,e,n){function s(o,u){if(!e[o]){if(!i[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(r)return r(o,!0);var p=new Error("Cannot find module '"+o+"'");throw p.code="MODULE_NOT_FOUND",p}var h=e[o]={exports:{}};i[o][0].call(h.exports,function(t){var e=i[o][1][t];return s(e?e:t)},h,h.exports,t,i,e,n)}return e[o].exports}for(var r="function"==typeof require&&require,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(t,i){(function(e){var n=e.React||t("react"),s={},r={isValue:function(t){return""!==t},isEmail:function(t){return t.match(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i)},isTrue:function(t){return t===!0},isNumeric:function(t){return t.match(/^-?[0-9]+$/)},isAlpha:function(t){return t.match(/^[a-zA-Z]+$/)},isWords:function(t){return t.match(/^[a-zA-Z\s]+$/)},isSpecialWords:function(t){return t.match(/^[a-zA-Z\s\u00C0-\u017F]+$/)},isLength:function(t,i,e){return void 0!==e?t.length>=i&&t.length<=e:t.length>=i},equals:function(t,i){return t==i}},o=function(t,i,e){var e=e||[];if("object"==typeof t)for(var n in t)o(t[n],i?i+"["+n+"]":n,e);else e.push(i+"="+encodeURIComponent(t));return e.join("&")},u=function(t,i,e,n,s){var n="urlencoded"===n?"application/"+n.replace("urlencoded","x-www-form-urlencoded"):"application/json";return e="application/json"===n?JSON.stringify(e):o(e),new Promise(function(r,o){try{var u=new XMLHttpRequest;u.open(t,i,!0),u.setRequestHeader("Accept","application/json"),u.setRequestHeader("Content-Type",n),Object.keys(s).forEach(function(t){u.setRequestHeader(t,s[t])}),u.onreadystatechange=function(){if(4===u.readyState)try{var t=u.responseText?JSON.parse(u.responseText):null;u.status>=200&&u.status<300?r(t):o(t)}catch(i){o(i)}},u.send(e)}catch(a){o(a)}})},a={post:u.bind(null,"POST"),put:u.bind(null,"PUT")},p={};s.defaults=function(t){p=t},s.Mixin={getInitialState:function(){return{_value:this.props.value?this.props.value:"",_isValid:!0,_isPristine:!0}},componentWillMount:function(){if(!this.props.name)throw new Error("Form Input requires a name property when used");if(!this.props._attachToForm)throw new Error("Form Mixin requires component to be nested in a Form");this._validations=this.props.validations||"",this.props.required&&(this._validations=this.props.validations?this.props.validations+",":"",this._validations+="isValue"),this.props._attachToForm(this)},componentWillReceiveProps:function(t){t._attachToForm=this.props._attachToForm,t._detachFromForm=this.props._detachFromForm,t._validate=this.props._validate},componentWillUnmount:function(){this.props._detachFromForm(this)},setValue:function(t){this.setState({_value:t,_isPristine:!1},function(){this.props._validate(this)}.bind(this))},resetValue:function(){this.setState({_value:"",_isPristine:!0},function(){this.props._validate(this)})},getValue:function(){return this.state._value},hasValue:function(){return""!==this.state._value},getErrorMessage:function(){return this.isValid()||this.showRequired()?null:this.state._serverError||this.props.validationError},isValid:function(){return this.state._isValid},isPristine:function(){return this.state._isPristine},isRequired:function(){return!!this.props.required},showRequired:function(){return this.isRequired()&&""===this.state._value},showError:function(){return!this.showRequired()&&!this.state._isValid}},s.addValidationRule=function(t,i){r[t]=i},s.Form=n.createClass({displayName:"Form",getInitialState:function(){return{isValid:!0,isSubmitting:!1}},getDefaultProps:function(){return{headers:{},onSuccess:function(){},onError:function(){},onSubmit:function(){},onSubmitted:function(){},onValid:function(){},onInvalid:function(){}}},componentWillMount:function(){this.inputs={},this.model={},this.registerInputs(this.props.children)},componentDidMount:function(){this.validateForm()},submit:function(t){if(t.preventDefault(),this.setFormPristine(!1),!this.props.url)return this.updateModel(),this.props.onSubmit(this.mapModel(),this.resetModel,this.updateInputsWithError),void 0;this.updateModel(),this.setState({isSubmitting:!0}),this.props.onSubmit(this.mapModel(),this.resetModel,this.updateInputsWithError);var i=Object.keys(this.props.headers).length&&this.props.headers||p.headers||{},e=this.props.method&&a[this.props.method.toLowerCase()]?this.props.method.toLowerCase():"post";a[e](this.props.url,this.mapModel(),this.props.contentType||p.contentType||"json",i).then(function(t){this.props.onSuccess(t),this.props.onSubmitted()}.bind(this)).catch(this.failSubmit)},mapModel:function(){return this.props.mapping?this.props.mapping(this.model):this.model},updateModel:function(){Object.keys(this.inputs).forEach(function(t){var i=this.inputs[t];this.model[t]=i.state._value}.bind(this))},resetModel:function(){Object.keys(this.inputs).forEach(function(t){this.inputs[t].resetValue()}.bind(this)),this.validateForm()},updateInputsWithError:function(t){Object.keys(t).forEach(function(i){var e=this.inputs[i];if(!e)throw new Error("You are trying to update an input that does not exists. Verify errors object with input names. "+JSON.stringify(t));var n=[{_isValid:!1,_serverError:t[i]}];e.setState.apply(e,n)}.bind(this))},failSubmit:function(t){this.updateInputsWithError(t),this.setState({isSubmitting:!1}),this.props.onError(t),this.props.onSubmitted()},registerInputs:function(t){n.Children.forEach(t,function(t){t.props&&t.props.name&&(t.props._attachToForm=this.attachToForm,t.props._detachFromForm=this.detachFromForm,t.props._validate=this.validate),t.props&&t.props.children&&this.registerInputs(t.props.children)}.bind(this))},getCurrentValues:function(){return Object.keys(this.inputs).reduce(function(t,i){var e=this.inputs[i];return t[i]=e.state._value,t}.bind(this),{})},setFormPristine:function(t){var i=this.inputs,e=Object.keys(i);e.forEach(function(e){var n=i[e];n.setState({_isPristine:t})}.bind(this))},validate:function(t){if(t.props.required||t._validations){var i=this.runValidation(t);t.setState({_isValid:i,_serverError:null},this.validateForm)}},runValidation:function(t){var i=!0;return t._validations.length&&(t.props.required||""!==t.state._value)&&t._validations.split(",").forEach(function(e){var n=e.split(":"),s=n.shift();if(n=n.map(function(t){try{return JSON.parse(t)}catch(i){return t}}),n=[t.state._value].concat(n),!r[s])throw new Error("Formsy does not have the validation rule: "+s);r[s].apply(this.getCurrentValues(),n)||(i=!1)}.bind(this)),i},validateForm:function(){var t=!0,i=this.inputs,e=Object.keys(i),n=function(){e.forEach(function(e){i[e].state._isValid||(t=!1)}.bind(this)),this.setState({isValid:t}),t&&this.props.onValid(),!t&&this.props.onInvalid()}.bind(this);e.forEach(function(t,s){var r=i[t],o=this.runValidation(r);r.setState({_isValid:o,_serverError:null},s===e.length-1?n:null)}.bind(this))},attachToForm:function(t){this.inputs[t.props.name]=t,this.model[t.props.name]=t.state._value,this.validate(t)},detachFromForm:function(t){delete this.inputs[t.props.name],delete this.model[t.props.name]},render:function(){return n.DOM.form({onSubmit:this.submit,className:this.props.className},this.props.children)}}),e.exports||e.module||e.define&&e.define.amd||(e.Formsy=s),i.exports=s}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{react:"react"}]},{},[1]);
src/client/components/Header/Header.js
jaimerosales/visual-reports-bim360dc
import AppNavbar from '../Navbar/AppNavbar' import React from 'react' import './Header.scss' class Header extends React.Component { render () { return ( <div> <AppNavbar {...this.props}/> </div> ) } } export default Header
src/components/labels_manager/labels_list.js
roman01la/f-react-kit
import React from 'react'; import Label from './label'; import { mutateLocal } from '../../lib/state_tools/mutator_client'; import { connectCSSExtractor } from '../../lib/css_tools/extract_css'; import styles from './labels_list.css'; function setSelectionState(item) { return () => mutateLocal(['setLabelSelection', { item }]); }; function getItems(items) { return items.map((item) => { return <Label key={item.get('name')} label={item} onClick={setSelectionState(item)} />; }); } const LabelsList = ({ labels }) => ( <div> <ul className={styles.labelsList}>{getItems(labels)}</ul> </div> ); export default connectCSSExtractor(LabelsList, Object.values(styles));
app/javascript/mastodon/components/setting_text.js
haleyashleypraesent/ProjectPrionosuchus
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; class SettingText extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, settingKey: PropTypes.array.isRequired, label: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, }; handleChange = (e) => { this.props.onChange(this.props.settingKey, e.target.value); } render () { const { settings, settingKey, label } = this.props; return ( <input className='setting-text' value={settings.getIn(settingKey)} onChange={this.handleChange} placeholder={label} /> ); } } export default SettingText;
src/containers/editor/RepoEditor/SearchInputer.js
mydearxym/mastani
import React from 'react' import { GITHUB_WEB_ADDR } from '@/config' import Button from '@/widgets/Buttons/Button' import FormItem from '@/widgets/FormItem' import { InputWrapper } from './styles/search_man' import { onGithubSearch, searchOnChange } from './logic' const SearchInputer = ({ value, searching }) => ( <> <InputWrapper> <FormItem value={value} size="large" onChange={searchOnChange} placeholder={`Github 仓库地址,如: ${GITHUB_WEB_ADDR}`} disabled={Boolean(searching)} autoFocus /> </InputWrapper> {searching ? ( <Button size="default" type="primary" ghost> 正在搜索.. </Button> ) : ( <Button size="default" type="primary" ghost onClick={onGithubSearch}> Github 搜索 </Button> )} </> ) export default React.memo(SearchInputer)
frontend/web/js/md/jquery.js
lekster/md
/*! 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);
node_modules/react/dist/react.js
rageboom/React_Study
/** * React v15.3.1 */ (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.React = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * Copyright 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. * * @providesModule AutoFocusUtils */ 'use strict'; var ReactDOMComponentTree = _dereq_(42); var focusNode = _dereq_(156); var AutoFocusUtils = { focusDOMComponent: function () { focusNode(ReactDOMComponentTree.getNodeFromInstance(this)); } }; module.exports = AutoFocusUtils; },{"156":156,"42":42}],2:[function(_dereq_,module,exports){ /** * Copyright 2013-present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(20); var ExecutionEnvironment = _dereq_(148); var FallbackCompositionState = _dereq_(21); var SyntheticCompositionEvent = _dereq_(103); var SyntheticInputEvent = _dereq_(107); var keyOf = _dereq_(166); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({ onBeforeInput: null }), captured: keyOf({ onBeforeInputCapture: null }) }, dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste] }, compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionEnd: null }), captured: keyOf({ onCompositionEndCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionStart: null }), captured: keyOf({ onCompositionStartCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionUpdate: null }), captured: keyOf({ onCompositionUpdateCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; },{"103":103,"107":107,"148":148,"16":16,"166":166,"20":20,"21":21}],3:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridColumn: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],4:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations */ 'use strict'; var CSSProperty = _dereq_(3); var ExecutionEnvironment = _dereq_(148); var ReactInstrumentation = _dereq_(73); var camelizeStyleName = _dereq_(150); var dangerousStyleValue = _dereq_(121); var hyphenateStyleName = _dereq_(161); var memoizeStringOnly = _dereq_(167); var warning = _dereq_(171); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if ("development" !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; "development" !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0; }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; "development" !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0; }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; "development" !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0; }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; "development" !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0; }; var checkRenderMessage = function (owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; }; /** * @param {string} name * @param {*} value * @param {ReactDOMComponent} component */ var warnValidStyle = function (name, value, component) { var owner; if (component) { owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number' && isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function (styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if ("development" !== 'production') { warnValidStyle(styleName, styleValue, component); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue, component) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function (node, styles, component) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(component._debugID, 'update styles', styles); } var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if ("development" !== 'production') { warnValidStyle(styleName, styles[styleName], component); } var styleValue = dangerousStyleValue(styleName, styles[styleName], component); if (styleName === 'float' || styleName === 'cssFloat') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; },{"121":121,"148":148,"150":150,"161":161,"167":167,"171":171,"3":3,"73":73}],5:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var PooledClass = _dereq_(25); var invariant = _dereq_(162); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } _assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function (callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function () { var callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { !(callbacks.length === contexts.length) ? "development" !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, checkpoint: function () { return this._callbacks ? this._callbacks.length : 0; }, rollback: function (len) { if (this._callbacks) { this._callbacks.length = len; this._contexts.length = len; } }, /** * Resets the internal queue. * * @internal */ reset: function () { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function () { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; },{"140":140,"162":162,"172":172,"25":25}],6:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPropagators = _dereq_(20); var ExecutionEnvironment = _dereq_(148); var ReactDOMComponentTree = _dereq_(42); var ReactUpdates = _dereq_(96); var SyntheticEvent = _dereq_(105); var getEventTarget = _dereq_(129); var isEventSupported = _dereq_(136); var isTextInputElement = _dereq_(137); var keyOf = _dereq_(166); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({ onChange: null }), captured: keyOf({ onChangeCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange] } }; /** * For IE shims */ var activeElement = null; var activeElementInst = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementInst = null; } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topChange) { return targetInst; } } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(target, targetInst); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. // IE10+ fire input events to often, such when a placeholder // changes or when an input with a placeholder is focused. isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 11); } /** * (For IE <=11) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For IE <=11) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); if (activeElement.attachEvent) { activeElement.attachEvent('onpropertychange', handlePropertyChange); } else { activeElement.addEventListener('propertychange', handlePropertyChange, false); } } /** * (For IE <=11) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; if (activeElement.detachEvent) { activeElement.detachEvent('onpropertychange', handlePropertyChange); } else { activeElement.removeEventListener('propertychange', handlePropertyChange, false); } activeElement = null; activeElementInst = null; activeElementValue = null; activeElementValueProp = null; } /** * (For IE <=11) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetInstForInputEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return targetInst; } } function handleEventsForInputEventIE(topLevelType, target, targetInst) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9-11, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventIE(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementInst; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topClick) { return targetInst; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { if (doesChangeEventBubble) { getTargetInstFunc = getTargetInstForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputEvent; } else { getTargetInstFunc = getTargetInstForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } } }; module.exports = ChangeEventPlugin; },{"105":105,"129":129,"136":136,"137":137,"148":148,"16":16,"166":166,"17":17,"20":20,"42":42,"96":96}],7:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations */ 'use strict'; var DOMLazyTree = _dereq_(8); var Danger = _dereq_(12); var ReactMultiChildUpdateTypes = _dereq_(78); var ReactDOMComponentTree = _dereq_(42); var ReactInstrumentation = _dereq_(73); var createMicrosoftUnsafeLocalFunction = _dereq_(120); var setInnerHTML = _dereq_(142); var setTextContent = _dereq_(143); function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getHostNode. if (Array.isArray(node)) { node = node[1]; } return node ? node.nextSibling : parentNode.firstChild; } /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, 'replace text', stringText); } } var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup; if ("development" !== 'production') { dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) { Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup); if (prevInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation(prevInstance._debugID, 'replace with', markup.toString()); } else { var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node); if (nextInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation(nextInstance._debugID, 'mount', markup.toString()); } } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @internal */ processUpdates: function (parentNode, updates) { if ("development" !== 'production') { var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID; } for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'insert child', { toIndex: update.toIndex, content: update.content.toString() }); } break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'move child', { fromIndex: update.fromIndex, toIndex: update.toIndex }); } break; case ReactMultiChildUpdateTypes.SET_MARKUP: setInnerHTML(parentNode, update.content); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'replace children', update.content.toString()); } break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent(parentNode, update.content); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'replace text', update.content.toString()); } break; case ReactMultiChildUpdateTypes.REMOVE_NODE: removeChild(parentNode, update.fromNode); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'remove child', { fromIndex: update.fromIndex }); } break; } } } }; module.exports = DOMChildrenOperations; },{"12":12,"120":120,"142":142,"143":143,"42":42,"73":73,"78":78,"8":8}],8:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMLazyTree */ 'use strict'; var DOMNamespaces = _dereq_(9); var setInnerHTML = _dereq_(142); var createMicrosoftUnsafeLocalFunction = _dereq_(120); var setTextContent = _dereq_(143); var ELEMENT_NODE_TYPE = 1; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * In IE (8-11) and Edge, appending nodes with no children is dramatically * faster than appending a full subtree, so we essentially queue up the * .appendChild calls here and apply them so each node is added to its parent * before any children are added. * * In other browsers, doing so is slower or neutral compared to the other order * (in Firefox, twice as slow) so we only do this inversion in IE. * * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode. */ var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent); function insertTreeChildren(tree) { if (!enableLazy) { return; } var node = tree.node; var children = tree.children; if (children.length) { for (var i = 0; i < children.length; i++) { insertTreeBefore(node, children[i], null); } } else if (tree.html != null) { setInnerHTML(node, tree.html); } else if (tree.text != null) { setTextContent(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. Also, some <object> plugins (like Flash Player) will read // <param> nodes immediately upon insertion into the DOM, so <object> // must also be populated prior to insertion into the DOM. if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) { insertTreeChildren(tree); parentNode.insertBefore(tree.node, referenceNode); } else { parentNode.insertBefore(tree.node, referenceNode); insertTreeChildren(tree); } }); function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode); insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { if (enableLazy) { parentTree.children.push(childTree); } else { parentTree.node.appendChild(childTree.node); } } function queueHTML(tree, html) { if (enableLazy) { tree.html = html; } else { setInnerHTML(tree.node, html); } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent(tree.node, text); } } function toString() { return this.node.nodeName; } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null, toString: toString }; } DOMLazyTree.insertTreeBefore = insertTreeBefore; DOMLazyTree.replaceChildWithTree = replaceChildWithTree; DOMLazyTree.queueChild = queueChild; DOMLazyTree.queueHTML = queueHTML; DOMLazyTree.queueText = queueText; module.exports = DOMLazyTree; },{"120":120,"142":142,"143":143,"9":9}],9:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMNamespaces */ 'use strict'; var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; module.exports = DOMNamespaces; },{}],10:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty */ 'use strict'; var _prodInvariant = _dereq_(140); var invariant = _dereq_(162); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_PROPERTY: 0x1, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? "development" !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', propName) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0; if ("development" !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if ("development" !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; /* eslint-enable max-len */ /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * @type {Object} */ getPossibleStandardName: "development" !== 'production' ? {} : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; },{"140":140,"162":162}],11:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations */ 'use strict'; var DOMProperty = _dereq_(10); var ReactDOMComponentTree = _dereq_(42); var ReactInstrumentation = _dereq_(73); var quoteAttributeValueForBrowser = _dereq_(139); var warning = _dereq_(171); var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; "development" !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function () { return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function (node) { node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, ''); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); return; } else if (propertyInfo.mustUseProperty) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propertyInfo.propertyName] = value; } else { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); return; } if ("development" !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } if ("development" !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload); } }, /** * Deletes an attributes from a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForAttribute: function (node, name) { node.removeAttribute(name); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'remove attribute', name); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propertyInfo.hasBooleanValue) { node[propName] = false; } else { node[propName] = ''; } } else { node.removeAttribute(propertyInfo.attributeName); } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'remove attribute', name); } } }; module.exports = DOMPropertyOperations; },{"10":10,"139":139,"171":171,"42":42,"73":73}],12:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger */ 'use strict'; var _prodInvariant = _dereq_(140); var DOMLazyTree = _dereq_(8); var ExecutionEnvironment = _dereq_(148); var createNodesFromMarkup = _dereq_(153); var emptyFunction = _dereq_(154); var invariant = _dereq_(162); var Danger = { /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('56') : void 0; !markup ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0; !(oldChild.nodeName !== 'HTML') ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : _prodInvariant('58') : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger; },{"140":140,"148":148,"153":153,"154":154,"162":162,"8":8}],13:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ 'use strict'; var keyOf = _dereq_(166); /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })]; module.exports = DefaultEventPluginOrder; },{"166":166}],14:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DisabledInputUtils */ 'use strict'; var disableableMouseListenerNames = { onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }; /** * Implements a host component that does not receive mouse events * when `disabled` is set. */ var DisabledInputUtils = { getHostProps: function (inst, props) { if (!props.disabled) { return props; } // Copy the props, except the mouse listeners var hostProps = {}; for (var key in props) { if (!disableableMouseListenerNames[key] && props.hasOwnProperty(key)) { hostProps[key] = props[key]; } } return hostProps; } }; module.exports = DisabledInputUtils; },{}],15:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(20); var ReactDOMComponentTree = _dereq_(42); var SyntheticMouseEvent = _dereq_(109); var keyOf = _dereq_(166); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { mouseEnter: { registrationName: keyOf({ onMouseEnter: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] }, mouseLeave: { registrationName: keyOf({ onMouseLeave: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] } }; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === topLevelTypes.topMouseOut) { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to); var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; module.exports = EnterLeaveEventPlugin; },{"109":109,"16":16,"166":166,"20":20,"42":42}],16:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ 'use strict'; var keyMirror = _dereq_(165); var PropagationPhases = keyMirror({ bubbled: null, captured: null }); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topAbort: null, topAnimationEnd: null, topAnimationIteration: null, topAnimationStart: null, topBlur: null, topCanPlay: null, topCanPlayThrough: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topDurationChange: null, topEmptied: null, topEncrypted: null, topEnded: null, topError: null, topFocus: null, topInput: null, topInvalid: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topLoadedData: null, topLoadedMetadata: null, topLoadStart: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topPause: null, topPlay: null, topPlaying: null, topProgress: null, topRateChange: null, topReset: null, topScroll: null, topSeeked: null, topSeeking: null, topSelectionChange: null, topStalled: null, topSubmit: null, topSuspend: null, topTextInput: null, topTimeUpdate: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topTransitionEnd: null, topVolumeChange: null, topWaiting: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"165":165}],17:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ 'use strict'; var _prodInvariant = _dereq_(140); var EventPluginRegistry = _dereq_(18); var EventPluginUtils = _dereq_(19); var ReactErrorUtils = _dereq_(64); var accumulateInto = _dereq_(116); var forEachAccumulated = _dereq_(125); var invariant = _dereq_(162); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; var getDictionaryKey = function (inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; }; /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {function} listener The callback to store. */ putListener: function (inst, registrationName, listener) { !(typeof listener === 'function') ? "development" !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0; var key = getDictionaryKey(inst); var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[key] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(inst, registrationName, listener); } }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; var key = getDictionaryKey(inst); return bankForRegistrationName && bankForRegistrationName[key]; }, /** * Deletes a listener from the registration bank. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { var key = getDictionaryKey(inst); delete bankForRegistrationName[key]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {object} inst The instance, which is the source of events. */ deleteAllListeners: function (inst) { var key = getDictionaryKey(inst); for (var registrationName in listenerBank) { if (!listenerBank.hasOwnProperty(registrationName)) { continue; } if (!listenerBank[registrationName][key]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][key]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? "development" !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; },{"116":116,"125":125,"140":140,"162":162,"18":18,"19":19,"64":64}],18:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry */ 'use strict'; var _prodInvariant = _dereq_(140); var invariant = _dereq_(162); /** * Injectable ordering of event plugins. */ var EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !PluginModule.extractEvents ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', eventName, pluginName) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', eventName) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, PluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; if ("development" !== 'production') { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: "development" !== 'production' ? {} : null, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (InjectedEventPluginOrder) { !!EventPluginOrder ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : void 0; // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { !!namesToPlugins[pluginName] ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0; namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if ("development" !== 'production') { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } } }; module.exports = EventPluginRegistry; },{"140":140,"162":162}],19:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ 'use strict'; var _prodInvariant = _dereq_(140); var EventConstants = _dereq_(16); var ReactErrorUtils = _dereq_(64); var invariant = _dereq_(162); var warning = _dereq_(171); /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var TreeTraversal; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; if ("development" !== 'production') { "development" !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } }, injectTreeTraversal: function (Injected) { TreeTraversal = Injected; if ("development" !== 'production') { "development" !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0; } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if ("development" !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; "development" !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if ("development" !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if ("development" !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if ("development" !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? "development" !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, isAncestor: function (a, b) { return TreeTraversal.isAncestor(a, b); }, getLowestCommonAncestor: function (a, b) { return TreeTraversal.getLowestCommonAncestor(a, b); }, getParentInstance: function (inst) { return TreeTraversal.getParentInstance(inst); }, traverseTwoPhase: function (target, fn, arg) { return TreeTraversal.traverseTwoPhase(target, fn, arg); }, traverseEnterLeave: function (from, to, fn, argFrom, argTo) { return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo); }, injection: injection }; module.exports = EventPluginUtils; },{"140":140,"16":16,"162":162,"171":171,"64":64}],20:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPluginUtils = _dereq_(19); var accumulateInto = _dereq_(116); var forEachAccumulated = _dereq_(125); var warning = _dereq_(171); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, upwards, event) { if ("development" !== 'production') { "development" !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0; } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null; EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; },{"116":116,"125":125,"16":16,"17":17,"171":171,"19":19}],21:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FallbackCompositionState */ 'use strict'; var _assign = _dereq_(172); var PooledClass = _dereq_(25); var getTextContentAccessor = _dereq_(133); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } _assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; },{"133":133,"172":172,"25":25}],22:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ 'use strict'; var DOMProperty = _dereq_(10); var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, icon: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, referrerPolicy: 0, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: 0, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {} }; module.exports = HTMLDOMPropertyConfig; },{"10":10}],23:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule KeyEscapeUtils * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; },{}],24:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactPropTypes = _dereq_(84); var ReactPropTypeLocations = _dereq_(83); var ReactPropTypesSecret = _dereq_(85); var invariant = _dereq_(162); var warning = _dereq_(171); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don\'t want to use valueLink and vice versa.') : _prodInvariant('87') : void 0; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don\'t want to use valueLink.') : _prodInvariant('88') : void 0; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don\'t want to use checkedLink') : _prodInvariant('89') : void 0; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: ReactPropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop, null, ReactPropTypesSecret); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); "development" !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils; },{"140":140,"162":162,"171":171,"83":83,"84":84,"85":85}],25:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ 'use strict'; var _prodInvariant = _dereq_(140); var invariant = _dereq_(162); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? "development" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; },{"140":140,"162":162}],26:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ 'use strict'; var _assign = _dereq_(172); var ReactChildren = _dereq_(29); var ReactComponent = _dereq_(32); var ReactPureComponent = _dereq_(86); var ReactClass = _dereq_(31); var ReactDOMFactories = _dereq_(45); var ReactElement = _dereq_(61); var ReactPropTypes = _dereq_(84); var ReactVersion = _dereq_(97); var onlyChild = _dereq_(138); var warning = _dereq_(171); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if ("development" !== 'production') { var ReactElementValidator = _dereq_(62); createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; if ("development" !== 'production') { var warned = false; __spread = function () { "development" !== 'production' ? warning(warned, '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; warned = true; return _assign.apply(null, arguments); }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, PureComponent: ReactPureComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; module.exports = React; },{"138":138,"171":171,"172":172,"29":29,"31":31,"32":32,"45":45,"61":61,"62":62,"84":84,"86":86,"97":97}],27:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter */ 'use strict'; var _assign = _dereq_(172); var EventConstants = _dereq_(16); var EventPluginRegistry = _dereq_(18); var ReactEventEmitterMixin = _dereq_(65); var ViewportMetrics = _dereq_(115); var getVendorPrefixedEventName = _dereq_(134); var isEventSupported = _dereq_(136); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var hasEventPageXY; var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend', topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration', topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * EventPluginHub.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when * pageX/pageY isn't supported (legacy browsers). * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (hasEventPageXY === undefined) { hasEventPageXY = document.createEvent && 'pageX' in document.createEvent('MouseEvent'); } if (!hasEventPageXY && !isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } } }); module.exports = ReactBrowserEventEmitter; },{"115":115,"134":134,"136":136,"16":16,"172":172,"18":18,"65":65}],28:[function(_dereq_,module,exports){ (function (process){ /** * Copyright 2014-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. * * @providesModule ReactChildReconciler */ 'use strict'; var ReactReconciler = _dereq_(88); var instantiateReactComponent = _dereq_(135); var KeyEscapeUtils = _dereq_(23); var shouldUpdateReactComponent = _dereq_(144); var traverseAllChildren = _dereq_(145); var warning = _dereq_(171); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && "development" === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = _dereq_(35); } function instantiateChild(childInstances, child, name, selfDebugID) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if ("development" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = _dereq_(35); } if (!keyUnique) { "development" !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child, true); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context, selfDebugID // 0 in production and for roots ) { if (nestedChildNodes == null) { return null; } var childInstances = {}; if ("development" !== 'production') { traverseAllChildren(nestedChildNodes, function (childInsts, child, name) { return instantiateChild(childInsts, child, name, selfDebugID); }, childInstances); } else { traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); } return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID // 0 in production and for roots ) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return; } var name; var prevChild; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement, true); nextChildren[name] = nextChildInstance; // Creating mount image now ensures refs are resolved in right order // (see https://github.com/facebook/react/pull/7101 for explanation). var nextChildMountImage = ReactReconciler.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID); mountImages.push(nextChildMountImage); } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { prevChild = prevChildren[name]; removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren, safely) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild, safely); } } } }; module.exports = ReactChildReconciler; }).call(this,undefined) },{"135":135,"144":144,"145":145,"171":171,"23":23,"35":35,"88":88}],29:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ 'use strict'; var PooledClass = _dereq_(25); var ReactElement = _dereq_(61); var emptyFunction = _dereq_(154); var traverseAllChildren = _dereq_(145); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func; var context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result; var keyPrefix = bookKeeping.keyPrefix; var func = bookKeeping.func; var context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; },{"145":145,"154":154,"25":25,"61":61}],30:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildrenMutationWarningHook */ 'use strict'; var ReactComponentTreeHook = _dereq_(35); var warning = _dereq_(171); function handleElement(debugID, element) { if (element == null) { return; } if (element._shadowChildren === undefined) { return; } if (element._shadowChildren === element.props.children) { return; } var isMutated = false; if (Array.isArray(element._shadowChildren)) { if (element._shadowChildren.length === element.props.children.length) { for (var i = 0; i < element._shadowChildren.length; i++) { if (element._shadowChildren[i] !== element.props.children[i]) { isMutated = true; } } } else { isMutated = true; } } if (!Array.isArray(element._shadowChildren) || isMutated) { "development" !== 'production' ? warning(false, 'Component\'s children should not be mutated.%s', ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } } var ReactChildrenMutationWarningHook = { onMountComponent: function (debugID) { handleElement(debugID, ReactComponentTreeHook.getElement(debugID)); }, onUpdateComponent: function (debugID) { handleElement(debugID, ReactComponentTreeHook.getElement(debugID)); } }; module.exports = ReactChildrenMutationWarningHook; },{"171":171,"35":35}],31:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactClass */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var ReactComponent = _dereq_(32); var ReactElement = _dereq_(61); var ReactPropTypeLocations = _dereq_(83); var ReactPropTypeLocationNames = _dereq_(82); var ReactNoopUpdateQueue = _dereq_(80); var emptyObject = _dereq_(155); var invariant = _dereq_(162); var keyMirror = _dereq_(165); var keyOf = _dereq_(166); var warning = _dereq_(171); var MIXINS_KEY = keyOf({ mixins: null }); /** * Policies that describe methods in `ReactClassInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if ("development" !== 'production') { validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); } Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if ("development" !== 'production') { validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context); } Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if ("development" !== 'production') { validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; // noop function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but only in __DEV__ "development" !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0; } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.OVERRIDE_BASE) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.', name) : _prodInvariant('73', name) : void 0; } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('74', name) : void 0; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if ("development" !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; "development" !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0; } return; } !(typeof spec !== 'function') ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0; !!ReactElement.isValidElement(spec) ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0; var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? "development" !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if ("development" !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; !!isReserved ? "development" !== 'production' ? invariant(false, '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.', name) : _prodInvariant('78', name) : void 0; var isInherited = name in Constructor; !!isInherited ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('79', name) : void 0; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : _prodInvariant('80') : void 0; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? "development" !== 'production' ? invariant(false, '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.', key) : _prodInvariant('81', key) : void 0; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if ("development" !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { "development" !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0; } else if (!args.length) { "development" !== 'production' ? warning(false, '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', componentName) : void 0; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback, 'replaceState'); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); } }; var ReactClassComponent = function () {}; _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { var Constructor = function (props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if ("development" !== 'production') { "development" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0; } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if ("development" !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (initialState === undefined && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : _prodInvariant('82', Constructor.displayName || 'ReactCompositeComponent') : void 0; this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if ("development" !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? "development" !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : _prodInvariant('83') : void 0; if ("development" !== 'production') { "development" !== 'production' ? warning(!Constructor.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.', spec.displayName || 'A component') : void 0; "development" !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; },{"140":140,"155":155,"162":162,"165":165,"166":166,"171":171,"172":172,"32":32,"61":61,"80":80,"82":82,"83":83}],32:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactNoopUpdateQueue = _dereq_(80); var canDefineProperty = _dereq_(118); var emptyObject = _dereq_(155); var invariant = _dereq_(162); var warning = _dereq_(171); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "development" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0; this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback, 'forceUpdate'); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if ("development" !== 'production') { var deprecatedAPIs = { 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).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { "development" !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; },{"118":118,"140":140,"155":155,"162":162,"171":171,"80":80}],33:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ 'use strict'; var DOMChildrenOperations = _dereq_(7); var ReactDOMIDOperations = _dereq_(47); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup }; module.exports = ReactComponentBrowserEnvironment; },{"47":47,"7":7}],34:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * * @providesModule ReactComponentEnvironment */ 'use strict'; var _prodInvariant = _dereq_(140); var invariant = _dereq_(162); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkup: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function (environment) { !!injected ? "development" !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : _prodInvariant('104') : void 0; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; },{"140":140,"162":162}],35:[function(_dereq_,module,exports){ /** * Copyright 2016-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. * * @providesModule ReactComponentTreeHook */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactCurrentOwner = _dereq_(37); var invariant = _dereq_(162); var warning = _dereq_(171); function isNative(fn) { // Based on isNative() from Lodash var funcToString = Function.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var reIsNative = RegExp('^' + funcToString // Take an example native function source for comparison .call(hasOwnProperty) // Strip regex characters so we can use it for regex .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') // Remove hasOwnProperty from the template to make it generic .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); try { var source = funcToString.call(fn); return reIsNative.test(source); } catch (err) { return false; } } var canUseCollections = // Array.from typeof Array.from === 'function' && // Map typeof Map === 'function' && isNative(Map) && // Map.prototype.keys Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) && // Set typeof Set === 'function' && isNative(Set) && // Set.prototype.keys Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys); var itemMap; var rootIDSet; var itemByKey; var rootByKey; if (canUseCollections) { itemMap = new Map(); rootIDSet = new Set(); } else { itemByKey = {}; rootByKey = {}; } var unmountedIDs = []; // Use non-numeric keys to prevent V8 performance issues: // https://github.com/facebook/react/pull/7232 function getKeyFromID(id) { return '.' + id; } function getIDFromKey(key) { return parseInt(key.substr(1), 10); } function get(id) { if (canUseCollections) { return itemMap.get(id); } else { var key = getKeyFromID(id); return itemByKey[key]; } } function remove(id) { if (canUseCollections) { itemMap['delete'](id); } else { var key = getKeyFromID(id); delete itemByKey[key]; } } function create(id, element, parentID) { var item = { element: element, parentID: parentID, text: null, childIDs: [], isMounted: false, updateCount: 0 }; if (canUseCollections) { itemMap.set(id, item); } else { var key = getKeyFromID(id); itemByKey[key] = item; } } function addRoot(id) { if (canUseCollections) { rootIDSet.add(id); } else { var key = getKeyFromID(id); rootByKey[key] = true; } } function removeRoot(id) { if (canUseCollections) { rootIDSet['delete'](id); } else { var key = getKeyFromID(id); delete rootByKey[key]; } } function getRegisteredIDs() { if (canUseCollections) { return Array.from(itemMap.keys()); } else { return Object.keys(itemByKey).map(getIDFromKey); } } function getRootIDs() { if (canUseCollections) { return Array.from(rootIDSet.keys()); } else { return Object.keys(rootByKey).map(getIDFromKey); } } function purgeDeep(id) { var item = get(id); if (item) { var childIDs = item.childIDs; remove(id); childIDs.forEach(purgeDeep); } } function describeComponentFrame(name, source, ownerName) { return '\n in ' + name + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); } function getDisplayName(element) { if (element == null) { return '#empty'; } else if (typeof element === 'string' || typeof element === 'number') { return '#text'; } else if (typeof element.type === 'string') { return element.type; } else { return element.type.displayName || element.type.name || 'Unknown'; } } function describeID(id) { var name = ReactComponentTreeHook.getDisplayName(id); var element = ReactComponentTreeHook.getElement(id); var ownerID = ReactComponentTreeHook.getOwnerID(id); var ownerName; if (ownerID) { ownerName = ReactComponentTreeHook.getDisplayName(ownerID); } "development" !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0; return describeComponentFrame(name, element && element._source, ownerName); } var ReactComponentTreeHook = { onSetChildren: function (id, nextChildIDs) { var item = get(id); item.childIDs = nextChildIDs; for (var i = 0; i < nextChildIDs.length; i++) { var nextChildID = nextChildIDs[i]; var nextChild = get(nextChildID); !nextChild ? "development" !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0; !(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? "development" !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0; !nextChild.isMounted ? "development" !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0; if (nextChild.parentID == null) { nextChild.parentID = id; // TODO: This shouldn't be necessary but mounting a new root during in // componentWillMount currently causes not-yet-mounted components to // be purged from our tree data so their parent ID is missing. } !(nextChild.parentID === id) ? "development" !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0; } }, onBeforeMountComponent: function (id, element, parentID) { create(id, element, parentID); }, onBeforeUpdateComponent: function (id, element) { var item = get(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.element = element; }, onMountComponent: function (id) { var item = get(id); item.isMounted = true; var isRoot = item.parentID === 0; if (isRoot) { addRoot(id); } }, onUpdateComponent: function (id) { var item = get(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.updateCount++; }, onUnmountComponent: function (id) { var item = get(id); if (item) { // We need to check if it exists. // `item` might not exist if it is inside an error boundary, and a sibling // error boundary child threw while mounting. Then this instance never // got a chance to mount, but it still gets an unmounting event during // the error boundary cleanup. item.isMounted = false; var isRoot = item.parentID === 0; if (isRoot) { removeRoot(id); } } unmountedIDs.push(id); }, purgeUnmountedComponents: function () { if (ReactComponentTreeHook._preventPurging) { // Should only be used for testing. return; } for (var i = 0; i < unmountedIDs.length; i++) { var id = unmountedIDs[i]; purgeDeep(id); } unmountedIDs.length = 0; }, isMounted: function (id) { var item = get(id); return item ? item.isMounted : false; }, getCurrentStackAddendum: function (topElement) { var info = ''; if (topElement) { var type = topElement.type; var name = typeof type === 'function' ? type.displayName || type.name : type; var owner = topElement._owner; info += describeComponentFrame(name || 'Unknown', topElement._source, owner && owner.getName()); } var currentOwner = ReactCurrentOwner.current; var id = currentOwner && currentOwner._debugID; info += ReactComponentTreeHook.getStackAddendumByID(id); return info; }, getStackAddendumByID: function (id) { var info = ''; while (id) { info += describeID(id); id = ReactComponentTreeHook.getParentID(id); } return info; }, getChildIDs: function (id) { var item = get(id); return item ? item.childIDs : []; }, getDisplayName: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element) { return null; } return getDisplayName(element); }, getElement: function (id) { var item = get(id); return item ? item.element : null; }, getOwnerID: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element || !element._owner) { return null; } return element._owner._debugID; }, getParentID: function (id) { var item = get(id); return item ? item.parentID : null; }, getSource: function (id) { var item = get(id); var element = item ? item.element : null; var source = element != null ? element._source : null; return source; }, getText: function (id) { var element = ReactComponentTreeHook.getElement(id); if (typeof element === 'string') { return element; } else if (typeof element === 'number') { return '' + element; } else { return null; } }, getUpdateCount: function (id) { var item = get(id); return item ? item.updateCount : 0; }, getRegisteredIDs: getRegisteredIDs, getRootIDs: getRootIDs }; module.exports = ReactComponentTreeHook; },{"140":140,"162":162,"171":171,"37":37}],36:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var ReactComponentEnvironment = _dereq_(34); var ReactCurrentOwner = _dereq_(37); var ReactElement = _dereq_(61); var ReactErrorUtils = _dereq_(64); var ReactInstanceMap = _dereq_(72); var ReactInstrumentation = _dereq_(73); var ReactNodeTypes = _dereq_(79); var ReactPropTypeLocations = _dereq_(83); var ReactReconciler = _dereq_(88); var checkReactTypeSpec = _dereq_(119); var emptyObject = _dereq_(155); var invariant = _dereq_(162); var shallowEqual = _dereq_(170); var shouldUpdateReactComponent = _dereq_(144); var warning = _dereq_(171); var CompositeTypes = { ImpureClass: 0, PureClass: 1, StatelessFunctional: 2 }; function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; var element = Component(this.props, this.context, this.updater); warnIfInvalidElement(Component, element); return element; }; function warnIfInvalidElement(Component, element) { if ("development" !== 'production') { "development" !== 'production' ? warning(element === null || element === false || ReactElement.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0; "development" !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0; } } function invokeComponentDidMountWithTimer() { var publicInstance = this._instance; if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidMount'); } publicInstance.componentDidMount(); if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidMount'); } } function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) { var publicInstance = this._instance; if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidUpdate'); } publicInstance.componentDidUpdate(prevProps, prevState, prevContext); if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidUpdate'); } } function shouldConstruct(Component) { return !!(Component.prototype && Component.prototype.isReactComponent); } function isPureComponent(Component) { return !!(Component.prototype && Component.prototype.isPureReactComponent); } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = 0; this._compositeType = null; this._instance = null; this._hostParent = null; this._hostContainerInfo = null; // See ReactUpdateQueue this._updateBatchNumber = null; this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedNodeType = null; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = false; if ("development" !== 'production') { this._warnedAboutRefsInRender = false; } }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} hostParent * @param {?object} hostContainerInfo * @param {?object} context * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { this._context = context; this._mountOrder = nextMountID++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var publicProps = this._currentElement.props; var publicContext = this._processContext(context); var Component = this._currentElement.type; var updateQueue = transaction.getUpdateQueue(); // Initialize the public class var doConstruct = shouldConstruct(Component); var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue); var renderedElement; // Support functional components if (!doConstruct && (inst == null || inst.render == null)) { renderedElement = inst; warnIfInvalidElement(Component, renderedElement); !(inst === null || inst === false || ReactElement.isValidElement(inst)) ? "development" !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0; inst = new StatelessComponent(Component); this._compositeType = CompositeTypes.StatelessFunctional; } else { if (isPureComponent(Component)) { this._compositeType = CompositeTypes.PureClass; } else { this._compositeType = CompositeTypes.ImpureClass; } } if ("development" !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { "development" !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0; } var propsMutated = inst.props !== publicProps; var componentName = Component.displayName || Component.name || 'Component'; "development" !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0; } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = updateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if ("development" !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. "development" !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : void 0; "development" !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0; "development" !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; var markup; if (inst.unstable_handleError) { markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context); } else { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } if (inst.componentDidMount) { if ("development" !== 'production') { transaction.getReactMountReady().enqueue(invokeComponentDidMountWithTimer, this); } else { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } } return markup; }, _constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) { if ("development" !== 'production') { ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } finally { ReactCurrentOwner.current = null; } } else { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } }, _constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) { var Component = this._currentElement.type; var instanceOrElement; if (doConstruct) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'ctor'); } } instanceOrElement = new Component(publicProps, publicContext, updateQueue); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'ctor'); } } } else { // This can still be an instance in case of factory components // but we'll count this as time spent rendering as the more common case. if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render'); } } instanceOrElement = Component(publicProps, publicContext, updateQueue); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render'); } } } return instanceOrElement; }, performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var markup; var checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } catch (e) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onError(); } } // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); this._renderedComponent.unmountComponent(true); transaction.rollback(checkpoint); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } return markup; }, performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var inst = this._instance; if (inst.componentWillMount) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillMount'); } } inst.componentWillMount(); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillMount'); } } // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } var nodeType = ReactNodeTypes.getType(renderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var selfDebugID = 0; if ("development" !== 'production') { selfDebugID = this._debugID; } var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), selfDebugID); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(this._debugID, child._debugID !== 0 ? [child._debugID] : []); } } return markup; }, getHostNode: function () { return ReactReconciler.getHostNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (safely) { if (!this._renderedComponent) { return; } var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { inst._calledComponentWillUnmount = true; if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUnmount'); } } if (safely) { var name = this.getName() + '.componentWillUnmount()'; ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst)); } else { inst.componentWillUnmount(); } if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUnmount'); } } } if (this._renderedComponent) { ReactReconciler.unmountComponent(this._renderedComponent, safely); this._renderedNodeType = null; this._renderedComponent = null; this._instance = null; } // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = 0; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if ("development" !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkContextTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; if ("development" !== 'production') { ReactInstrumentation.debugTool.onBeginProcessingChildContext(); } var childContext = inst.getChildContext && inst.getChildContext(); if ("development" !== 'production') { ReactInstrumentation.debugTool.onEndProcessingChildContext(); } if (childContext) { !(typeof Component.childContextTypes === 'object') ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0; if ("development" !== 'production') { this._checkContextTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); } for (var name in childContext) { !(name in Component.childContextTypes) ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0; } return _assign({}, currentContext, childContext); } return currentContext; }, /** * Assert that the context types are valid * * @param {object} typeSpecs Map of context field to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkContextTypes: function (typeSpecs, values, location) { checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID); }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { this._updateBatchNumber = null; } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; !(inst != null) ? "development" !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', this.getName() || 'ReactCompositeComponent') : void 0; var willReceive = false; var nextContext; // Determine if the context has changed or not if (this._context === nextUnmaskedContext) { nextContext = inst.context; } else { nextContext = this._processContext(nextUnmaskedContext); willReceive = true; } var prevProps = prevParentElement.props; var nextProps = nextParentElement.props; // Not a simple state update but a props update if (prevParentElement !== nextParentElement) { willReceive = true; } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (willReceive && inst.componentWillReceiveProps) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillReceiveProps'); } } inst.componentWillReceiveProps(nextProps, nextContext); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillReceiveProps'); } } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = true; if (!this._pendingForceUpdate) { if (inst.shouldComponentUpdate) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'shouldComponentUpdate'); } } shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'shouldComponentUpdate'); } } } else { if (this._compositeType === CompositeTypes.PureClass) { shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState); } } } if ("development" !== 'production') { "development" !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0; } this._updateBatchNumber = null; if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = _assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; _assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUpdate'); } } inst.componentWillUpdate(nextProps, nextState, nextContext); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUpdate'); } } } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { if ("development" !== 'production') { transaction.getReactMountReady().enqueue(invokeComponentDidUpdateWithTimer.bind(this, prevProps, prevState, prevContext), this); } else { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance); ReactReconciler.unmountComponent(prevComponentInstance, false); var nodeType = ReactNodeTypes.getType(nextRenderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var selfDebugID = 0; if ("development" !== 'production') { selfDebugID = this._debugID; } var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), selfDebugID); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(this._debugID, child._debugID !== 0 ? [child._debugID] : []); } } this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) { ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render'); } } var renderedComponent = inst.render(); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render'); } } if ("development" !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (renderedComponent === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: function () { var renderedComponent; if ("development" !== 'production' || this._compositeType !== CompositeTypes.StatelessFunctional) { ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } } else { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } !( // TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? "development" !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0; return renderedComponent; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? "development" !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : _prodInvariant('110') : void 0; var publicComponentInstance = component.getPublicInstance(); if ("development" !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; "development" !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (this._compositeType === CompositeTypes.StatelessFunctional) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; var ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; },{"119":119,"140":140,"144":144,"155":155,"162":162,"170":170,"171":171,"172":172,"34":34,"37":37,"61":61,"64":64,"72":72,"73":73,"79":79,"83":83,"88":88}],37:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],38:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactDOMComponentTree = _dereq_(42); var ReactDefaultInjection = _dereq_(60); var ReactMount = _dereq_(76); var ReactReconciler = _dereq_(88); var ReactUpdates = _dereq_(96); var ReactVersion = _dereq_(97); var findDOMNode = _dereq_(123); var getHostComponentFromComposite = _dereq_(130); var renderSubtreeIntoContainer = _dereq_(141); var warning = _dereq_(171); ReactDefaultInjection.inject(); var ReactDOM = { findDOMNode: findDOMNode, render: ReactMount.render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. /* eslint-enable camelcase */ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ ComponentTree: { getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode, getNodeFromInstance: function (inst) { // inst is an internal instance (but could be a composite) if (inst._renderedComponent) { inst = getHostComponentFromComposite(inst); } if (inst) { return ReactDOMComponentTree.getNodeFromInstance(inst); } else { return null; } } }, Mount: ReactMount, Reconciler: ReactReconciler }); } if ("development" !== 'production') { var ExecutionEnvironment = _dereq_(148); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { // Firefox does not have the issue with devtools loaded over file:// var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1; console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools'); } } var testFunc = function testFn() {}; "development" !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0; // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; "development" !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : void 0; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { "development" !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0; break; } } } } if ("development" !== 'production') { var ReactInstrumentation = _dereq_(73); var ReactDOMUnknownPropertyHook = _dereq_(57); var ReactDOMNullInputValuePropHook = _dereq_(49); ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook); ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook); } module.exports = ReactDOM; },{"123":123,"130":130,"141":141,"148":148,"171":171,"42":42,"49":49,"57":57,"60":60,"73":73,"76":76,"88":88,"96":96,"97":97}],39:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ 'use strict'; var DisabledInputUtils = _dereq_(14); /** * Implements a <button> host component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = { getHostProps: DisabledInputUtils.getHostProps }; module.exports = ReactDOMButton; },{"14":14}],40:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent */ /* global hasOwnProperty:true */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var AutoFocusUtils = _dereq_(1); var CSSPropertyOperations = _dereq_(4); var DOMLazyTree = _dereq_(8); var DOMNamespaces = _dereq_(9); var DOMProperty = _dereq_(10); var DOMPropertyOperations = _dereq_(11); var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPluginRegistry = _dereq_(18); var ReactBrowserEventEmitter = _dereq_(27); var ReactDOMButton = _dereq_(39); var ReactDOMComponentFlags = _dereq_(41); var ReactDOMComponentTree = _dereq_(42); var ReactDOMInput = _dereq_(48); var ReactDOMOption = _dereq_(50); var ReactDOMSelect = _dereq_(51); var ReactDOMTextarea = _dereq_(55); var ReactInstrumentation = _dereq_(73); var ReactMultiChild = _dereq_(77); var ReactServerRenderingTransaction = _dereq_(92); var emptyFunction = _dereq_(154); var escapeTextContentForBrowser = _dereq_(122); var invariant = _dereq_(162); var isEventSupported = _dereq_(136); var keyOf = _dereq_(166); var shallowEqual = _dereq_(170); var validateDOMNesting = _dereq_(146); var warning = _dereq_(171); var Flags = ReactDOMComponentFlags; var deleteListener = EventPluginHub.deleteListener; var getNode = ReactDOMComponentTree.getNodeFromInstance; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = EventPluginRegistry.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var STYLE = keyOf({ style: null }); var HTML = keyOf({ __html: null }); var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; // Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE). var DOC_FRAGMENT_TYPE = 11; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined because undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; "development" !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : void 0; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[component._tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : _prodInvariant('137', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? "development" !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : _prodInvariant('60') : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? "development" !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : _prodInvariant('61') : void 0; } if ("development" !== 'production') { "development" !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0; "development" !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : void 0; "development" !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0; } !(props.style == null || typeof props.style === 'object') ? "development" !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(component)) : _prodInvariant('62', getDeclarationErrorAddendum(component)) : void 0; } function enqueuePutListener(inst, registrationName, listener, transaction) { if (transaction instanceof ReactServerRenderingTransaction) { return; } if ("development" !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. "development" !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0; } var containerInfo = inst._hostContainerInfo; var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE; var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; listenTo(registrationName, doc); transaction.getReactMountReady().enqueue(putListener, { inst: inst, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener); } function inputPostMount() { var inst = this; ReactDOMInput.postMountWrapper(inst); } function textareaPostMount() { var inst = this; ReactDOMTextarea.postMountWrapper(inst); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } var setContentChildForInstrumentation = emptyFunction; if ("development" !== 'production') { setContentChildForInstrumentation = function (content) { var hasExistingContent = this._contentDebugID != null; var debugID = this._debugID; // This ID represents the inlined child that has no backing instance: var contentDebugID = -debugID; if (content == null) { if (hasExistingContent) { ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID); } this._contentDebugID = null; return; } this._contentDebugID = contentDebugID; if (hasExistingContent) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content); ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID); } else { ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID); ReactInstrumentation.debugTool.onMountComponent(contentDebugID); ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]); } }; } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? "development" !== 'production' ? invariant(false, 'Must be mounted to trap events') : _prodInvariant('63') : void 0; var node = getNode(inst); !node ? "development" !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : _prodInvariant('64') : void 0; switch (inst._tag) { case 'iframe': case 'object': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); } } break; case 'source': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node)]; break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)]; break; case 'input': case 'select': case 'textarea': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topInvalid, 'invalid', node)]; break; } } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; // NOTE: menuitem's close tag should be omitted, but that causes problems. var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = _assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? "development" !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : _prodInvariant('65', tag) : void 0; validatedTagCache[tag] = true; } } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } var globalIdCounter = 1; /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(element) { var tag = element.type; validateDangerousTag(tag); this._currentElement = element; this._tag = tag.toLowerCase(); this._namespaceURI = null; this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._hostNode = null; this._hostParent = null; this._rootNodeID = 0; this._domID = 0; this._hostContainerInfo = null; this._wrapperState = null; this._topLevelWrapper = null; this._flags = 0; if ("development" !== 'production') { this._ancestorInfo = null; setContentChildForInstrumentation.call(this, null); } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?ReactDOMComponent} the parent component instance * @param {?object} info about the host container * @param {object} context * @return {string} The computed markup. */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { this._rootNodeID = globalIdCounter++; this._domID = hostContainerInfo._idCounter++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var props = this._currentElement.props; switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'button': props = ReactDOMButton.getHostProps(this, props, hostParent); break; case 'input': ReactDOMInput.mountWrapper(this, props, hostParent); props = ReactDOMInput.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'option': ReactDOMOption.mountWrapper(this, props, hostParent); props = ReactDOMOption.getHostProps(this, props); break; case 'select': ReactDOMSelect.mountWrapper(this, props, hostParent); props = ReactDOMSelect.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, hostParent); props = ReactDOMTextarea.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; } assertValidProps(this, props); // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI; var parentTag; if (hostParent != null) { namespaceURI = hostParent._namespaceURI; parentTag = hostParent._tag; } else if (hostContainerInfo._tag) { namespaceURI = hostContainerInfo._namespaceURI; parentTag = hostContainerInfo._tag; } if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') { namespaceURI = DOMNamespaces.html; } if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'svg') { namespaceURI = DOMNamespaces.svg; } else if (this._tag === 'math') { namespaceURI = DOMNamespaces.mathml; } } this._namespaceURI = namespaceURI; if ("development" !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo._tag) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(this._tag, this, parentInfo); } this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var el; if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); var type = this._currentElement.type; div.innerHTML = '<' + type + '></' + type + '>'; el = div.removeChild(div.firstChild); } else if (props.is) { el = ownerDocument.createElement(this._currentElement.type, props.is); } else { // Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug. // See discussion in https://github.com/facebook/react/pull/6896 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 el = ownerDocument.createElement(this._currentElement.type); } } else { el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type); } ReactDOMComponentTree.precacheNode(this, el); this._flags |= Flags.hasCachedChildNodes; if (!this._hostParent) { DOMPropertyOperations.setAttributeForRoot(el); } this._updateDOMProperties(null, props, transaction); var lazyTree = DOMLazyTree(el); this._createInitialChildren(transaction, props, context, lazyTree); mountImage = lazyTree; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(inputPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'textarea': transaction.getReactMountReady().enqueue(textareaPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'select': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'button': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'option': transaction.getReactMountReady().enqueue(optionPostMount, this); break; } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if ("development" !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = _assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._hostParent) { ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID); return ret; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); if ("development" !== 'production') { setContentChildForInstrumentation.call(this, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, lazyTree) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node if ("development" !== 'production') { setContentChildForInstrumentation.call(this, contentToUse); } DOMLazyTree.queueText(lazyTree, contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { DOMLazyTree.queueChild(lazyTree, mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'button': lastProps = ReactDOMButton.getHostProps(this, lastProps); nextProps = ReactDOMButton.getHostProps(this, nextProps); break; case 'input': lastProps = ReactDOMInput.getHostProps(this, lastProps); nextProps = ReactDOMInput.getHostProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getHostProps(this, lastProps); nextProps = ReactDOMOption.getHostProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getHostProps(this, lastProps); nextProps = ReactDOMSelect.getHostProps(this, nextProps); break; case 'textarea': lastProps = ReactDOMTextarea.getHostProps(this, lastProps); nextProps = ReactDOMTextarea.getHostProps(this, nextProps); break; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction); this._updateDOMChildren(lastProps, nextProps, transaction, context); switch (this._tag) { case 'input': // Update the wrapper around inputs *after* updating props. This has to // happen after `_updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. ReactDOMInput.updateWrapper(this); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); break; case 'select': // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); break; } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, lastProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { if (nextProp) { if ("development" !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = _assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); if ("development" !== 'production') { setContentChildForInstrumentation.call(this, nextContent); } } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } else if (nextChildren != null) { if ("development" !== 'production') { setContentChildForInstrumentation.call(this, null); } this.updateChildren(nextChildren, transaction, context); } }, getHostNode: function () { return getNode(this); }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function (safely) { switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ !false ? "development" !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.', this._tag) : _prodInvariant('66', this._tag) : void 0; break; } this.unmountChildren(safely); ReactDOMComponentTree.uncacheNode(this); EventPluginHub.deleteAllListeners(this); this._rootNodeID = 0; this._domID = 0; this._wrapperState = null; if ("development" !== 'production') { setContentChildForInstrumentation.call(this, null); } }, getPublicInstance: function () { return getNode(this); } }; _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; },{"1":1,"10":10,"11":11,"122":122,"136":136,"140":140,"146":146,"154":154,"16":16,"162":162,"166":166,"17":17,"170":170,"171":171,"172":172,"18":18,"27":27,"39":39,"4":4,"41":41,"42":42,"48":48,"50":50,"51":51,"55":55,"73":73,"77":77,"8":8,"9":9,"92":92}],41:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponentFlags */ 'use strict'; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; module.exports = ReactDOMComponentFlags; },{}],42:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponentTree */ 'use strict'; var _prodInvariant = _dereq_(140); var DOMProperty = _dereq_(10); var ReactDOMComponentFlags = _dereq_(41); var invariant = _dereq_(162); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags; var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2); /** * Drill down (through composites and empty components) until we get a host or * host text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedHostOrTextFromComponent(component) { var rendered; while (rendered = component._renderedComponent) { component = rendered; } return component; } /** * Populate `_hostNode` on the rendered host/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var hostInst = getRenderedHostOrTextFromComponent(inst); hostInst._hostNode = node; node[internalInstanceKey] = hostInst; } function uncacheNode(inst) { var node = inst._hostNode; if (node) { delete node[internalInstanceKey]; inst._hostNode = null; } } /** * Populate `_hostNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (inst._flags & Flags.hasCachedChildNodes) { return; } var children = inst._renderedChildren; var childNode = node.firstChild; outer: for (var name in children) { if (!children.hasOwnProperty(name)) { continue; } var childInst = children[name]; var childID = getRenderedHostOrTextFromComponent(childInst)._domID; if (childID === 0) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } // We assume the child nodes are in the same order as the child instances. for (; childNode !== null; childNode = childNode.nextSibling) { if (childNode.nodeType === 1 && childNode.getAttribute(ATTR_NAME) === String(childID) || childNode.nodeType === 8 && childNode.nodeValue === ' react-text: ' + childID + ' ' || childNode.nodeType === 8 && childNode.nodeValue === ' react-empty: ' + childID + ' ') { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. !false ? "development" !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0; } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = getClosestInstanceFromNode(node); if (inst != null && inst._hostNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._hostNode !== undefined) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; if (inst._hostNode) { return inst._hostNode; } // Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; while (!inst._hostNode) { parents.push(inst); !inst._hostParent ? "development" !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0; inst = inst._hostParent; } // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (; parents.length; inst = parents.pop()) { precacheChildNodes(inst, inst._hostNode); } return inst._hostNode; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode }; module.exports = ReactDOMComponentTree; },{"10":10,"140":140,"162":162,"41":41}],43:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMContainerInfo */ 'use strict'; var validateDOMNesting = _dereq_(146); var DOC_NODE_TYPE = 9; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; if ("development" !== 'production') { info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null; } return info; } module.exports = ReactDOMContainerInfo; },{"146":146}],44:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * * @providesModule ReactDOMEmptyComponent */ 'use strict'; var _assign = _dereq_(172); var DOMLazyTree = _dereq_(8); var ReactDOMComponentTree = _dereq_(42); var ReactDOMEmptyComponent = function (instantiate) { // ReactCompositeComponent uses this: this._currentElement = null; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; this._hostContainerInfo = null; this._domID = 0; }; _assign(ReactDOMEmptyComponent.prototype, { mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var domID = hostContainerInfo._idCounter++; this._domID = domID; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var nodeValue = ' react-empty: ' + this._domID + ' '; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var node = ownerDocument.createComment(nodeValue); ReactDOMComponentTree.precacheNode(this, node); return DOMLazyTree(node); } else { if (transaction.renderToStaticMarkup) { // Normally we'd insert a comment node, but since this is a situation // where React won't take over (static pages), we can simply return // nothing. return ''; } return '<!--' + nodeValue + '-->'; } }, receiveComponent: function () {}, getHostNode: function () { return ReactDOMComponentTree.getNodeFromInstance(this); }, unmountComponent: function () { ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMEmptyComponent; },{"172":172,"42":42,"8":8}],45:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFactories */ 'use strict'; var ReactElement = _dereq_(61); /** * Create a factory that creates HTML tag elements. * * @private */ var createDOMFactory = ReactElement.createFactory; if ("development" !== 'production') { var ReactElementValidator = _dereq_(62); createDOMFactory = ReactElementValidator.createFactory; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = { a: createDOMFactory('a'), abbr: createDOMFactory('abbr'), address: createDOMFactory('address'), area: createDOMFactory('area'), article: createDOMFactory('article'), aside: createDOMFactory('aside'), audio: createDOMFactory('audio'), b: createDOMFactory('b'), base: createDOMFactory('base'), bdi: createDOMFactory('bdi'), bdo: createDOMFactory('bdo'), big: createDOMFactory('big'), blockquote: createDOMFactory('blockquote'), body: createDOMFactory('body'), br: createDOMFactory('br'), button: createDOMFactory('button'), canvas: createDOMFactory('canvas'), caption: createDOMFactory('caption'), cite: createDOMFactory('cite'), code: createDOMFactory('code'), col: createDOMFactory('col'), colgroup: createDOMFactory('colgroup'), data: createDOMFactory('data'), datalist: createDOMFactory('datalist'), dd: createDOMFactory('dd'), del: createDOMFactory('del'), details: createDOMFactory('details'), dfn: createDOMFactory('dfn'), dialog: createDOMFactory('dialog'), div: createDOMFactory('div'), dl: createDOMFactory('dl'), dt: createDOMFactory('dt'), em: createDOMFactory('em'), embed: createDOMFactory('embed'), fieldset: createDOMFactory('fieldset'), figcaption: createDOMFactory('figcaption'), figure: createDOMFactory('figure'), footer: createDOMFactory('footer'), form: createDOMFactory('form'), h1: createDOMFactory('h1'), h2: createDOMFactory('h2'), h3: createDOMFactory('h3'), h4: createDOMFactory('h4'), h5: createDOMFactory('h5'), h6: createDOMFactory('h6'), head: createDOMFactory('head'), header: createDOMFactory('header'), hgroup: createDOMFactory('hgroup'), hr: createDOMFactory('hr'), html: createDOMFactory('html'), i: createDOMFactory('i'), iframe: createDOMFactory('iframe'), img: createDOMFactory('img'), input: createDOMFactory('input'), ins: createDOMFactory('ins'), kbd: createDOMFactory('kbd'), keygen: createDOMFactory('keygen'), label: createDOMFactory('label'), legend: createDOMFactory('legend'), li: createDOMFactory('li'), link: createDOMFactory('link'), main: createDOMFactory('main'), map: createDOMFactory('map'), mark: createDOMFactory('mark'), menu: createDOMFactory('menu'), menuitem: createDOMFactory('menuitem'), meta: createDOMFactory('meta'), meter: createDOMFactory('meter'), nav: createDOMFactory('nav'), noscript: createDOMFactory('noscript'), object: createDOMFactory('object'), ol: createDOMFactory('ol'), optgroup: createDOMFactory('optgroup'), option: createDOMFactory('option'), output: createDOMFactory('output'), p: createDOMFactory('p'), param: createDOMFactory('param'), picture: createDOMFactory('picture'), pre: createDOMFactory('pre'), progress: createDOMFactory('progress'), q: createDOMFactory('q'), rp: createDOMFactory('rp'), rt: createDOMFactory('rt'), ruby: createDOMFactory('ruby'), s: createDOMFactory('s'), samp: createDOMFactory('samp'), script: createDOMFactory('script'), section: createDOMFactory('section'), select: createDOMFactory('select'), small: createDOMFactory('small'), source: createDOMFactory('source'), span: createDOMFactory('span'), strong: createDOMFactory('strong'), style: createDOMFactory('style'), sub: createDOMFactory('sub'), summary: createDOMFactory('summary'), sup: createDOMFactory('sup'), table: createDOMFactory('table'), tbody: createDOMFactory('tbody'), td: createDOMFactory('td'), textarea: createDOMFactory('textarea'), tfoot: createDOMFactory('tfoot'), th: createDOMFactory('th'), thead: createDOMFactory('thead'), time: createDOMFactory('time'), title: createDOMFactory('title'), tr: createDOMFactory('tr'), track: createDOMFactory('track'), u: createDOMFactory('u'), ul: createDOMFactory('ul'), 'var': createDOMFactory('var'), video: createDOMFactory('video'), wbr: createDOMFactory('wbr'), // SVG circle: createDOMFactory('circle'), clipPath: createDOMFactory('clipPath'), defs: createDOMFactory('defs'), ellipse: createDOMFactory('ellipse'), g: createDOMFactory('g'), image: createDOMFactory('image'), line: createDOMFactory('line'), linearGradient: createDOMFactory('linearGradient'), mask: createDOMFactory('mask'), path: createDOMFactory('path'), pattern: createDOMFactory('pattern'), polygon: createDOMFactory('polygon'), polyline: createDOMFactory('polyline'), radialGradient: createDOMFactory('radialGradient'), rect: createDOMFactory('rect'), stop: createDOMFactory('stop'), svg: createDOMFactory('svg'), text: createDOMFactory('text'), tspan: createDOMFactory('tspan') }; module.exports = ReactDOMFactories; },{"61":61,"62":62}],46:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFeatureFlags */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: true }; module.exports = ReactDOMFeatureFlags; },{}],47:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations */ 'use strict'; var DOMChildrenOperations = _dereq_(7); var ReactDOMComponentTree = _dereq_(42); /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); } }; module.exports = ReactDOMIDOperations; },{"42":42,"7":7}],48:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var DisabledInputUtils = _dereq_(14); var DOMPropertyOperations = _dereq_(11); var LinkedValueUtils = _dereq_(24); var ReactDOMComponentTree = _dereq_(42); var ReactUpdates = _dereq_(96); var invariant = _dereq_(162); var warning = _dereq_(171); var didWarnValueLink = false; var didWarnCheckedLink = false; var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } function isControlled(props) { var usesChecked = props.type === 'checkbox' || props.type === 'radio'; return usesChecked ? props.checked !== undefined : props.value !== undefined; } /** * Implements an <input> host component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getHostProps: function (inst, props) { var value = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var hostProps = _assign({ // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type: undefined, // Make sure we set .step before .value (setting .value before .step // means .value is rounded on mount, based upon step precision) step: undefined, // Make sure we set .min & .max before .value (to ensure proper order // in corner cases such as min or max deriving from value, e.g. Issue #7170) min: undefined, max: undefined }, DisabledInputUtils.getHostProps(inst, props), { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if ("development" !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); var owner = inst._currentElement._owner; if (props.valueLink !== undefined && !didWarnValueLink) { "development" !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.checkedLink !== undefined && !didWarnCheckedLink) { "development" !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnCheckedLink = true; } if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { "development" !== 'production' ? warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { "development" !== 'production' ? warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnValueDefaultValue = true; } } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: props.value != null ? props.value : defaultValue, listeners: null, onChange: _handleChange.bind(inst) }; if ("development" !== 'production') { inst._wrapperState.controlled = isControlled(props); } }, updateWrapper: function (inst) { var props = inst._currentElement.props; if ("development" !== 'production') { var controlled = isControlled(props); var owner = inst._currentElement._owner; if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { "development" !== 'production' ? warning(false, '%s is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnUncontrolledToControlled = true; } if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { "development" !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnControlledToUncontrolled = true; } } // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false); } var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } } else { if (props.value == null && props.defaultValue != null) { node.defaultValue = '' + props.defaultValue; } if (props.checked == null && props.defaultChecked != null) { node.defaultChecked = !!props.defaultChecked; } } }, postMountWrapper: function (inst) { var props = inst._currentElement.props; // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); // Detach value from defaultValue. We won't do anything if we're working on // submit or reset inputs as those values & defaultValues are linked. They // are not resetable nodes so this operation doesn't matter and actually // removes browser-default values (eg "Submit Query") when no value is // provided. switch (props.type) { case 'submit': case 'reset': break; case 'color': case 'date': case 'datetime': case 'datetime-local': case 'month': case 'time': case 'week': // This fixes the no-show issue on iOS Safari and Android Chrome: // https://github.com/facebook/react/issues/7233 node.value = ''; node.value = node.defaultValue; break; default: node.value = node.value; break; } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug // this is needed to work around a chrome bug where setting defaultChecked // will sometimes influence the value of checked (even after detachment). // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 // We need to temporarily unset name to avoid disrupting radio button groups. var name = node.name; if (name !== '') { node.name = ''; } node.defaultChecked = !node.defaultChecked; node.defaultChecked = !node.defaultChecked; if (name !== '') { node.name = name; } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactDOMComponentTree.getNodeFromInstance(this); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode); !otherInstance ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : _prodInvariant('90') : void 0; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; },{"11":11,"14":14,"140":140,"162":162,"171":171,"172":172,"24":24,"42":42,"96":96}],49:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMNullInputValuePropHook */ 'use strict'; var ReactComponentTreeHook = _dereq_(35); var warning = _dereq_(171); var didWarnValueNull = false; function handleElement(debugID, element) { if (element == null) { return; } if (element.type !== 'input' && element.type !== 'textarea' && element.type !== 'select') { return; } if (element.props != null && element.props.value === null && !didWarnValueNull) { "development" !== 'production' ? warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; didWarnValueNull = true; } } var ReactDOMNullInputValuePropHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMNullInputValuePropHook; },{"171":171,"35":35}],50:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ 'use strict'; var _assign = _dereq_(172); var ReactChildren = _dereq_(29); var ReactDOMComponentTree = _dereq_(42); var ReactDOMSelect = _dereq_(51); var warning = _dereq_(171); var didWarnInvalidOptionChildren = false; function flattenChildren(children) { var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. ReactChildren.forEach(children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; "development" !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0; } }); return content; } /** * Implements an <option> host component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, hostParent) { // TODO (yungsters): Remove support for `selected` in <option>. if ("development" !== 'production') { "development" !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0; } // Look up whether this option is 'selected' var selectValue = null; if (hostParent != null) { var selectParent = hostParent; if (selectParent._tag === 'optgroup') { selectParent = selectParent._hostParent; } if (selectParent != null && selectParent._tag === 'select') { selectValue = ReactDOMSelect.getSelectValueContext(selectParent); } } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { var value; if (props.value != null) { value = props.value + ''; } else { value = flattenChildren(props.children); } selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } } inst._wrapperState = { selected: selected }; }, postMountWrapper: function (inst) { // value="" should make a value attribute (#6219) var props = inst._currentElement.props; if (props.value != null) { var node = ReactDOMComponentTree.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getHostProps: function (inst, props) { var hostProps = _assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { hostProps.selected = inst._wrapperState.selected; } var content = flattenChildren(props.children); if (content) { hostProps.children = content; } return hostProps; } }; module.exports = ReactDOMOption; },{"171":171,"172":172,"29":29,"42":42,"51":51}],51:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ 'use strict'; var _assign = _dereq_(172); var DisabledInputUtils = _dereq_(14); var LinkedValueUtils = _dereq_(24); var ReactDOMComponentTree = _dereq_(42); var ReactUpdates = _dereq_(96); var warning = _dereq_(171); var didWarnValueLink = false; var didWarnValueDefaultValue = false; function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); if (props.valueLink !== undefined && !didWarnValueLink) { "development" !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { "development" !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } else if (!props.multiple && isArray) { "development" !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactDOMComponentTree.getNodeFromInstance(inst).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> host component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { getHostProps: function (inst, props) { return _assign({}, DisabledInputUtils.getHostProps(inst, props), { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if ("development" !== 'production') { checkSelectPropTypes(inst, props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, listeners: null, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { "development" !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValueDefaultValue = true; } }, getSelectValueContext: function (inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); if (this._rootNodeID) { this._wrapperState.pendingUpdate = true; } ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; },{"14":14,"171":171,"172":172,"24":24,"42":42,"96":96}],52:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ 'use strict'; var ExecutionEnvironment = _dereq_(148); var getNodeForCharacterOffset = _dereq_(132); var getTextContentAccessor = _dereq_(133); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (offsets.end === undefined) { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; },{"132":132,"133":133,"148":148}],53:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMServer */ 'use strict'; var ReactDefaultInjection = _dereq_(60); var ReactServerRendering = _dereq_(91); var ReactVersion = _dereq_(97); ReactDefaultInjection.inject(); var ReactDOMServer = { renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, version: ReactVersion }; module.exports = ReactDOMServer; },{"60":60,"91":91,"97":97}],54:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextComponent */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var DOMChildrenOperations = _dereq_(7); var DOMLazyTree = _dereq_(8); var ReactDOMComponentTree = _dereq_(42); var escapeTextContentForBrowser = _dereq_(122); var invariant = _dereq_(162); var validateDOMNesting = _dereq_(146); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings between comment nodes so that they * can undergo the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; // Properties this._domID = 0; this._mountIndex = 0; this._closingComment = null; this._commentNodes = null; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { if ("development" !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo != null) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting('#text', this, parentInfo); } } var domID = hostContainerInfo._idCounter++; var openingValue = ' react-text: ' + domID + ' '; var closingValue = ' /react-text '; this._domID = domID; this._hostParent = hostParent; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var openingComment = ownerDocument.createComment(openingValue); var closingComment = ownerDocument.createComment(closingValue); var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment()); DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)); if (this._stringText) { DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)); ReactDOMComponentTree.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getHostNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); } } }, getHostNode: function () { var hostNode = this._commentNodes; if (hostNode) { return hostNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? "development" !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0; if (node.nodeType === 8 && node.nodeValue === ' /react-text ') { this._closingComment = node; break; } node = node.nextSibling; } } hostNode = [this._hostNode, this._closingComment]; this._commentNodes = hostNode; return hostNode; }, unmountComponent: function () { this._closingComment = null; this._commentNodes = null; ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMTextComponent; },{"122":122,"140":140,"146":146,"162":162,"172":172,"42":42,"7":7,"8":8}],55:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var DisabledInputUtils = _dereq_(14); var LinkedValueUtils = _dereq_(24); var ReactDOMComponentTree = _dereq_(42); var ReactUpdates = _dereq_(96); var invariant = _dereq_(162); var warning = _dereq_(171); var didWarnValueLink = false; var didWarnValDefaultVal = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } /** * Implements a <textarea> host component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getHostProps: function (inst, props) { !(props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : _prodInvariant('91') : void 0; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. We could add a check in setTextContent // to only set the value if/when the value differs from the node value (which would // completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution. // The value can be a boolean or object so that's why it's forced to be a string. var hostProps = _assign({}, DisabledInputUtils.getHostProps(inst, props), { value: undefined, defaultValue: undefined, children: '' + inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if ("development" !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); if (props.valueLink !== undefined && !didWarnValueLink) { "development" !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { "development" !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValDefaultVal = true; } } var value = LinkedValueUtils.getValue(props); var initialValue = value; // Only bother fetching default value if we're going to use it if (value == null) { var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if ("development" !== 'production') { "development" !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0; } !(defaultValue == null) ? "development" !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : _prodInvariant('92') : void 0; if (Array.isArray(children)) { !(children.length <= 1) ? "development" !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : _prodInvariant('93') : void 0; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } inst._wrapperState = { initialValue: '' + initialValue, listeners: null, onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } if (props.defaultValue == null) { node.defaultValue = newValue; } } if (props.defaultValue != null) { node.defaultValue = props.defaultValue; } }, postMountWrapper: function (inst) { // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); // Warning: node.value may be the empty string at this point (IE11) if placeholder is set. node.value = node.textContent; // Detach value from defaultValue } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; },{"14":14,"140":140,"162":162,"171":171,"172":172,"24":24,"42":42,"96":96}],56:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTreeTraversal */ 'use strict'; var _prodInvariant = _dereq_(140); var invariant = _dereq_(162); /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { !('_hostNode' in instA) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; !('_hostNode' in instB) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; var depthA = 0; for (var tempA = instA; tempA; tempA = tempA._hostParent) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = tempB._hostParent) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = instA._hostParent; depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = instB._hostParent; depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB) { return instA; } instA = instA._hostParent; instB = instB._hostParent; } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { !('_hostNode' in instA) ? "development" !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; !('_hostNode' in instB) ? "development" !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; while (instB) { if (instB === instA) { return true; } instB = instB._hostParent; } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { !('_hostNode' in inst) ? "development" !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0; return inst._hostParent; } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = inst._hostParent; } var i; for (i = path.length; i-- > 0;) { fn(path[i], false, arg); } for (i = 0; i < path.length; i++) { fn(path[i], true, arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = from._hostParent; } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = to._hostParent; } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], true, argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], false, argTo); } } module.exports = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; },{"140":140,"162":162}],57:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMUnknownPropertyHook */ 'use strict'; var DOMProperty = _dereq_(10); var EventPluginRegistry = _dereq_(18); var ReactComponentTreeHook = _dereq_(35); var warning = _dereq_(171); if ("development" !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, valueLink: true, defaultChecked: true, checkedLink: true, innerHTML: true, suppressContentEditableWarning: true, onFocusIn: true, onFocusOut: true }; var warnedProperties = {}; var validateProperty = function (tagName, name, debugID) { if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) { return true; } if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return true; } if (EventPluginRegistry.registrationNameModules.hasOwnProperty(name)) { return true; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null; if (standardName != null) { "development" !== 'production' ? warning(false, 'Unknown DOM property %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else if (registrationName != null) { "development" !== 'production' ? warning(false, 'Unknown event handler property %s. Did you mean `%s`?%s', name, registrationName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else { // We were unable to guess which prop the user intended. // It is likely that the user was just blindly spreading/forwarding props // Components should be careful to only render valid props/attributes. // Warning will be invoked in warnUnknownProperties to allow grouping. return false; } }; } var warnUnknownProperties = function (debugID, element) { var unknownProps = []; for (var key in element.props) { var isValid = validateProperty(element.type, key, debugID); if (!isValid) { unknownProps.push(key); } } var unknownPropString = unknownProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (unknownProps.length === 1) { "development" !== 'production' ? warning(false, 'Unknown prop %s on <%s> tag. Remove this prop from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } else if (unknownProps.length > 1) { "development" !== 'production' ? warning(false, 'Unknown props %s on <%s> tag. Remove these props from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } }; function handleElement(debugID, element) { if (element == null || typeof element.type !== 'string') { return; } if (element.type.indexOf('-') >= 0 || element.props.is) { return; } warnUnknownProperties(debugID, element); } var ReactDOMUnknownPropertyHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMUnknownPropertyHook; },{"10":10,"171":171,"18":18,"35":35}],58:[function(_dereq_,module,exports){ /** * Copyright 2016-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. * * @providesModule ReactDebugTool */ 'use strict'; var ReactInvalidSetStateWarningHook = _dereq_(74); var ReactHostOperationHistoryHook = _dereq_(69); var ReactComponentTreeHook = _dereq_(35); var ReactChildrenMutationWarningHook = _dereq_(30); var ExecutionEnvironment = _dereq_(148); var performanceNow = _dereq_(169); var warning = _dereq_(171); var hooks = []; var didHookThrowForEvent = {}; function callHook(event, fn, context, arg1, arg2, arg3, arg4, arg5) { try { fn.call(context, arg1, arg2, arg3, arg4, arg5); } catch (e) { "development" !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0; didHookThrowForEvent[event] = true; } } function emitEvent(event, arg1, arg2, arg3, arg4, arg5) { for (var i = 0; i < hooks.length; i++) { var hook = hooks[i]; var fn = hook[event]; if (fn) { callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); } } } var isProfiling = false; var flushHistory = []; var lifeCycleTimerStack = []; var currentFlushNesting = 0; var currentFlushMeasurements = null; var currentFlushStartTime = null; var currentTimerDebugID = null; var currentTimerStartTime = null; var currentTimerNestedFlushDuration = null; var currentTimerType = null; var lifeCycleTimerHasWarned = false; function clearHistory() { ReactComponentTreeHook.purgeUnmountedComponents(); ReactHostOperationHistoryHook.clearHistory(); } function getTreeSnapshot(registeredIDs) { return registeredIDs.reduce(function (tree, id) { var ownerID = ReactComponentTreeHook.getOwnerID(id); var parentID = ReactComponentTreeHook.getParentID(id); tree[id] = { displayName: ReactComponentTreeHook.getDisplayName(id), text: ReactComponentTreeHook.getText(id), updateCount: ReactComponentTreeHook.getUpdateCount(id), childIDs: ReactComponentTreeHook.getChildIDs(id), // Text nodes don't have owners but this is close enough. ownerID: ownerID || ReactComponentTreeHook.getOwnerID(parentID), parentID: parentID }; return tree; }, {}); } function resetMeasurements() { var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements || []; var previousOperations = ReactHostOperationHistoryHook.getHistory(); if (currentFlushNesting === 0) { currentFlushStartTime = null; currentFlushMeasurements = null; clearHistory(); return; } if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(); currentFlushStartTime = performanceNow(); currentFlushMeasurements = []; } function checkDebugID(debugID) { var allowRoot = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (allowRoot && debugID === 0) { return; } if (!debugID) { "development" !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0; } } function beginLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType && !lifeCycleTimerHasWarned) { "development" !== 'production' ? warning(false, '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.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } currentTimerStartTime = performanceNow(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; } function endLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { "development" !== 'production' ? warning(false, '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.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } if (isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = null; currentTimerNestedFlushDuration = null; currentTimerDebugID = null; currentTimerType = null; } function pauseCurrentLifeCycleTimer() { var currentTimer = { startTime: currentTimerStartTime, nestedFlushStartTime: performanceNow(), debugID: currentTimerDebugID, timerType: currentTimerType }; lifeCycleTimerStack.push(currentTimer); currentTimerStartTime = null; currentTimerNestedFlushDuration = null; currentTimerDebugID = null; currentTimerType = null; } function resumeCurrentLifeCycleTimer() { var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(); var startTime = _lifeCycleTimerStack$.startTime; var nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime; var debugID = _lifeCycleTimerStack$.debugID; var timerType = _lifeCycleTimerStack$.timerType; var nestedFlushDuration = performanceNow() - nestedFlushStartTime; currentTimerStartTime = startTime; currentTimerNestedFlushDuration += nestedFlushDuration; currentTimerDebugID = debugID; currentTimerType = timerType; } var ReactDebugTool = { addHook: function (hook) { hooks.push(hook); }, removeHook: function (hook) { for (var i = 0; i < hooks.length; i++) { if (hooks[i] === hook) { hooks.splice(i, 1); i--; } } }, isProfiling: function () { return isProfiling; }, beginProfiling: function () { if (isProfiling) { return; } isProfiling = true; flushHistory.length = 0; resetMeasurements(); ReactDebugTool.addHook(ReactHostOperationHistoryHook); }, endProfiling: function () { if (!isProfiling) { return; } isProfiling = false; resetMeasurements(); ReactDebugTool.removeHook(ReactHostOperationHistoryHook); }, getFlushHistory: function () { return flushHistory; }, onBeginFlush: function () { currentFlushNesting++; resetMeasurements(); pauseCurrentLifeCycleTimer(); emitEvent('onBeginFlush'); }, onEndFlush: function () { resetMeasurements(); currentFlushNesting--; resumeCurrentLifeCycleTimer(); emitEvent('onEndFlush'); }, onBeginLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); emitEvent('onBeginLifeCycleTimer', debugID, timerType); beginLifeCycleTimer(debugID, timerType); }, onEndLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); endLifeCycleTimer(debugID, timerType); emitEvent('onEndLifeCycleTimer', debugID, timerType); }, onError: function (debugID) { if (currentTimerDebugID != null) { endLifeCycleTimer(currentTimerDebugID, currentTimerType); } emitEvent('onError', debugID); }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onHostOperation: function (debugID, type, payload) { checkDebugID(debugID); emitEvent('onHostOperation', debugID, type, payload); }, onSetState: function () { emitEvent('onSetState'); }, onSetChildren: function (debugID, childDebugIDs) { checkDebugID(debugID); childDebugIDs.forEach(checkDebugID); emitEvent('onSetChildren', debugID, childDebugIDs); }, onBeforeMountComponent: function (debugID, element, parentDebugID) { checkDebugID(debugID); checkDebugID(parentDebugID, true); emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); }, onMountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onMountComponent', debugID); }, onBeforeUpdateComponent: function (debugID, element) { checkDebugID(debugID); emitEvent('onBeforeUpdateComponent', debugID, element); }, onUpdateComponent: function (debugID) { checkDebugID(debugID); emitEvent('onUpdateComponent', debugID); }, onBeforeUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onBeforeUnmountComponent', debugID); }, onUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onUnmountComponent', debugID); }, onTestEvent: function () { emitEvent('onTestEvent'); } }; // TODO remove these when RN/www gets updated ReactDebugTool.addDevtool = ReactDebugTool.addHook; ReactDebugTool.removeDevtool = ReactDebugTool.removeHook; ReactDebugTool.addHook(ReactInvalidSetStateWarningHook); ReactDebugTool.addHook(ReactComponentTreeHook); ReactDebugTool.addHook(ReactChildrenMutationWarningHook); var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { ReactDebugTool.beginProfiling(); } module.exports = ReactDebugTool; },{"148":148,"169":169,"171":171,"30":30,"35":35,"69":69,"74":74}],59:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ 'use strict'; var _assign = _dereq_(172); var ReactUpdates = _dereq_(96); var Transaction = _dereq_(114); var emptyFunction = _dereq_(154); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } _assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; },{"114":114,"154":154,"172":172,"96":96}],60:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ 'use strict'; var BeforeInputEventPlugin = _dereq_(2); var ChangeEventPlugin = _dereq_(6); var DefaultEventPluginOrder = _dereq_(13); var EnterLeaveEventPlugin = _dereq_(15); var HTMLDOMPropertyConfig = _dereq_(22); var ReactComponentBrowserEnvironment = _dereq_(33); var ReactDOMComponent = _dereq_(40); var ReactDOMComponentTree = _dereq_(42); var ReactDOMEmptyComponent = _dereq_(44); var ReactDOMTreeTraversal = _dereq_(56); var ReactDOMTextComponent = _dereq_(54); var ReactDefaultBatchingStrategy = _dereq_(59); var ReactEventListener = _dereq_(66); var ReactInjection = _dereq_(70); var ReactReconcileTransaction = _dereq_(87); var SVGDOMPropertyConfig = _dereq_(98); var SelectEventPlugin = _dereq_(99); var SimpleEventPlugin = _dereq_(100); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree); ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.HostComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent(instantiate); }); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); } module.exports = { inject: inject }; },{"100":100,"13":13,"15":15,"2":2,"22":22,"33":33,"40":40,"42":42,"44":44,"54":54,"56":56,"59":59,"6":6,"66":66,"70":70,"87":87,"98":98,"99":99}],61:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * * @providesModule ReactElement */ 'use strict'; var _assign = _dereq_(172); var ReactCurrentOwner = _dereq_(37); var warning = _dereq_(171); var canDefineProperty = _dereq_(118); var hasOwnProperty = Object.prototype.hasOwnProperty; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; function hasValidRef(config) { if ("development" !== 'production') { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { if ("development" !== 'production') { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; "development" !== 'production' ? warning(false, '%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)', displayName) : void 0; } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; "development" !== 'production' ? warning(false, '%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)', displayName) : void 0; } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if ("development" !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; var shadowChildren = Array.isArray(props.children) ? props.children.slice(0) : props.children; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); Object.defineProperty(element, '_shadowChildren', { configurable: false, enumerable: false, writable: false, value: shadowChildren }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._shadowChildren = shadowChildren; element._source = source; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if ("development" !== 'production') { "development" !== 'production' ? warning( /* eslint-disable no-proto */ config.__proto__ == null || config.__proto__ === Object.prototype, /* eslint-enable no-proto */ 'React.createElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0; } if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if ("development" !== 'production') { if (key || ref) { if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if ("development" !== 'production') { "development" !== 'production' ? warning( /* eslint-disable no-proto */ config.__proto__ == null || config.__proto__ === Object.prototype, /* eslint-enable no-proto */ 'React.cloneElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0; } if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; ReactElement.REACT_ELEMENT_TYPE = REACT_ELEMENT_TYPE; module.exports = ReactElement; },{"118":118,"171":171,"172":172,"37":37}],62:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * * @providesModule ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactCurrentOwner = _dereq_(37); var ReactComponentTreeHook = _dereq_(35); var ReactElement = _dereq_(61); var ReactPropTypeLocations = _dereq_(83); var checkReactTypeSpec = _dereq_(119); var canDefineProperty = _dereq_(118); var getIteratorFn = _dereq_(131); var warning = _dereq_(171); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = ' Check the top-level render call using <' + parentName + '>.'; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {}); var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (memoizer[currentComponentErrorInfo]) { return; } memoizer[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } "development" !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkReactTypeSpec(componentClass.propTypes, element.props, ReactPropTypeLocations.prop, name, element, null); } if (typeof componentClass.getDefaultProps === 'function') { "development" !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { "development" !== 'production' ? warning(false, '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', getDeclarationErrorAddendum()) : void 0; } var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if ("development" !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { "development" !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; },{"118":118,"119":119,"131":131,"171":171,"35":35,"37":37,"61":61,"83":83}],63:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * * @providesModule ReactEmptyComponent */ 'use strict'; var emptyComponentFactory; var ReactEmptyComponentInjection = { injectEmptyComponentFactory: function (factory) { emptyComponentFactory = factory; } }; var ReactEmptyComponent = { create: function (instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; },{}],64:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactErrorUtils */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {?String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a, b) { try { return func(a, b); } catch (x) { if (caughtError === null) { caughtError = x; } return undefined; } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if ("development" !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) { var boundFunc = func.bind(null, a, b); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; },{}],65:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ 'use strict'; var EventPluginHub = _dereq_(17); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"17":17}],66:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener */ 'use strict'; var _assign = _dereq_(172); var EventListener = _dereq_(147); var ExecutionEnvironment = _dereq_(148); var PooledClass = _dereq_(25); var ReactDOMComponentTree = _dereq_(42); var ReactUpdates = _dereq_(96); var getEventTarget = _dereq_(129); var getUnboundedScrollPosition = _dereq_(159); /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findParent(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. while (inst._hostParent) { inst = inst._hostParent; } var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst); var container = rootNode.parentNode; return ReactDOMComponentTree.getClosestInstanceFromNode(container); } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } _assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent); var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget); // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = targetInst; do { bookKeeping.ancestors.push(ancestor); ancestor = ancestor && findParent(ancestor); } while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) { targetInst = bookKeeping.ancestors[i]; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; },{"129":129,"147":147,"148":148,"159":159,"172":172,"25":25,"42":42,"96":96}],67:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactFeatureFlags * */ 'use strict'; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false }; module.exports = ReactFeatureFlags; },{}],68:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * * @providesModule ReactHostComponent */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var invariant = _dereq_(162); var genericComponentClass = null; // This registry keeps track of wrapper classes around host tags. var tagToComponentClass = {}; var textComponentClass = null; var ReactHostComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function (componentClasses) { _assign(tagToComponentClass, componentClasses); } }; /** * Get a host internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? "development" !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : _prodInvariant('111', element.type) : void 0; return new genericComponentClass(element); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactHostComponent = { createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactHostComponentInjection }; module.exports = ReactHostComponent; },{"140":140,"162":162,"172":172}],69:[function(_dereq_,module,exports){ /** * Copyright 2016-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. * * @providesModule ReactHostOperationHistoryHook */ 'use strict'; var history = []; var ReactHostOperationHistoryHook = { onHostOperation: function (debugID, type, payload) { history.push({ instanceID: debugID, type: type, payload: payload }); }, clearHistory: function () { if (ReactHostOperationHistoryHook._preventClearing) { // Should only be used for tests. return; } history = []; }, getHistory: function () { return history; } }; module.exports = ReactHostOperationHistoryHook; },{}],70:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ 'use strict'; var DOMProperty = _dereq_(10); var EventPluginHub = _dereq_(17); var EventPluginUtils = _dereq_(19); var ReactComponentEnvironment = _dereq_(34); var ReactClass = _dereq_(31); var ReactEmptyComponent = _dereq_(63); var ReactBrowserEventEmitter = _dereq_(27); var ReactHostComponent = _dereq_(68); var ReactUpdates = _dereq_(96); var ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventPluginUtils: EventPluginUtils.injection, EventEmitter: ReactBrowserEventEmitter.injection, HostComponent: ReactHostComponent.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"10":10,"17":17,"19":19,"27":27,"31":31,"34":34,"63":63,"68":68,"96":96}],71:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ 'use strict'; var ReactDOMSelection = _dereq_(52); var containsNode = _dereq_(151); var focusNode = _dereq_(156); var getActiveElement = _dereq_(157); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; },{"151":151,"156":156,"157":157,"52":52}],72:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceMap */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; },{}],73:[function(_dereq_,module,exports){ /** * Copyright 2016-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. * * @providesModule ReactInstrumentation */ 'use strict'; var debugTool = null; if ("development" !== 'production') { var ReactDebugTool = _dereq_(58); debugTool = ReactDebugTool; } module.exports = { debugTool: debugTool }; },{"58":58}],74:[function(_dereq_,module,exports){ /** * Copyright 2016-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. * * @providesModule ReactInvalidSetStateWarningHook */ 'use strict'; var warning = _dereq_(171); if ("development" !== 'production') { var processingChildContext = false; var warnInvalidSetState = function () { "development" !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0; }; } var ReactInvalidSetStateWarningHook = { onBeginProcessingChildContext: function () { processingChildContext = true; }, onEndProcessingChildContext: function () { processingChildContext = false; }, onSetState: function () { warnInvalidSetState(); } }; module.exports = ReactInvalidSetStateWarningHook; },{"171":171}],75:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ 'use strict'; var adler32 = _dereq_(117); var TAG_END = /\/?>/; var COMMENT_START = /^<\!\-\-/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags, comments and self-closing tags) if (COMMENT_START.test(markup)) { return markup; } else { return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); } }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; },{"117":117}],76:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMount */ 'use strict'; var _prodInvariant = _dereq_(140); var DOMLazyTree = _dereq_(8); var DOMProperty = _dereq_(10); var ReactBrowserEventEmitter = _dereq_(27); var ReactCurrentOwner = _dereq_(37); var ReactDOMComponentTree = _dereq_(42); var ReactDOMContainerInfo = _dereq_(43); var ReactDOMFeatureFlags = _dereq_(46); var ReactElement = _dereq_(61); var ReactFeatureFlags = _dereq_(67); var ReactInstanceMap = _dereq_(72); var ReactInstrumentation = _dereq_(73); var ReactMarkupChecksum = _dereq_(75); var ReactReconciler = _dereq_(88); var ReactUpdateQueue = _dereq_(95); var ReactUpdates = _dereq_(96); var emptyObject = _dereq_(155); var instantiateReactComponent = _dereq_(135); var invariant = _dereq_(162); var setInnerHTML = _dereq_(142); var shouldUpdateReactComponent = _dereq_(144); var warning = _dereq_(171); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var instancesByReactRootID = {}; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) { var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var wrappedElement = wrapperInstance._currentElement.props; var type = wrappedElement.type; markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name); console.time(markerName); } var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context, 0 /* parentDebugID */ ); if (markerName) { console.timeEnd(markerName); } wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance; ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container, safely) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onBeginFlush(); } ReactReconciler.unmountComponent(instance, safely); if ("development" !== 'production') { ReactInstrumentation.debugTool.onEndFlush(); } if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._hostParent); } } /** * True if the supplied DOM node is a React DOM element and * it has been rendered by another copy of React. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM has been rendered by another copy of React * @internal */ function nodeIsRenderedByOtherInstance(container) { var rootEl = getReactRootElementInContainer(container); return !!(rootEl && isReactNode(rootEl) && !ReactDOMComponentTree.getInstanceFromNode(rootEl)); } /** * True if the supplied DOM node is a valid node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid DOM node. * @internal */ function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE_TYPE || node.nodeType === DOC_NODE_TYPE || node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)); } /** * True if the supplied DOM node is a valid React node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid React DOM node. * @internal */ function isReactNode(node) { return isValidContainer(node) && (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME)); } function getHostRootInstanceInContainer(container) { var rootEl = getReactRootElementInContainer(container); var prevHostInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl); return prevHostInstance && !prevHostInstance._hostParent ? prevHostInstance : null; } function getTopLevelWrapperInContainer(container) { var root = getHostRootInstanceInContainer(container); return root ? root._hostContainerInfo._topLevelWrapper : null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var topLevelRootCounter = 1; var TopLevelWrapper = function () { this.rootID = topLevelRootCounter++; }; TopLevelWrapper.prototype.isReactComponent = {}; if ("development" !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { // this.props is actually a ReactElement return this.props; }; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** * Used by devtools. The keys are not important. */ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, nextContext, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement, nextContext); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); return prevComponent; }, /** * Render a new component into the DOM. Hooked by hooks! * * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. "development" !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? "development" !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement, false); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && ReactInstanceMap.has(parentComponent)) ? "development" !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : _prodInvariant('38') : void 0; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render'); !ReactElement.isValidElement(nextElement) ? "development" !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : _prodInvariant('39', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : void 0; "development" !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0; var nextWrappedElement = ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement); var nextContext; if (parentComponent) { var parentInst = ReactInstanceMap.get(parentComponent); nextContext = parentInst._processChildContext(parentInst._context); } else { nextContext = emptyObject; } var prevComponent = getTopLevelWrapperInContainer(container); if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, nextContext, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if ("development" !== 'production') { "development" !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { "development" !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : void 0; break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, nextContext)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.render * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Unmounts and destroys the React component rendered in the `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.unmountcomponentatnode * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) "development" !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? "development" !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : _prodInvariant('40') : void 0; if ("development" !== 'production') { "development" !== 'production' ? warning(!nodeIsRenderedByOtherInstance(container), 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by another copy of React.') : void 0; } var prevComponent = getTopLevelWrapperInContainer(container); if (!prevComponent) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME); if ("development" !== 'production') { "development" !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0; } return false; } delete instancesByReactRootID[prevComponent._instance.rootID]; ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false); return true; }, _mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) { !isValidContainer(container) ? "development" !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : _prodInvariant('41') : void 0; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { ReactDOMComponentTree.precacheNode(instance, rootElement); return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if ("development" !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s', difference) : _prodInvariant('42', difference) : void 0; if ("development" !== 'production') { "development" !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : void 0; } } } !(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but you didn\'t use server rendering. We can\'t do this without using server rendering due to cross-browser quirks. See ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('43') : void 0; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } DOMLazyTree.insertTreeBefore(container, markup, null); } else { setInnerHTML(container, markup); ReactDOMComponentTree.precacheNode(instance, container.firstChild); } if ("development" !== 'production') { var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild); if (hostNode._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation(hostNode._debugID, 'mount', markup.toString()); } } } }; module.exports = ReactMount; },{"10":10,"135":135,"140":140,"142":142,"144":144,"155":155,"162":162,"171":171,"27":27,"37":37,"42":42,"43":43,"46":46,"61":61,"67":67,"72":72,"73":73,"75":75,"8":8,"88":88,"95":95,"96":96}],77:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactComponentEnvironment = _dereq_(34); var ReactInstanceMap = _dereq_(72); var ReactInstrumentation = _dereq_(73); var ReactMultiChildUpdateTypes = _dereq_(78); var ReactCurrentOwner = _dereq_(37); var ReactReconciler = _dereq_(88); var ReactChildReconciler = _dereq_(28); var emptyFunction = _dereq_(154); var flattenChildren = _dereq_(124); var invariant = _dereq_(162); /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.INSERT_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.MOVE_EXISTING, content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getHostNode(child), toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for removing an element at an index. * * @param {number} fromIndex Index of the element to remove. * @private */ function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.REMOVE_NODE, content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.SET_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.TEXT_CONTENT, content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue); } var setChildrenForInstrumentation = emptyFunction; if ("development" !== 'production') { var getDebugID = function (inst) { if (!inst._debugID) { // Check for ART-like instances. TODO: This is silly/gross. var internal; if (internal = ReactInstanceMap.get(inst)) { inst = internal; } } return inst._debugID; }; setChildrenForInstrumentation = function (children) { var debugID = getDebugID(this); // TODO: React Native empty components are also multichild. // This means they still get into this method but don't have _debugID. if (debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function (key) { return children[key]._debugID; }) : []); } }; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if ("development" !== 'production') { var selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context, selfDebugID); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) { var nextChildren; var selfDebugID = 0; if ("development" !== 'production') { selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); } finally { ReactCurrentOwner.current = null; } ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; } } nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; var selfDebugID = 0; if ("development" !== 'production') { selfDebugID = getDebugID(this); } var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID); child._mountIndex = index++; mountImages.push(mountImage); } } if ("development" !== 'production') { setChildrenForInstrumentation.call(this, children); } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { !false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } // Set new text content. var updates = [makeTextContent(nextContent)]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { !false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var removedNodes = {}; var mountImages = []; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context); if (!nextChildren && !prevChildren) { return; } var updates = null; var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var nextIndex = 0; var lastIndex = 0; // `nextMountIndex` will increment for each newly mounted child. var nextMountIndex = 0; var lastPlacedNode = null; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); // The `removedNodes` loop below will actually remove the child. } // The child must be instantiated before it's mounted. updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context)); nextMountIndex++; } nextIndex++; lastPlacedNode = ReactReconciler.getHostNode(nextChild); } // Remove children that are no longer present. for (name in removedNodes) { if (removedNodes.hasOwnProperty(name)) { updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])); } } if (updates) { processQueue(this, updates); } this._renderedChildren = nextChildren; if ("development" !== 'production') { setChildrenForInstrumentation.call(this, nextChildren); } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. It does not actually perform any * backend operations. * * @internal */ unmountChildren: function (safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { return makeMove(child, afterNode, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function (child, mountImage, afterNode, index, transaction, context) { child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; } } }; module.exports = ReactMultiChild; },{"124":124,"140":140,"154":154,"162":162,"28":28,"34":34,"37":37,"72":72,"73":73,"78":78,"88":88}],78:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ 'use strict'; var keyMirror = _dereq_(165); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, SET_MARKUP: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; },{"165":165}],79:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNodeTypes * */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactElement = _dereq_(61); var invariant = _dereq_(162); var ReactNodeTypes = { HOST: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (ReactElement.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.HOST; } } !false ? "development" !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0; } }; module.exports = ReactNodeTypes; },{"140":140,"162":162,"61":61}],80:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNoopUpdateQueue */ 'use strict'; var warning = _dereq_(171); function warnNoop(publicInstance, callerName) { if ("development" !== 'production') { var constructor = publicInstance.constructor; "development" !== 'production' ? warning(false, '%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.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnNoop(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; },{"171":171}],81:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ 'use strict'; var _prodInvariant = _dereq_(140); var invariant = _dereq_(162); /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function (object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('119') : void 0; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('120') : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; },{"140":140,"162":162}],82:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ 'use strict'; var ReactPropTypeLocationNames = {}; if ("development" !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; },{}],83:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ 'use strict'; var keyMirror = _dereq_(165); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"165":165}],84:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ 'use strict'; var ReactElement = _dereq_(61); var ReactPropTypeLocationNames = _dereq_(82); var ReactPropTypesSecret = _dereq_(85); var emptyFunction = _dereq_(154); var getIteratorFn = _dereq_(131); var warning = _dereq_(171); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if ("development" !== 'production') { var manualPropTypeCallCache = {}; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if ("development" !== 'production') { if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') { var cacheKey = componentName + ':' + propName; if (!manualPropTypeCallCache[cacheKey]) { "development" !== 'production' ? warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will not work in the next major version. You may be ' + 'seeing this warning due to a third-party PropTypes library. ' + 'See https://fb.me/react-warning-dont-call-proptypes for details.', propFullName, componentName) : void 0; manualPropTypeCallCache[cacheKey] = true; } } } if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new PropTypeError('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!ReactElement.isValidElement(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { "development" !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { "development" !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } module.exports = ReactPropTypes; },{"131":131,"154":154,"171":171,"61":61,"82":82,"85":85}],85:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypesSecret */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; },{}],86:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPureComponent */ 'use strict'; var _assign = _dereq_(172); var ReactComponent = _dereq_(32); var ReactNoopUpdateQueue = _dereq_(80); var emptyObject = _dereq_(155); /** * Base class helpers for the updating state of a component. */ function ReactPureComponent(props, context, updater) { // Duplicated from ReactComponent. this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. _assign(ReactPureComponent.prototype, ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; module.exports = ReactPureComponent; },{"155":155,"172":172,"32":32,"80":80}],87:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction */ 'use strict'; var _assign = _dereq_(172); var CallbackQueue = _dereq_(5); var PooledClass = _dereq_(25); var ReactBrowserEventEmitter = _dereq_(27); var ReactInputSelection = _dereq_(71); var ReactInstrumentation = _dereq_(73); var Transaction = _dereq_(114); var ReactUpdateQueue = _dereq_(95); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; if ("development" !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(useCreateElement) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactDOMTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return ReactUpdateQueue; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function () { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function (checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; _assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"114":114,"172":172,"25":25,"27":27,"5":5,"71":71,"73":73,"95":95}],88:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ 'use strict'; var ReactRef = _dereq_(89); var ReactInstrumentation = _dereq_(73); var warning = _dereq_(171); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing host component instance * @param {?object} info about the host container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID // 0 in production and for roots ) { if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID); } } var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID); } } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getHostNode: function (internalInstance) { return internalInstance.getHostNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance, safely) { if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID); } } }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement); } } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. "development" !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; module.exports = ReactReconciler; },{"171":171,"73":73,"89":89}],89:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRef */ 'use strict'; var ReactOwner = _dereq_(81); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; return ( // This has a few false positives w/r/t empty components. prevEmpty || nextEmpty || nextElement.ref !== prevElement.ref || // If owner changes but we have an unchanged function ref, don't update refs typeof nextElement.ref === 'string' && nextElement._owner !== prevElement._owner ); }; ReactRef.detachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; },{"81":81}],90:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * * @providesModule ReactServerBatchingStrategy */ 'use strict'; var ReactServerBatchingStrategy = { isBatchingUpdates: false, batchedUpdates: function (callback) { // Don't do anything here. During the server rendering we don't want to // schedule any updates. We will simply ignore them. } }; module.exports = ReactServerBatchingStrategy; },{}],91:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRendering */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactDOMContainerInfo = _dereq_(43); var ReactDefaultBatchingStrategy = _dereq_(59); var ReactElement = _dereq_(61); var ReactInstrumentation = _dereq_(73); var ReactMarkupChecksum = _dereq_(75); var ReactReconciler = _dereq_(88); var ReactServerBatchingStrategy = _dereq_(90); var ReactServerRenderingTransaction = _dereq_(92); var ReactUpdates = _dereq_(96); var emptyObject = _dereq_(155); var instantiateReactComponent = _dereq_(135); var invariant = _dereq_(162); var pendingTransactions = 0; /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToStringImpl(element, makeStaticMarkup) { var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup); pendingTransactions++; return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, true); var markup = ReactReconciler.mountComponent(componentInstance, transaction, null, ReactDOMContainerInfo(), emptyObject, 0 /* parentDebugID */ ); if ("development" !== 'production') { ReactInstrumentation.debugTool.onUnmountComponent(componentInstance._debugID); } if (!makeStaticMarkup) { markup = ReactMarkupChecksum.addChecksumToMarkup(markup); } return markup; }, null); } finally { pendingTransactions--; ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. if (!pendingTransactions) { ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } } /** * Render a ReactElement to its initial HTML. This should only be used on the * server. * See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring */ function renderToString(element) { !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : _prodInvariant('46') : void 0; return renderToStringImpl(element, false); } /** * Similar to renderToString, except this doesn't create extra DOM attributes * such as data-react-id that React uses internally. * See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostaticmarkup */ function renderToStaticMarkup(element) { !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : _prodInvariant('47') : void 0; return renderToStringImpl(element, true); } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; },{"135":135,"140":140,"155":155,"162":162,"43":43,"59":59,"61":61,"73":73,"75":75,"88":88,"90":90,"92":92,"96":96}],92:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * * @providesModule ReactServerRenderingTransaction */ 'use strict'; var _assign = _dereq_(172); var PooledClass = _dereq_(25); var Transaction = _dereq_(114); var ReactInstrumentation = _dereq_(73); var ReactServerUpdateQueue = _dereq_(93); /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = []; if ("development" !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } var noopCallbackQueue = { enqueue: function () {} }; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.useCreateElement = false; this.updateQueue = new ReactServerUpdateQueue(this); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return noopCallbackQueue; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return this.updateQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () {}, checkpoint: function () {}, rollback: function () {} }; _assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"114":114,"172":172,"25":25,"73":73,"93":93}],93:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerUpdateQueue * */ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ReactUpdateQueue = _dereq_(95); var Transaction = _dereq_(114); var warning = _dereq_(171); function warnNoop(publicInstance, callerName) { if ("development" !== 'production') { var constructor = publicInstance.constructor; "development" !== 'production' ? warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the update queue used for server rendering. * It delegates to ReactUpdateQueue while server rendering is in progress and * switches to ReactNoopUpdateQueue after the transaction has completed. * @class ReactServerUpdateQueue * @param {Transaction} transaction */ var ReactServerUpdateQueue = function () { /* :: transaction: Transaction; */ function ReactServerUpdateQueue(transaction) { _classCallCheck(this, ReactServerUpdateQueue); this.transaction = transaction; } /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ ReactServerUpdateQueue.prototype.isMounted = function isMounted(publicInstance) { return false; }; /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ ReactServerUpdateQueue.prototype.enqueueCallback = function enqueueCallback(publicInstance, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueCallback(publicInstance, callback, callerName); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueForceUpdate(publicInstance); } else { warnNoop(publicInstance, 'forceUpdate'); } }; /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} completeState Next state. * @internal */ ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState); } else { warnNoop(publicInstance, 'replaceState'); } }; /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} partialState Next partial state to be merged with state. * @internal */ ReactServerUpdateQueue.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueSetState(publicInstance, partialState); } else { warnNoop(publicInstance, 'setState'); } }; return ReactServerUpdateQueue; }(); module.exports = ReactServerUpdateQueue; },{"114":114,"171":171,"95":95}],94:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUMDEntry */ 'use strict'; var _assign = _dereq_(172); var ReactDOM = _dereq_(38); var ReactDOMServer = _dereq_(53); var React = _dereq_(26); // `version` will be added here by ReactIsomorphic. var ReactUMDEntry = _assign({ __SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOM, __SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOMServer }, React); module.exports = ReactUMDEntry; },{"172":172,"26":26,"38":38,"53":53}],95:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdateQueue */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactCurrentOwner = _dereq_(37); var ReactInstanceMap = _dereq_(72); var ReactInstrumentation = _dereq_(73); var ReactUpdates = _dereq_(96); var invariant = _dereq_(162); var warning = _dereq_(171); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function formatUnexpectedArgument(arg) { var type = typeof arg; if (type !== 'object') { return type; } var displayName = arg.constructor && arg.constructor.name || type; var keys = Object.keys(arg); if (keys.length > 0 && keys.length < 20) { return displayName + ' (keys: ' + keys.join(', ') + ')'; } return displayName; } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if ("development" !== 'production') { var ctor = publicInstance.constructor; // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. "development" !== 'production' ? warning(!callerName, '%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.', callerName, callerName, ctor && (ctor.displayName || ctor.name) || 'ReactClass') : void 0; } return null; } if ("development" !== 'production') { "development" !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if ("development" !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @param {string} callerName Name of the calling function in the public API. * @internal */ enqueueCallback: function (publicInstance, callback, callerName) { ReactUpdateQueue.validateCallback(callback, callerName); var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetState(); "development" !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0; } var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, enqueueElementInternal: function (internalInstance, nextElement, nextContext) { internalInstance._pendingElement = nextElement; // TODO: introduce _pendingContext instead of setting it directly. internalInstance._context = nextContext; enqueueUpdate(internalInstance); }, validateCallback: function (callback, callerName) { !(!callback || typeof callback === 'function') ? "development" !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : _prodInvariant('122', callerName, formatUnexpectedArgument(callback)) : void 0; } }; module.exports = ReactUpdateQueue; },{"140":140,"162":162,"171":171,"37":37,"72":72,"73":73,"96":96}],96:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var CallbackQueue = _dereq_(5); var PooledClass = _dereq_(25); var ReactFeatureFlags = _dereq_(67); var ReactReconciler = _dereq_(88); var Transaction = _dereq_(114); var invariant = _dereq_(162); var dirtyComponents = []; var updateBatchNumber = 0; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */true); } _assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? "development" !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.props === component._renderedComponent._currentElement) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber); if (markerName) { console.timeEnd(markerName); } if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? "development" !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; },{"114":114,"140":140,"162":162,"172":172,"25":25,"5":5,"67":67,"88":88}],97:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactVersion */ 'use strict'; module.exports = '15.3.1'; },{}],98:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ 'use strict'; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlns: 0, xmlnsXlink: 'xmlns:xlink', xmlLang: 'xml:lang', xmlSpace: 'xml:space', y: 0, y1: 0, y2: 0, yChannelSelector: 'yChannelSelector', z: 0, zoomAndPan: 'zoomAndPan' }; var SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function (key) { SVGDOMPropertyConfig.Properties[key] = 0; if (ATTRS[key]) { SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]; } }); module.exports = SVGDOMPropertyConfig; },{}],99:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(20); var ExecutionEnvironment = _dereq_(148); var ReactDOMComponentTree = _dereq_(42); var ReactInputSelection = _dereq_(71); var SyntheticEvent = _dereq_(105); var getActiveElement = _dereq_(157); var isTextInputElement = _dereq_(137); var keyOf = _dereq_(166); var shallowEqual = _dereq_(170); var topLevelTypes = EventConstants.topLevelTypes; var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({ onSelect: null }), captured: keyOf({ onSelectCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange] } }; var activeElement = null; var activeElementInst = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. See #3639. var hasListener = false; var ON_SELECT_KEY = keyOf({ onSelect: null }); /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement = targetNode; activeElementInst = targetInst; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementInst = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case topLevelTypes.topSelectionChange: if (skipSelectionChangeEvent) { break; } // falls through case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (inst, registrationName, listener) { if (registrationName === ON_SELECT_KEY) { hasListener = true; } } }; module.exports = SelectEventPlugin; },{"105":105,"137":137,"148":148,"157":157,"16":16,"166":166,"170":170,"20":20,"42":42,"71":71}],100:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ 'use strict'; var _prodInvariant = _dereq_(140); var EventConstants = _dereq_(16); var EventListener = _dereq_(147); var EventPropagators = _dereq_(20); var ReactDOMComponentTree = _dereq_(42); var SyntheticAnimationEvent = _dereq_(101); var SyntheticClipboardEvent = _dereq_(102); var SyntheticEvent = _dereq_(105); var SyntheticFocusEvent = _dereq_(106); var SyntheticKeyboardEvent = _dereq_(108); var SyntheticMouseEvent = _dereq_(109); var SyntheticDragEvent = _dereq_(104); var SyntheticTouchEvent = _dereq_(110); var SyntheticTransitionEvent = _dereq_(111); var SyntheticUIEvent = _dereq_(112); var SyntheticWheelEvent = _dereq_(113); var emptyFunction = _dereq_(154); var getEventCharCode = _dereq_(126); var invariant = _dereq_(162); var keyOf = _dereq_(166); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { abort: { phasedRegistrationNames: { bubbled: keyOf({ onAbort: true }), captured: keyOf({ onAbortCapture: true }) } }, animationEnd: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationEnd: true }), captured: keyOf({ onAnimationEndCapture: true }) } }, animationIteration: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationIteration: true }), captured: keyOf({ onAnimationIterationCapture: true }) } }, animationStart: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationStart: true }), captured: keyOf({ onAnimationStartCapture: true }) } }, blur: { phasedRegistrationNames: { bubbled: keyOf({ onBlur: true }), captured: keyOf({ onBlurCapture: true }) } }, canPlay: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlay: true }), captured: keyOf({ onCanPlayCapture: true }) } }, canPlayThrough: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlayThrough: true }), captured: keyOf({ onCanPlayThroughCapture: true }) } }, click: { phasedRegistrationNames: { bubbled: keyOf({ onClick: true }), captured: keyOf({ onClickCapture: true }) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({ onContextMenu: true }), captured: keyOf({ onContextMenuCapture: true }) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({ onCopy: true }), captured: keyOf({ onCopyCapture: true }) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({ onCut: true }), captured: keyOf({ onCutCapture: true }) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({ onDoubleClick: true }), captured: keyOf({ onDoubleClickCapture: true }) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({ onDrag: true }), captured: keyOf({ onDragCapture: true }) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnd: true }), captured: keyOf({ onDragEndCapture: true }) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnter: true }), captured: keyOf({ onDragEnterCapture: true }) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({ onDragExit: true }), captured: keyOf({ onDragExitCapture: true }) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({ onDragLeave: true }), captured: keyOf({ onDragLeaveCapture: true }) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({ onDragOver: true }), captured: keyOf({ onDragOverCapture: true }) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({ onDragStart: true }), captured: keyOf({ onDragStartCapture: true }) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({ onDrop: true }), captured: keyOf({ onDropCapture: true }) } }, durationChange: { phasedRegistrationNames: { bubbled: keyOf({ onDurationChange: true }), captured: keyOf({ onDurationChangeCapture: true }) } }, emptied: { phasedRegistrationNames: { bubbled: keyOf({ onEmptied: true }), captured: keyOf({ onEmptiedCapture: true }) } }, encrypted: { phasedRegistrationNames: { bubbled: keyOf({ onEncrypted: true }), captured: keyOf({ onEncryptedCapture: true }) } }, ended: { phasedRegistrationNames: { bubbled: keyOf({ onEnded: true }), captured: keyOf({ onEndedCapture: true }) } }, error: { phasedRegistrationNames: { bubbled: keyOf({ onError: true }), captured: keyOf({ onErrorCapture: true }) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({ onFocus: true }), captured: keyOf({ onFocusCapture: true }) } }, input: { phasedRegistrationNames: { bubbled: keyOf({ onInput: true }), captured: keyOf({ onInputCapture: true }) } }, invalid: { phasedRegistrationNames: { bubbled: keyOf({ onInvalid: true }), captured: keyOf({ onInvalidCapture: true }) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({ onKeyDown: true }), captured: keyOf({ onKeyDownCapture: true }) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({ onKeyPress: true }), captured: keyOf({ onKeyPressCapture: true }) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({ onKeyUp: true }), captured: keyOf({ onKeyUpCapture: true }) } }, load: { phasedRegistrationNames: { bubbled: keyOf({ onLoad: true }), captured: keyOf({ onLoadCapture: true }) } }, loadedData: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedData: true }), captured: keyOf({ onLoadedDataCapture: true }) } }, loadedMetadata: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedMetadata: true }), captured: keyOf({ onLoadedMetadataCapture: true }) } }, loadStart: { phasedRegistrationNames: { bubbled: keyOf({ onLoadStart: true }), captured: keyOf({ onLoadStartCapture: true }) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({ onMouseDown: true }), captured: keyOf({ onMouseDownCapture: true }) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({ onMouseMove: true }), captured: keyOf({ onMouseMoveCapture: true }) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOut: true }), captured: keyOf({ onMouseOutCapture: true }) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOver: true }), captured: keyOf({ onMouseOverCapture: true }) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({ onMouseUp: true }), captured: keyOf({ onMouseUpCapture: true }) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({ onPaste: true }), captured: keyOf({ onPasteCapture: true }) } }, pause: { phasedRegistrationNames: { bubbled: keyOf({ onPause: true }), captured: keyOf({ onPauseCapture: true }) } }, play: { phasedRegistrationNames: { bubbled: keyOf({ onPlay: true }), captured: keyOf({ onPlayCapture: true }) } }, playing: { phasedRegistrationNames: { bubbled: keyOf({ onPlaying: true }), captured: keyOf({ onPlayingCapture: true }) } }, progress: { phasedRegistrationNames: { bubbled: keyOf({ onProgress: true }), captured: keyOf({ onProgressCapture: true }) } }, rateChange: { phasedRegistrationNames: { bubbled: keyOf({ onRateChange: true }), captured: keyOf({ onRateChangeCapture: true }) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({ onReset: true }), captured: keyOf({ onResetCapture: true }) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({ onScroll: true }), captured: keyOf({ onScrollCapture: true }) } }, seeked: { phasedRegistrationNames: { bubbled: keyOf({ onSeeked: true }), captured: keyOf({ onSeekedCapture: true }) } }, seeking: { phasedRegistrationNames: { bubbled: keyOf({ onSeeking: true }), captured: keyOf({ onSeekingCapture: true }) } }, stalled: { phasedRegistrationNames: { bubbled: keyOf({ onStalled: true }), captured: keyOf({ onStalledCapture: true }) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({ onSubmit: true }), captured: keyOf({ onSubmitCapture: true }) } }, suspend: { phasedRegistrationNames: { bubbled: keyOf({ onSuspend: true }), captured: keyOf({ onSuspendCapture: true }) } }, timeUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onTimeUpdate: true }), captured: keyOf({ onTimeUpdateCapture: true }) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({ onTouchCancel: true }), captured: keyOf({ onTouchCancelCapture: true }) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTouchEnd: true }), captured: keyOf({ onTouchEndCapture: true }) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({ onTouchMove: true }), captured: keyOf({ onTouchMoveCapture: true }) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({ onTouchStart: true }), captured: keyOf({ onTouchStartCapture: true }) } }, transitionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTransitionEnd: true }), captured: keyOf({ onTransitionEndCapture: true }) } }, volumeChange: { phasedRegistrationNames: { bubbled: keyOf({ onVolumeChange: true }), captured: keyOf({ onVolumeChangeCapture: true }) } }, waiting: { phasedRegistrationNames: { bubbled: keyOf({ onWaiting: true }), captured: keyOf({ onWaitingCapture: true }) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({ onWheel: true }), captured: keyOf({ onWheelCapture: true }) } } }; var topLevelEventsToDispatchConfig = { topAbort: eventTypes.abort, topAnimationEnd: eventTypes.animationEnd, topAnimationIteration: eventTypes.animationIteration, topAnimationStart: eventTypes.animationStart, topBlur: eventTypes.blur, topCanPlay: eventTypes.canPlay, topCanPlayThrough: eventTypes.canPlayThrough, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topDurationChange: eventTypes.durationChange, topEmptied: eventTypes.emptied, topEncrypted: eventTypes.encrypted, topEnded: eventTypes.ended, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topInvalid: eventTypes.invalid, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topLoadedData: eventTypes.loadedData, topLoadedMetadata: eventTypes.loadedMetadata, topLoadStart: eventTypes.loadStart, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topPause: eventTypes.pause, topPlay: eventTypes.play, topPlaying: eventTypes.playing, topProgress: eventTypes.progress, topRateChange: eventTypes.rateChange, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSeeked: eventTypes.seeked, topSeeking: eventTypes.seeking, topStalled: eventTypes.stalled, topSubmit: eventTypes.submit, topSuspend: eventTypes.suspend, topTimeUpdate: eventTypes.timeUpdate, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topTransitionEnd: eventTypes.transitionEnd, topVolumeChange: eventTypes.volumeChange, topWaiting: eventTypes.waiting, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[type].dependencies = [type]; } var ON_CLICK_KEY = keyOf({ onClick: null }); var onClickListeners = {}; function getDictionaryKey(inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; } var SimpleEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topAbort: case topLevelTypes.topCanPlay: case topLevelTypes.topCanPlayThrough: case topLevelTypes.topDurationChange: case topLevelTypes.topEmptied: case topLevelTypes.topEncrypted: case topLevelTypes.topEnded: case topLevelTypes.topError: case topLevelTypes.topInput: case topLevelTypes.topInvalid: case topLevelTypes.topLoad: case topLevelTypes.topLoadedData: case topLevelTypes.topLoadedMetadata: case topLevelTypes.topLoadStart: case topLevelTypes.topPause: case topLevelTypes.topPlay: case topLevelTypes.topPlaying: case topLevelTypes.topProgress: case topLevelTypes.topRateChange: case topLevelTypes.topReset: case topLevelTypes.topSeeked: case topLevelTypes.topSeeking: case topLevelTypes.topStalled: case topLevelTypes.topSubmit: case topLevelTypes.topSuspend: case topLevelTypes.topTimeUpdate: case topLevelTypes.topVolumeChange: case topLevelTypes.topWaiting: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topAnimationEnd: case topLevelTypes.topAnimationIteration: case topLevelTypes.topAnimationStart: EventConstructor = SyntheticAnimationEvent; break; case topLevelTypes.topTransitionEnd: EventConstructor = SyntheticTransitionEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? "development" !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : _prodInvariant('86', topLevelType) : void 0; var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (inst, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. if (registrationName === ON_CLICK_KEY) { var key = getDictionaryKey(inst); var node = ReactDOMComponentTree.getNodeFromInstance(inst); if (!onClickListeners[key]) { onClickListeners[key] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (inst, registrationName) { if (registrationName === ON_CLICK_KEY) { var key = getDictionaryKey(inst); onClickListeners[key].remove(); delete onClickListeners[key]; } } }; module.exports = SimpleEventPlugin; },{"101":101,"102":102,"104":104,"105":105,"106":106,"108":108,"109":109,"110":110,"111":111,"112":112,"113":113,"126":126,"140":140,"147":147,"154":154,"16":16,"162":162,"166":166,"20":20,"42":42}],101:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticAnimationEvent */ 'use strict'; var SyntheticEvent = _dereq_(105); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface); module.exports = SyntheticAnimationEvent; },{"105":105}],102:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent */ 'use strict'; var SyntheticEvent = _dereq_(105); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"105":105}],103:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent */ 'use strict'; var SyntheticEvent = _dereq_(105); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; },{"105":105}],104:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent */ 'use strict'; var SyntheticMouseEvent = _dereq_(109); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"109":109}],105:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent */ 'use strict'; var _assign = _dereq_(172); var PooledClass = _dereq_(25); var emptyFunction = _dereq_(154); var warning = _dereq_(171); var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { if ("development" !== 'production') { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } if ("development" !== 'production') { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== 'unknown') { // eslint-disable-line valid-typeof // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { if ("development" !== 'production') { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } else { this[propName] = null; } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } if ("development" !== 'production') { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)); } } }); SyntheticEvent.Interface = EventInterface; if ("development" !== 'production') { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { "development" !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; "development" !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } },{"154":154,"171":171,"172":172,"25":25}],106:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(112); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"112":112}],107:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent */ 'use strict'; var SyntheticEvent = _dereq_(105); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; },{"105":105}],108:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(112); var getEventCharCode = _dereq_(126); var getEventKey = _dereq_(127); var getEventModifierState = _dereq_(128); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"112":112,"126":126,"127":127,"128":128}],109:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(112); var ViewportMetrics = _dereq_(115); var getEventModifierState = _dereq_(128); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"112":112,"115":115,"128":128}],110:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(112); var getEventModifierState = _dereq_(128); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"112":112,"128":128}],111:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTransitionEvent */ 'use strict'; var SyntheticEvent = _dereq_(105); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface); module.exports = SyntheticTransitionEvent; },{"105":105}],112:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent */ 'use strict'; var SyntheticEvent = _dereq_(105); var getEventTarget = _dereq_(129); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"105":105,"129":129}],113:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent */ 'use strict'; var SyntheticMouseEvent = _dereq_(109); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"109":109}],114:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ 'use strict'; var _prodInvariant = _dereq_(140); var invariant = _dereq_(162); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occurred. */ OBSERVED_ERROR: {} }; module.exports = Transaction; },{"140":140,"162":162}],115:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{}],116:[function(_dereq_,module,exports){ /** * Copyright 2014-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. * * @providesModule accumulateInto * */ 'use strict'; var _prodInvariant = _dereq_(140); var invariant = _dereq_(162); /** * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? "development" !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } current.push(next); return current; } if (Array.isArray(next)) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; },{"140":140,"162":162}],117:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 * */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { var n = Math.min(i + 4096, m); for (; i < n; i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; },{}],118:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule canDefineProperty */ 'use strict'; var canDefineProperty = false; if ("development" !== 'production') { try { Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; },{}],119:[function(_dereq_,module,exports){ (function (process){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule checkReactTypeSpec */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactPropTypeLocationNames = _dereq_(82); var ReactPropTypesSecret = _dereq_(85); var invariant = _dereq_(162); var warning = _dereq_(171); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && "development" === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = _dereq_(35); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } "development" !== 'production' ? warning(!error || error 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).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if ("development" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = _dereq_(35); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } "development" !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; }).call(this,undefined) },{"140":140,"162":162,"171":171,"35":35,"82":82,"85":85}],120:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createMicrosoftUnsafeLocalFunction */ /* globals MSApp */ 'use strict'; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; module.exports = createMicrosoftUnsafeLocalFunction; },{}],121:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue */ 'use strict'; var CSSProperty = _dereq_(3); var warning = _dereq_(171); var isUnitlessNumber = CSSProperty.isUnitlessNumber; var styleWarnings = {}; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { if ("development" !== 'production') { // Allow '0' to pass through without warning. 0 is already special and // doesn't require units, so we don't need to warn about it. if (component && value !== '0') { var owner = component._currentElement._owner; var ownerName = owner ? owner.getName() : null; if (ownerName && !styleWarnings[ownerName]) { styleWarnings[ownerName] = {}; } var warned = false; if (ownerName) { var warnings = styleWarnings[ownerName]; warned = warnings[name]; if (!warned) { warnings[name] = true; } } if (!warned) { "development" !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0; } } } value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; },{"171":171,"3":3}],122:[function(_dereq_,module,exports){ /** * Copyright 2016-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. * * Based on the escape-html library, which is used under the MIT License below: * * Copyright (c) 2012-2013 TJ Holowaychuk * Copyright (c) 2015 Andreas Lubbe * Copyright (c) 2015 Tiancheng "Timothy" Gu * * 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. * * @providesModule escapeTextContentForBrowser */ 'use strict'; // code copied and modified from escape-html /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Escape special characters in the given string of html. * * @param {string} string The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '&quot;'; break; case 38: // & escape = '&amp;'; break; case 39: // ' escape = '&#x27;'; // modified from escape-html; used to be '&#39' break; case 60: // < escape = '&lt;'; break; case 62: // > escape = '&gt;'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } // end code copied and modified from escape-html /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { if (typeof text === 'boolean' || typeof text === 'number') { // this shortcircuit helps perf for types that we know will never have // special characters, especially given that this function is used often // for numeric dom ids. return '' + text; } return escapeHtml(text); } module.exports = escapeTextContentForBrowser; },{}],123:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule findDOMNode */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactCurrentOwner = _dereq_(37); var ReactDOMComponentTree = _dereq_(42); var ReactInstanceMap = _dereq_(72); var getHostComponentFromComposite = _dereq_(130); var invariant = _dereq_(162); var warning = _dereq_(171); /** * Returns the DOM node rendered by this element. * * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode * * @param {ReactComponent|DOMElement} componentOrElement * @return {?DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if ("development" !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getHostComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { !false ? "development" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44') : void 0; } else { !false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0; } } module.exports = findDOMNode; },{"130":130,"140":140,"162":162,"171":171,"37":37,"42":42,"72":72}],124:[function(_dereq_,module,exports){ (function (process){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren * */ 'use strict'; var KeyEscapeUtils = _dereq_(23); var traverseAllChildren = _dereq_(145); var warning = _dereq_(171); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && "development" === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = _dereq_(35); } /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. * @param {number=} selfDebugID Optional debugID of the current internal instance. */ function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) { // We found a component instance. if (traverseContext && typeof traverseContext === 'object') { var result = traverseContext; var keyUnique = result[name] === undefined; if ("development" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = _dereq_(35); } if (!keyUnique) { "development" !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (keyUnique && child != null) { result[name] = child; } } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children, selfDebugID) { if (children == null) { return children; } var result = {}; if ("development" !== 'production') { traverseAllChildren(children, function (traverseContext, child, name) { return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID); }, result); } else { traverseAllChildren(children, flattenSingleChildIntoContext, result); } return result; } module.exports = flattenChildren; }).call(this,undefined) },{"145":145,"171":171,"23":23,"35":35}],125:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated * */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } module.exports = forEachAccumulated; },{}],126:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; },{}],127:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey */ 'use strict'; var getEventCharCode = _dereq_(126); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 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: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; },{"126":126}],128:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; },{}],129:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventTarget */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; },{}],130:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getHostComponentFromComposite */ 'use strict'; var ReactNodeTypes = _dereq_(79); function getHostComponentFromComposite(inst) { var type; while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) { inst = inst._renderedComponent; } if (type === ReactNodeTypes.HOST) { return inst._renderedComponent; } else if (type === ReactNodeTypes.EMPTY) { return null; } } module.exports = getHostComponentFromComposite; },{"79":79}],131:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getIteratorFn * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; },{}],132:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNodeForCharacterOffset */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; },{}],133:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ 'use strict'; var ExecutionEnvironment = _dereq_(148); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; },{"148":148}],134:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getVendorPrefixedEventName */ 'use strict'; var ExecutionEnvironment = _dereq_(148); /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment.canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; } module.exports = getVendorPrefixedEventName; },{"148":148}],135:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent */ 'use strict'; var _prodInvariant = _dereq_(140), _assign = _dereq_(172); var ReactCompositeComponent = _dereq_(36); var ReactEmptyComponent = _dereq_(63); var ReactHostComponent = _dereq_(68); var invariant = _dereq_(162); var warning = _dereq_(171); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; _assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } var nextDebugID = 1; /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @param {boolean} shouldHaveDebugID * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node, shouldHaveDebugID) { var instance; if (node === null || node === false) { instance = ReactEmptyComponent.create(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : _prodInvariant('130', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : void 0; // Special case string values if (typeof element.type === 'string') { instance = ReactHostComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); // We renamed this. Allow the old name for compat. :( if (!instance.getHostNode) { instance.getHostNode = instance.getNativeNode; } } else { instance = new ReactCompositeComponentWrapper(element); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactHostComponent.createInstanceForText(node); } else { !false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0; } if ("development" !== 'production') { "development" !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0; } // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if ("development" !== 'production') { instance._debugID = shouldHaveDebugID ? nextDebugID++ : 0; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if ("development" !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; },{"140":140,"162":162,"171":171,"172":172,"36":36,"63":63,"68":68}],136:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ 'use strict'; var ExecutionEnvironment = _dereq_(148); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; },{"148":148}],137:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement * */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); if (nodeName === 'input') { return !!supportedInputTypes[elem.type]; } if (nodeName === 'textarea') { return true; } return false; } module.exports = isTextInputElement; },{}],138:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule onlyChild */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactElement = _dereq_(61); var invariant = _dereq_(162); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? "development" !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0; return children; } module.exports = onlyChild; },{"140":140,"162":162,"61":61}],139:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule quoteAttributeValueForBrowser */ 'use strict'; var escapeTextContentForBrowser = _dereq_(122); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; },{"122":122}],140:[function(_dereq_,module,exports){ /** * 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. * * @providesModule reactProdInvariant * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; },{}],141:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule renderSubtreeIntoContainer */ 'use strict'; var ReactMount = _dereq_(76); module.exports = ReactMount.renderSubtreeIntoContainer; },{"76":76}],142:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ 'use strict'; var ExecutionEnvironment = _dereq_(148); var DOMNamespaces = _dereq_(9); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; var createMicrosoftUnsafeLocalFunction = _dereq_(120); // SVG temp container for IE lacking innerHTML var reusableSVGContainer; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { // IE does not have innerHTML for SVG nodes, so instead we inject the // new markup in a temp node and then move the child nodes across into // the target node if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) { reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>'; var newNodes = reusableSVGContainer.firstChild.childNodes; for (var i = 0; i < newNodes.length; i++) { node.appendChild(newNodes[i]); } } else { node.innerHTML = html; } }); if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } testElement = null; } module.exports = setInnerHTML; },{"120":120,"148":148,"9":9}],143:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setTextContent */ 'use strict'; var ExecutionEnvironment = _dereq_(148); var escapeTextContentForBrowser = _dereq_(122); var setInnerHTML = _dereq_(142); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) { firstChild.nodeValue = text; return; } } node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; },{"122":122,"142":142,"148":148}],144:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } } module.exports = shouldUpdateReactComponent; },{}],145:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ 'use strict'; var _prodInvariant = _dereq_(140); var ReactCurrentOwner = _dereq_(37); var ReactElement = _dereq_(61); var getIteratorFn = _dereq_(131); var invariant = _dereq_(162); var KeyEscapeUtils = _dereq_(23); var warning = _dereq_(171); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if ("development" !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } "development" !== 'production' ? warning(didWarnAboutMaps, '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.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if ("development" !== 'production') { addendum = ' 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.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); !false ? "development" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; },{"131":131,"140":140,"162":162,"171":171,"23":23,"37":37,"61":61}],146:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule validateDOMNesting */ 'use strict'; var _assign = _dereq_(172); var emptyFunction = _dereq_(154); var warning = _dereq_(171); var validateDOMNesting = emptyFunction; if ("development" !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; var tagDisplayName = childTag; if (childTag !== '#text') { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } "development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>. ' + 'See %s.%s', tagDisplayName, ancestorTag, ownerInfo, info) : void 0; } else { "development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0; } } }; validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; },{"154":154,"171":171,"172":172}],147:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, 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. * * @typechecks */ var emptyFunction = _dereq_(154); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function listen(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function capture(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function remove() { target.removeEventListener(eventType, callback, true); } }; } else { if ("development" !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function registerDefault() {} }; module.exports = EventListener; },{"154":154}],148:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],149:[function(_dereq_,module,exports){ "use strict"; /** * 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. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; },{}],150:[function(_dereq_,module,exports){ /** * 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. * * @typechecks */ 'use strict'; var camelize = _dereq_(149); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; },{"149":149}],151:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * * */ var isTextNode = _dereq_(164); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if ('contains' in outerNode) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; },{"164":164}],152:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * * @typechecks */ var invariant = _dereq_(162); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browsers builtin objects can report typeof 'function' (e.g. NodeList // in old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? "development" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; !(typeof length === 'number') ? "development" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; !(length === 0 || length - 1 in obj) ? "development" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; !(typeof obj.callee !== 'function') ? "development" !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; },{"162":162}],153:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = _dereq_(148); var createArrayFromMixed = _dereq_(152); var getMarkupWrap = _dereq_(158); var invariant = _dereq_(162); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = Array.from(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; },{"148":148,"152":152,"158":158,"162":162}],154:[function(_dereq_,module,exports){ "use strict"; /** * 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. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; },{}],155:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; var emptyObject = {}; if ("development" !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; },{}],156:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; },{}],157:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],158:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * */ /*eslint-disable fb-www/unsafe-html */ var ExecutionEnvironment = _dereq_(148); var invariant = _dereq_(162); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? "development" !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; },{"148":148,"162":162}],159:[function(_dereq_,module,exports){ /** * 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. * * @typechecks */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; },{}],160:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],161:[function(_dereq_,module,exports){ /** * 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. * * @typechecks */ 'use strict'; var hyphenate = _dereq_(160); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; },{"160":160}],162:[function(_dereq_,module,exports){ /** * 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. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if ("development" !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { 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]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; },{}],163:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; },{}],164:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * * @typechecks */ var isNode = _dereq_(163); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; },{"163":163}],165:[function(_dereq_,module,exports){ /** * 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. * * @typechecks static-only */ 'use strict'; var invariant = _dereq_(162); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function keyMirror(obj) { var ret = {}; var key; !(obj instanceof Object && !Array.isArray(obj)) ? "development" !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : void 0; for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; },{"162":162}],166:[function(_dereq_,module,exports){ "use strict"; /** * 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. * */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function keyOf(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; },{}],167:[function(_dereq_,module,exports){ /** * 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. * * * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; },{}],168:[function(_dereq_,module,exports){ /** * 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. * * @typechecks */ 'use strict'; var ExecutionEnvironment = _dereq_(148); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; },{"148":148}],169:[function(_dereq_,module,exports){ 'use strict'; /** * 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. * * @typechecks */ var performance = _dereq_(168); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function performanceNow() { return performance.now(); }; } else { performanceNow = function performanceNow() { return Date.now(); }; } module.exports = performanceNow; },{"168":168}],170:[function(_dereq_,module,exports){ /** * 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. * * @typechecks * */ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqual; },{}],171:[function(_dereq_,module,exports){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyFunction = _dereq_(154); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("development" !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; },{"154":154}],172:[function(_dereq_,module,exports){ 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}]},{},[94])(94) });
app/Resources/js/startup/home.js
ryota-murakami/tweet-pick
import React from 'react' import { Provider } from 'react-redux' import App from '../containers/home' import ReactOnRails from 'react-on-rails' const mainNode = () => { const store = ReactOnRails.getStore('homeStore') const reactComponent = ( <Provider store={store}> <App/> </Provider> ) return reactComponent } export default mainNode
test/components/Counter.spec.js
ACalix/sprinthub
import { spy } from 'sinon'; import React from 'react'; import { shallow } from 'enzyme'; import { BrowserRouter as Router } from 'react-router-dom'; import renderer from 'react-test-renderer'; import Counter from '../../app/components/Counter'; function setup() { const actions = { increment: spy(), incrementIfOdd: spy(), incrementAsync: spy(), decrement: spy() }; const component = shallow(<Counter counter={1} {...actions} />); return { component, actions, buttons: component.find('button'), p: component.find('.counter') }; } describe('Counter component', () => { it('should should display count', () => { const { p } = setup(); expect(p.text()).toMatch(/^1$/); }); it('should first button should call increment', () => { const { buttons, actions } = setup(); buttons.at(0).simulate('click'); expect(actions.increment.called).toBe(true); }); it('should match exact snapshot', () => { const { actions } = setup(); const tree = renderer .create( <div> <Router> <Counter counter={1} {...actions} /> </Router> </div> ) .toJSON(); expect(tree).toMatchSnapshot(); }); it('should second button should call decrement', () => { const { buttons, actions } = setup(); buttons.at(1).simulate('click'); expect(actions.decrement.called).toBe(true); }); it('should third button should call incrementIfOdd', () => { const { buttons, actions } = setup(); buttons.at(2).simulate('click'); expect(actions.incrementIfOdd.called).toBe(true); }); it('should fourth button should call incrementAsync', () => { const { buttons, actions } = setup(); buttons.at(3).simulate('click'); expect(actions.incrementAsync.called).toBe(true); }); });
app/src/containers/recommended-diet/index.js
supernova-at/media-bias
/* * Imports. */ // NPM. import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; // Local. import './recommended-diet.css'; import Outlet from '../../components/outlet'; import Recommender from './recommender'; import { Zones } from '../../zones'; // Members. const heading = `Balancing your diet`; const subheading = `Here's our recommendation for you`; /* * RecommendedDiet class. */ class RecommendedDiet extends Component { render () { const recommendations = this._recommendation.map(outlet => { return <Outlet key={outlet.name} name={outlet.name} />; }); let currentDiet = this.context.diet.map(outletName => ( <Outlet key={outletName} name={outletName} /> )); const leanClass = classnames('the-lean show1', { 'lean-left': this._lean === Zones.Left, 'lean-lean-left': this._lean === Zones.LeanLeft, 'lean-center': this._lean === Zones.Center, 'lean-lean-right': this._lean === Zones.LeanRight, 'lean-right': this._lean === Zones.Right, }); const showReccos = recommendations.length > 0; return ( <div className="newspaper-copy"> <h1 className="newspaper-heading">{heading}</h1> <h3 className="newspaper-subheading">{subheading}</h3> <div> <div className="recco-pair"> <h2> <span>Your current diet is&nbsp;</span> <span className={leanClass}> {this._lean} </span> <span className="show1">&nbsp; (with {this._deviation} deviation).</span> </h2> <div className="recco-outlets-list show0">{currentDiet}</div> </div> <div className="recco-pair show2"> <h2>You should consider reading:</h2> <div className="recco-outlets-list"> {showReccos && recommendations} {!showReccos && ( <span className="recco-na">N/A</span> )} </div> </div> </div> </div> ); } constructor (...args) { super(...args); const { lean, deviation, recommendation } = Recommender(this.context.diet); this._lean = lean; this._deviation = deviation; this._recommendation = recommendation; // Record the lean. window.ga('send', 'event', { eventCategory: 'Recommendation Page', eventAction: 'User Lean', eventLabel: this._lean, nonInteraction: true, }); // Record the deviation. window.ga('send', 'event', { eventCategory: 'Recommendation Page', eventAction: 'Lean Deviation', eventLabel: this._deviation, nonInteraction: true, }); // Record our recommendation. window.ga('send', 'event', { eventCategory: 'Recommendation Page', eventAction: 'Outlets Reccomended', eventLabel: this._recommendation.map(outlet => outlet.name).join(','), nonInteraction: true, }); } }; RecommendedDiet.displayName = 'RecommendedDiet'; RecommendedDiet.contextTypes = { diet: PropTypes.array, }; export default RecommendedDiet;
public/js/components/profile/visitor/activityfeed/Comment.react.js
TRomesh/Coupley
import React from 'react'; import Card from 'material-ui/lib/card/card'; import ListItem from 'material-ui/lib/lists/list-item'; import List from 'material-ui/lib/lists/list'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; var Comment = React.createClass({ render: function () { return ( <div> <Card> <ListItem leftAvatar={<Avatar src="https://s-media-cache-ak0.pinimg.com/236x/dc/15/f2/dc15f28faef36bc55e64560d000e871c.jpg" />} primaryText={this.props.cfirstName} secondaryText={<p>{this.props.comment_txt}</p>} secondaryTextLines={1} /> <Divider inset={true} /> </Card> </div> ); } }); export default Comment;
ajax/libs/forerunnerdb/1.3.302/fdb-legacy.js
pvnr0082t/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/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'), OldView = _dereq_('../lib/OldView'), OldViewBind = _dereq_('../lib/OldView.Bind'), Grid = _dereq_('../lib/Grid'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":10,"../lib/Highchart":11,"../lib/OldView":26,"../lib/OldView.Bind":25,"../lib/Overview":29,"../lib/Persist":31,"../lib/View":36}],2:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * 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) { var sortKey; this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; for (sortKey in orderBy) { if (orderBy.hasOwnProperty(sortKey)) { this._keyArr.push({ key: sortKey, dir: orderBy[sortKey] }); } } }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); /** * 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 obj[sortType.key]; 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.dir === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.dir === -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 += obj[sortType.key]; } // 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; },{"./Shared":35}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) { this._store = []; 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, 'index', function (index) { if (index !== undefined) { if (!(index instanceof Array)) { // Convert the index object to an array of key val objects index = this.keys(index); } } return this.$super.call(this, index); }); BinaryTree.prototype.keys = function (obj) { var i, keys = []; for (i in obj) { if (obj.hasOwnProperty(i)) { keys.push({ key: i, val: obj[i] }); } } return keys; }; BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return true; } } 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._index.length; i++) { indexData = this._index[i]; if (indexData.val === 1) { result = this.sortAsc(a[indexData.key], b[indexData.key]); } else if (indexData.val === -1) { result = this.sortDesc(a[indexData.key], b[indexData.key]); } if (result !== 0) { return 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._index.length; i++) { indexData = this._index[i]; if (hash) { hash += '_'; } hash += obj[indexData.key]; } return hash;*/ return obj[this._index[0].key]; }; 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._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) { 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._compareFunc, this._hashFunc); } return true; } if (result === -1) { // 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._compareFunc, this._hashFunc); } return true; } if (result === 1) { // 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._compareFunc, this._hashFunc); } return true; } return false; }; BinaryTree.prototype.lookup = function (data, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, resultArr); } } return resultArr; }; 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 'key': resultArr.push(this._data); break; default: resultArr.push({ key: this._key, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Shared":35}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // 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'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the 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'); /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = JSON.stringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * 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, 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': // 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; 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': 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 = JSON.stringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (JSON.stringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { 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); }; // 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); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this._onChange(); this.deferEmit('change', {type: 'remove', data: dataSet}); } if (callback) { callback(false, dataSet); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * 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. * @private */ Collection.prototype.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); } }; /** * 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) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } } // Check if all queues are complete if (!this.isProcessingQueue()) { this.emit('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 (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // 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 }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc; 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); }; 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 false; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = JSON.stringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = JSON.stringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = JSON.stringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.apply(this, arguments); }; 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 || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // 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'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value return new Path(query.substr(3, query.length - 3)).value(item)[0]; } return new Path(query).value(item)[0]; } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // 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); } }; /** * 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); }; /** * 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 }; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== 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[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // 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[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection 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 name = options.name; if (name) { if (!this._collection[name]) { 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!'); } } 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); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":7,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":28,"./Path":30,"./ReactorIO":34,"./Shared":35}],5:[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'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function () { 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); } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":4,"./Shared":35}],6:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } 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; } } } } 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; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = 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 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":8,"./Metrics.js":15,"./Overload":28,"./Shared":35}],7:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],8:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } 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'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; /** * 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._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._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._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._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":15,"./Overload":28,"./Shared":35}],9:[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'); 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; } } 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) { this.updateObject(this._data, update, query, options); }; /** * 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 + '"'); } } }; /** * 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 () { 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); return true; } } } else { return true; } return false; }; /** * Creates a new document instance. * @func document * @memberof Db * @param {String} documentName The name of the document to create. * @returns {*} */ Db.prototype.document = function (documentName) { if (documentName) { // Handle being passed an instance if (documentName instanceof FdbDocument) { if (documentName.state() !== 'droppped') { return documentName; } else { documentName = documentName.name(); } } this._document = this._document || {}; this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this); return this._document[documentName]; } 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":4,"./Shared":35}],10:[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'); 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 () { 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); delete this._selector; delete this._template; delete this._from; delete this._db; 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>&nbsp;All', '</a>', '</li>', '<li role="presentation" class="divider"></li>', '{^{for options}}', '<li role="presentation" data-link="data-val{:' + filterField + '}">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox">&nbsp;{^{:' + filterField + '}}', '</a>', '</li>', '{{/for}}' ].join('') }, { $wrap: 'options' }); elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) { var elem = window.jQuery(this), query = filterView.query(), search = elem.val(); if (search) { query[filterField] = new RegExp(search, 'gi'); } else { delete query[filterField]; } filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) { // Clear search text box window.jQuery(this).parents('li').find('.gridFilterSearch').val(''); // Clear view query var query = filterView.query(); delete query[filterField]; filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) { e.stopPropagation(); var fieldValue, elem = $(this), checkbox = elem.find('input[type="checkbox"]'), checked, addMode = true, fieldInArr, liElem, i; // If the checkbox is not the one clicked on if (!window.jQuery(e.target).is('input')) { // Set checkbox to opposite of current value checkbox.prop('checked', !checkbox.prop('checked')); checked = checkbox.is(':checked'); } else { checkbox.prop('checked', checkbox.prop('checked')); checked = checkbox.is(':checked'); } liElem = window.jQuery(this); fieldValue = liElem.attr('data-val'); // Check if the selection is the "all" option if (fieldValue === '$all') { // Remove the field from the query delete queryObj[filterField]; // Clear all other checkboxes liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false); } else { // Clear the "all" checkbox liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false); // Check if the type needs casting switch (filterVarType) { case 'integer': fieldValue = parseInt(fieldValue, 10); break; case 'float': fieldValue = parseFloat(fieldValue); break; default: } // Check if the item exists already queryObj[filterField] = queryObj[filterField] || { $in: [] }; fieldInArr = queryObj[filterField].$in; for (i = 0; i < fieldInArr.length; i++) { if (fieldInArr[i] === fieldValue) { // Item already exists if (checked === false) { // Remove the item fieldInArr.splice(i, 1); } addMode = false; break; } } if (addMode && checked) { fieldInArr.push(fieldValue); } if (!fieldInArr.length) { // Remove the field from the query delete queryObj[filterField]; } } // Set the view query self._from.queryData(queryObj); if (self._from.pageFirst) { self._from.pageFirst(); } }); }); } self.emit('refresh'); } else { throw('Grid requires the AutoBind module in order to operate!'); } } return this; }; /** * Returns the number of documents currently in the grid. * @func count * @memberof Grid * @returns {Number} */ Grid.prototype.count = function () { return this._from.count(); }; /** * Creates a grid and assigns the collection as its data source. * @func grid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.grid = View.prototype.grid = function (selector, template, options) { if (this._db && this._db._grid ) { if (selector !== undefined) { if (template !== undefined) { if (!this._db._grid[selector]) { var grid = new Grid(selector, template, options) .db(this._db) .from(this); this._grid = this._grid || []; this._grid.push(grid); this._db._grid[selector] = grid; return grid; } else { throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector); } } return this._db._grid[selector]; } return this._db._grid; } }; /** * Removes a grid safely from the DOM. Must be called when grid is * no longer required / is being removed from DOM otherwise references * will stick around and cause memory leaks. * @func unGrid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) { var i, grid; if (this._db && this._db._grid ) { if (selector && template) { if (this._db._grid[selector]) { grid = this._db._grid[selector]; delete this._db._grid[selector]; return grid.drop(); } else { throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name); } } else { // No parameters passed, remove all grids from this module for (i in this._db._grid) { if (this._db._grid.hasOwnProperty(i)) { grid = this._db._grid[i]; delete this._db._grid[i]; grid.drop(); if (this.debug()) { console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"'); } } } this._db._grid = {}; } } }; /** * Adds a grid to the internal grid lookup. * @func _addGrid * @memberof Collection * @param {Grid} grid The grid to add. * @returns {Collection} * @private */ Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) { if (grid !== undefined) { this._grid = this._grid || []; this._grid.push(grid); } return this; }; /** * Removes a grid from the internal grid lookup. * @func _removeGrid * @memberof Collection * @param {Grid} grid The grid to remove. * @returns {Collection} * @private */ Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) { if (grid !== undefined && this._grid) { var index = this._grid.indexOf(grid); if (index > -1) { this._grid.splice(index, 1); } } return this; }; // Extend DB with grids init Db.prototype.init = function () { this._grid = {}; DbInit.apply(this, arguments); }; /** * Determine if a grid with the passed name already exists. * @func gridExists * @memberof Db * @param {String} selector The jQuery selector to bind the grid to. * @returns {boolean} */ Db.prototype.gridExists = function (selector) { return Boolean(this._grid[selector]); }; /** * Creates a grid based on the passed arguments. * @func grid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.grid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Removes a grid based on the passed arguments. * @func unGrid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.unGrid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Returns an array of grids the DB currently has. * @func grids * @memberof Db * @returns {Array} An array of objects containing details of each grid * the database is currently managing. */ Db.prototype.grids = function () { var arr = [], item, i; for (i in this._grid) { if (this._grid.hasOwnProperty(i)) { item = this._grid[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Grid'); module.exports = Grid; },{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":34,"./Shared":35,"./View":36}],11:[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.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) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = { categories: [] }, seriesName, query, dataSearch, seriesValues, 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++) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } seriesData.push({ name: seriesName, data: seriesValues }); } 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, arguments); }); }; /** * 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._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 () { 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); 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 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":28,"./Shared":35}],12:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), treeInstance = new BinaryTree(), btree = function () {}; treeInstance.inOrder('hash'); /** * The index class used to instantiate hash map 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 (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); 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('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 = new (btree.create(2, this.sortAsc))(); 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, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; 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) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.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); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":3,"./Path":30,"./Shared":35}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":30,"./Shared":35}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * 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":35}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":27,"./Shared":35}],16:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],17:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } arrItem.chainReceive(this, type, data, options); } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],18:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Common; Common = { /** * 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) { if (!copies) { return JSON.parse(JSON.stringify(data)); } else { var i, json = JSON.stringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(JSON.parse(json)); } return copyArr; } } return undefined; }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":28}],19:[function(_dereq_,module,exports){ "use strict"; var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); 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; } }; module.exports = Events; },{"./Overload":28}],21:[function(_dereq_,module,exports){ "use strict"; 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, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; 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=} 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 '$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 (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) { return true; } else if (inArr[inArrIndex] === source) { return true; } } return false; } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; } return -1; } }; module.exports = Matching; },{}],22:[function(_dereq_,module,exports){ "use strict"; var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":28}],24:[function(_dereq_,module,exports){ "use strict"; var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @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; },{}],25:[function(_dereq_,module,exports){ "use strict"; // Grab the view class var Shared, Core, OldView, OldViewInit; Shared = _dereq_('./Shared'); Core = Shared.modules.Core; OldView = Shared.modules.OldView; OldViewInit = OldView.prototype.init; OldView.prototype.init = function () { var self = this; this._binds = []; this._renderStart = 0; this._renderEnd = 0; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], _bindInsert: [], _bindUpdate: [], _bindRemove: [], _bindUpsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100, _bindInsert: 100, _bindUpdate: 100, _bindRemove: 100, _bindUpsert: 100 }; this._deferTime = { insert: 100, update: 1, remove: 1, upsert: 1, _bindInsert: 100, _bindUpdate: 1, _bindRemove: 1, _bindUpsert: 1 }; OldViewInit.apply(this, arguments); // Hook view events to update binds this.on('insert', function (successArr, failArr) { self._bindEvent('insert', successArr, failArr); }); this.on('update', function (successArr, failArr) { self._bindEvent('update', successArr, failArr); }); this.on('remove', function (successArr, failArr) { self._bindEvent('remove', successArr, failArr); }); this.on('change', self._bindChange); }; /** * Binds a selector to the insert, update and delete events of a particular * view and keeps the selector in sync so that updates are reflected on the * web page in real-time. * * @param {String} selector The jQuery selector string to get target elements. * @param {Object} options The options object. */ OldView.prototype.bind = function (selector, options) { if (options && options.template) { this._binds[selector] = options; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!'); } return this; }; /** * Un-binds a selector from the view changes. * @param {String} selector The jQuery selector string to identify the bind to remove. * @returns {Collection} */ OldView.prototype.unBind = function (selector) { delete this._binds[selector]; return this; }; /** * Returns true if the selector is bound to the view. * @param {String} selector The jQuery selector string to identify the bind to check for. * @returns {boolean} */ OldView.prototype.isBound = function (selector) { return Boolean(this._binds[selector]); }; /** * Sorts items in the DOM based on the bind settings and the passed item array. * @param {String} selector The jQuery selector of the bind container. * @param {Array} itemArr The array of items used to determine the order the DOM * elements should be in based on the order they are in, in the array. */ OldView.prototype.bindSortDom = function (selector, itemArr) { var container = window.jQuery(selector), arrIndex, arrItem, domItem; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr); } for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) { arrItem = itemArr[arrIndex]; // Now we've done our inserts into the DOM, let's ensure // they are still ordered correctly domItem = container.find('#' + arrItem[this._primaryKey]); if (domItem.length) { if (arrIndex === 0) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem); } container.prepend(domItem); } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem); } domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')')); } } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem); } } } }; OldView.prototype.bindRefresh = function (obj) { var binds = this._binds, bindKey, bind; if (!obj) { // Grab current data obj = { data: this.find() }; } for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { bind = binds[bindKey]; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); } this.bindSortDom(bindKey, obj.data); if (bind.afterOperation) { bind.afterOperation(); } if (bind.refresh) { bind.refresh(); } } } }; /** * Renders a bind view data to the DOM. * @param {String} bindSelector The jQuery selector string to use to identify * the bind target. Must match the selector used when defining the original bind. * @param {Function=} domHandler If specified, this handler method will be called * with the final HTML for the view instead of the DB handling the DOM insertion. */ OldView.prototype.bindRender = function (bindSelector, domHandler) { // Check the bind exists var bind = this._binds[bindSelector], domTarget = window.jQuery(bindSelector), allData, dataItem, itemHtml, finalHtml = window.jQuery('<ul></ul>'), bindCallback, i; if (bind) { allData = this._data.find(); bindCallback = function (itemHtml) { finalHtml.append(itemHtml); }; // Loop all items and add them to the screen for (i = 0; i < allData.length; i++) { dataItem = allData[i]; itemHtml = bind.template(dataItem, bindCallback); } if (!domHandler) { domTarget.append(finalHtml.html()); } else { domHandler(bindSelector, finalHtml.html()); } } }; OldView.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { 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); } this._bindEvent(type, dataArr, []); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { callback(); } this.emit('bindQueueComplete'); } }; OldView.prototype._bindEvent = function (type, successArr, failArr) { /*var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type];*/ var binds = this._binds, unfilteredDataSet = this.find({}), filteredDataSet, bindKey; // Check if the number of inserts is greater than the defer threshold /*if (successArr && successArr.length > deferThreshold) { // Break up upsert into blocks this._deferQueue[type] = queue.concat(successArr); // Fire off the insert queue handler this.processQueue(type); return; } else {*/ for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { if (binds[bindKey].reduce) { filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options); } else { filteredDataSet = unfilteredDataSet; } switch (type) { case 'insert': this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'update': this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'remove': this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; } } } //} }; OldView.prototype._bindChange = function (newDataArr) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr); } this.bindRefresh(newDataArr); }; OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, itemHtml, makeCallback, i; makeCallback = function (itemElem, insertedItem, failArr, all) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.insert) { options.insert(itemHtml, insertedItem, failArr, all); } else { // Handle the insert automatically // Add the item to the container if (options.prependInsert) { container.prepend(itemHtml); } else { container.append(itemHtml); } } if (options.afterInsert) { options.afterInsert(itemHtml, insertedItem, failArr, all); } }; }; // Loop the inserted items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (!itemElem.length) { itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all)); } } }; OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, itemData) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.update) { options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append'); } else { if (itemElem.length) { // An existing item is in the container, replace it with the // new rendered item from the updated data itemElem.replaceWith(itemHtml); } else { // The item element does not already exist, append it if (options.prependUpdate) { container.prepend(itemHtml); } else { container.append(itemHtml); } } } if (options.afterUpdate) { options.afterUpdate(itemHtml, itemData, all); } }; }; // Loop the updated items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); options.template(successArr[i], makeCallback(itemElem, successArr[i])); } }; OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, data, all) { return function () { if (options.remove) { options.remove(itemElem, data, all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, data, all); } } }; }; // Loop the removed items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (itemElem.length) { if (options.beforeRemove) { options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all)); } else { if (options.remove) { options.remove(itemElem, successArr[i], all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, successArr[i], all); } } } } } }; },{"./Shared":35}],26:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, CollectionGroup, Collection, CollectionInit, CollectionGroupInit, DbInit; Shared = _dereq_('./Shared'); /** * The view constructor. * @param viewName * @constructor */ var OldView = function (viewName) { this.init.apply(this, arguments); }; OldView.prototype.init = function (viewName) { var self = this; this._name = viewName; this._listeners = {}; this._query = { query: {}, options: {} }; // Register listeners for the CRUD events this._onFromSetData = function () { self._onSetData.apply(self, arguments); }; this._onFromInsert = function () { self._onInsert.apply(self, arguments); }; this._onFromUpdate = function () { self._onUpdate.apply(self, arguments); }; this._onFromRemove = function () { self._onRemove.apply(self, arguments); }; this._onFromChange = function () { if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); } self._onChange.apply(self, arguments); }; }; Shared.addModule('OldView', OldView); CollectionGroup = _dereq_('./CollectionGroup'); Collection = _dereq_('./Collection'); CollectionInit = Collection.prototype.init; CollectionGroupInit = CollectionGroup.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Shared.mixin(OldView.prototype, 'Mixin.Events'); /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ OldView.prototype.drop = function () { if ((this._db || this._from) && this._name) { if (this.debug()) { console.log('ForerunnerDB.OldView: Dropping view ' + this._name); } this._state = 'dropped'; this.emit('drop', this); if (this._db && this._db._oldViews) { delete this._db._oldViews[this._name]; } if (this._from && this._from._oldViews) { delete this._from._oldViews[this._name]; } return true; } return false; }; OldView.prototype.debug = function () { // TODO: Make this function work return false; }; /** * Gets / sets the DB the view is bound against. Automatically set * when the db.oldView(viewName) method is called. * @param db * @returns {*} */ OldView.prototype.db = function (db) { if (db !== undefined) { this._db = db; return this; } return this._db; }; /** * Gets / sets the collection that the view derives it's data from. * @param {*} collection A collection instance or the name of a collection * to use as the data set to derive view data from. * @returns {*} */ OldView.prototype.from = function (collection) { if (collection !== undefined) { // Check if this is a collection name or a collection instance if (typeof(collection) === 'string') { if (this._db.collectionExists(collection)) { collection = this._db.collection(collection); } else { throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.'); } } // Check if the existing from matches the passed one if (this._from !== collection) { // Check if we already have a collection assigned if (this._from) { // Remove ourselves from the collection view lookup this.removeFrom(); } this.addFrom(collection); } return this; } return this._from; }; OldView.prototype.addFrom = function (collection) { //var self = this; this._from = collection; if (this._from) { this._from.on('setData', this._onFromSetData); //this._from.on('insert', this._onFromInsert); //this._from.on('update', this._onFromUpdate); //this._from.on('remove', this._onFromRemove); this._from.on('change', this._onFromChange); // Add this view to the collection's view lookup this._from._addOldView(this); this._primaryKey = this._from._primaryKey; this.refresh(); return this; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()'); } }; OldView.prototype.removeFrom = function () { // Unsubscribe from events on this "from" this._from.off('setData', this._onFromSetData); //this._from.off('insert', this._onFromInsert); //this._from.off('update', this._onFromUpdate); //this._from.off('remove', this._onFromRemove); this._from.off('change', this._onFromChange); this._from._removeOldView(this); }; /** * Gets the primary key for this view from the assigned collection. * @returns {String} */ OldView.prototype.primaryKey = function () { if (this._from) { return this._from.primaryKey(); } return undefined; }; /** * Gets / sets the query that the view uses to build it's data set. * @param {Object=} query * @param {Boolean=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._query.query = query; } if (options !== undefined) { this._query.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query; }; /** * 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. */ OldView.prototype.queryAdd = function (obj, overwrite, refresh) { var query = this._query.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)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ OldView.prototype.queryRemove = function (obj, refresh) { var query = this._query.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Gets / sets the query being used to generate the view data. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.query = function (query, refresh) { if (query !== undefined) { this._query.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.query; }; /** * 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 {*} */ OldView.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._query.options = options; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.options; }; /** * Refreshes the view data and diffs between previous and new data to * determine if any events need to be triggered or DOM binds updated. */ OldView.prototype.refresh = function (force) { if (this._from) { // Take a copy of the data before updating it, we will use this to // "diff" between the old and new data and handle DOM bind updates var oldData = this._data, oldDataArr, oldDataItem, newData, newDataArr, query, primaryKey, dataItem, inserted = [], updated = [], removed = [], operated = false, i; if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing view ' + this._name); console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined")); if (typeof(this._data) !== "undefined") { console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length); } //console.log(OldView.prototype.refresh.caller); } // Query the collection and update the data if (this._query) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has query and options, getting subset...'); } // Run query against collection //console.log('refresh with query and options', this._query.options); this._data = this._from.subset(this._query.query, this._query.options); //console.log(this._data); } else { // No query, return whole collection if (this._query.options) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has options, getting subset...'); } this._data = this._from.subset({}, this._query.options); } else { if (this.debug()) { console.log('ForerunnerDB.OldView: View has no query or options, getting subset...'); } this._data = this._from.subset({}); } } // Check if there was old data if (!force && oldData) { if (this.debug()) { console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...'); } // Now determine the difference newData = this._data; if (oldData.subsetOf() === newData.subsetOf()) { if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from same collection...'); } newDataArr = newData.find(); oldDataArr = oldData.find(); primaryKey = newData._primaryKey; // The old data and new data were derived from the same parent collection // so scan the data to determine changes for (i = 0; i < newDataArr.length; i++) { dataItem = newDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data oldDataItem = oldData.find(query)[0]; if (!oldDataItem) { // New item detected inserted.push(dataItem); } else { // Check if an update has occurred if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) { // Updated / already included item detected updated.push(dataItem); } } } // Now loop the old data and check if any records were removed for (i = 0; i < oldDataArr.length; i++) { dataItem = oldDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data if (!newData.find(query)[0]) { // Removed item detected removed.push(dataItem); } } if (this.debug()) { console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows'); console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows'); console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows'); } // Now we have a diff of the two data sets, we need to get the DOM updated if (inserted.length) { this._onInsert(inserted, []); operated = true; } if (updated.length) { this._onUpdate(updated, []); operated = true; } if (removed.length) { this._onRemove(removed, []); operated = true; } } else { // The previous data and the new data are derived from different collections // and can therefore not be compared, all data is therefore effectively "new" // so first perform a remove of all existing data then do an insert on all new data if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from different collections...'); } removed = oldData.find(); if (removed.length) { this._onRemove(removed); operated = true; } inserted = newData.find(); if (inserted.length) { this._onInsert(inserted); operated = true; } } } else { // Force an update as if the view never got created by padding all elements // to the insert if (this.debug()) { console.log('ForerunnerDB.OldView: Forcing data update', newDataArr); } this._data = this._from.subset(this._query.query, this._query.options); newDataArr = this._data.find(); if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr); } this._onInsert(newDataArr, []); } if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); } this.emit('change'); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ OldView.prototype.count = function () { return this._data && this._data._data ? this._data._data.length : 0; }; /** * Queries the view data. See Collection.find() for more information. * @returns {*} */ OldView.prototype.find = function () { if (this._data) { if (this.debug()) { console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data); } return this._data.find.apply(this._data, arguments); } else { return []; } }; /** * Inserts into view data via the view collection. See Collection.insert() for more information. * @returns {*} */ OldView.prototype.insert = function () { if (this._from) { // Pass the args through to the from object return this._from.insert.apply(this._from, arguments); } else { return []; } }; /** * Updates into view data via the view collection. See Collection.update() for more information. * @returns {*} */ OldView.prototype.update = function () { if (this._from) { // Pass the args through to the from object return this._from.update.apply(this._from, arguments); } else { return []; } }; /** * Removed from view data via the view collection. See Collection.remove() for more information. * @returns {*} */ OldView.prototype.remove = function () { if (this._from) { // Pass the args through to the from object return this._from.remove.apply(this._from, arguments); } else { return []; } }; OldView.prototype._onSetData = function (newDataArr, oldDataArr) { this.emit('remove', oldDataArr, []); this.emit('insert', newDataArr, []); //this.refresh(); }; OldView.prototype._onInsert = function (successArr, failArr) { this.emit('insert', successArr, failArr); //this.refresh(); }; OldView.prototype._onUpdate = function (successArr, failArr) { this.emit('update', successArr, failArr); //this.refresh(); }; OldView.prototype._onRemove = function (successArr, failArr) { this.emit('remove', successArr, failArr); //this.refresh(); }; OldView.prototype._onChange = function () { if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); } this.refresh(); }; // Extend collection with view init Collection.prototype.init = function () { this._oldViews = []; CollectionInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend collection with view init CollectionGroup.prototype.init = function () { this._oldViews = []; CollectionGroupInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ CollectionGroup.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ CollectionGroup.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend DB with views init Db.prototype.init = function () { this._oldViews = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.oldView = function (viewName) { if (!this._oldViews[viewName]) { if (this.debug()) { console.log('ForerunnerDB.OldView: Creating view ' + viewName); } } this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this); return this._oldViews[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.oldViewExists = function (viewName) { return Boolean(this._oldViews[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.oldViews = function () { var arr = [], i; for (i in this._oldViews) { if (this._oldViews.hasOwnProperty(i)) { arr.push({ name: i, count: this._oldViews[i].count() }); } } return arr; }; Shared.finishModule('OldView'); module.exports = OldView; },{"./Collection":4,"./CollectionGroup":5,"./Shared":35}],27:[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":30,"./Shared":35}],28:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],29:[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'); 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 () { 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]; } delete this._name; this.emit('drop', this); } return true; }; Db.prototype.overview = function (overviewName) { if (overviewName) { // Handle being passed an instance if (overviewName instanceof Overview) { return overviewName; } this._overview = this._overview || {}; this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this); return this._overview[overviewName]; } 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":4,"./Document":9,"./Shared":35}],30:[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.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. * * @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') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * 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(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; 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])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * 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; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * 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; }; /** * 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":35}],31:[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; /** * 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) { this._encodeSteps = [ this._encode ]; this._decodeSteps = [ this._decode ]; // 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'); 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 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) { 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) { 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 = JSON.parse(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 = JSON.parse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } 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::' + JSON.stringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } 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) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { 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.apply(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); }); } 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!'); } } } // Call the original method CollectionDrop.apply(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) { 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!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Db.prototype.load = function (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 obj[index].load(loadCallback); } } }; /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Db.prototype.save = function (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 obj[index].save(saveCallback); } } }; Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":32,"./PersistCrypto":33,"./Shared":35,"async":37,"localforage":79}],32:[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) { }; 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, JSON.stringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = JSON.parse(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 the persistent storage class Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":35,"pako":81}],33:[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; }; /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype._jsonFormatter = { 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 JSON.stringify(jsonObj); }, parse: function (jsonStr) { // parse json string var jsonObj = JSON.parse(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 wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: this._jsonFormatter }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, JSON.stringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var data; if (wrapper) { wrapper = JSON.parse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: this._jsonFormatter }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with the persistent storage class Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":35,"crypto-js":46}],34:[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. * @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 reactoreOut 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 || !reactorOut.chainReceive) { 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); } 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":35}],35:[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.302', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Triggers":23,"./Mixin.Updating":24,"./Overload":28}],36:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, false); this.queryOptions(options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection(this.name() + '_internalPrivate'); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this.publicData().findById(id, options); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } if (typeof(source) === 'string') { source = this._db.collection(source); } if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } this._from = source; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" source and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(source, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check that the state of the "self" object is not dropped if (self && !self.isDropped()) { // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = source.find(this._querySettings.query, this._querySettings.options); this._transformPrimaryKey(source.primaryKey()); this._transformSetData(collData); this._privateData.primaryKey(source.primaryKey()); this._privateData.setData(collData); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, //tempData, //dataIsArray, updates, //finalUpdates, primaryKey, tQuery, item, currentIndex, i; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data'); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); // Modify transform data this._transformSetData(collData); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } if (this._transformEnabled && this._transformIn) { primaryKey = this._publicData.primaryKey(); for (i = 0; i < updates.length; i++) { tQuery = {}; item = updates[i]; tQuery[primaryKey] = item[primaryKey]; this._transformUpdate(tQuery, item); } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"'); } // Modify transform data this._transformRemove(chainPacket.data.query, chainPacket.options); this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._privateData.on.apply(this._privateData, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._privateData.off.apply(this._privateData, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._privateData.distinct.apply(this._privateData, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._privateData.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 () { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } } else { return true; } return false; }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this.privateData().db(db); this.publicData().db(db); // Apply the same debug settings this.debug(db.debug()); this.privateData().debug(db.debug()); this.publicData().debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { if (this.publicData()) { return this.publicData().count.apply(this.publicData(), arguments); } return 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { 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; } // Update the transformed data object this._transformPrimaryKey(this.privateData().primaryKey()); this._transformSetData(this.privateData().find()); return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; /** * Updates the public data object to match data from the private data object * by running private data through the dataIn method provided in * the transform() call. * @private */ View.prototype._transformSetData = function (data) { if (this._transformEnabled) { // Clear existing data this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); this._publicData.setData(data); } }; View.prototype._transformInsert = function (data, index) { if (this._transformEnabled && this._publicData) { this._publicData.insert(data, index); } }; View.prototype._transformUpdate = function (query, update, options) { if (this._transformEnabled && this._publicData) { this._publicData.update(query, update, options); } }; View.prototype._transformRemove = function (query, options) { if (this._transformEnabled && this._publicData) { this._publicData.remove(query, options); } }; View.prototype._transformPrimaryKey = function (key) { if (this._transformEnabled && this._publicData) { this._publicData.primaryKey(key); } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { // Handle being passed an instance if (viewName instanceof View) { return viewName; } if (!this._view[viewName]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":34,"./Shared":35}],37:[function(_dereq_,module,exports){ (function (process){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ /*jshint onevar: false, indent:4 */ /*global setImmediate: false, setTimeout: false, console: false */ (function () { var async = {}; // global on the server, window in the browser var root, previous_async; root = this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { var called = false; return function() { if (called) throw new Error("Callback was already called."); called = true; fn.apply(root, arguments); } } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; var _each = function (arr, iterator) { for (var i = 0; i < arr.length; i += 1) { iterator(arr[i], i, arr); } }; var _map = function (arr, iterator) { if (arr.map) { return arr.map(iterator); } var results = []; _each(arr, function (x, i, a) { results.push(iterator(x, i, a)); }); return results; }; var _reduce = function (arr, iterator, memo) { if (arr.reduce) { return arr.reduce(iterator, memo); } _each(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; }; var _keys = function (obj) { if (Object.keys) { return Object.keys(obj); } var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// if (typeof process === 'undefined' || !(process.nextTick)) { if (typeof setImmediate === 'function') { async.nextTick = function (fn) { // not a direct alias for IE10 compatibility setImmediate(fn); }; async.setImmediate = async.nextTick; } else { async.nextTick = function (fn) { setTimeout(fn, 0); }; async.setImmediate = async.nextTick; } } else { async.nextTick = process.nextTick; if (typeof setImmediate !== 'undefined') { async.setImmediate = function (fn) { // not a direct alias for IE10 compatibility setImmediate(fn); }; } else { async.setImmediate = async.nextTick; } } async.each = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; _each(arr, function (x) { iterator(x, only_once(done) ); }); function done(err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(); } } } }; async.forEach = async.each; async.eachSeries = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; var iterate = function () { iterator(arr[completed], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(); } else { iterate(); } } }); }; iterate(); }; async.forEachSeries = async.eachSeries; async.eachLimit = function (arr, limit, iterator, callback) { var fn = _eachLimit(limit); fn.apply(null, [arr, iterator, callback]); }; async.forEachLimit = async.eachLimit; var _eachLimit = function (limit) { return function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length || limit <= 0) { return callback(); } var completed = 0; var started = 0; var running = 0; (function replenish () { if (completed >= arr.length) { return callback(); } while (running < limit && started < arr.length) { started += 1; running += 1; iterator(arr[started - 1], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; running -= 1; if (completed >= arr.length) { callback(); } else { replenish(); } } }); } })(); }; }; var doParallel = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.each].concat(args)); }; }; var doParallelLimit = function(limit, fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [_eachLimit(limit)].concat(args)); }; }; var doSeries = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.eachSeries].concat(args)); }; }; var _asyncMap = function (eachfn, arr, iterator, callback) { arr = _map(arr, function (x, i) { return {index: i, value: x}; }); if (!callback) { eachfn(arr, function (x, callback) { iterator(x.value, function (err) { callback(err); }); }); } else { var results = []; eachfn(arr, function (x, callback) { iterator(x.value, function (err, v) { results[x.index] = v; callback(err); }); }, function (err) { callback(err, results); }); } }; async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = function (arr, limit, iterator, callback) { return _mapLimit(limit)(arr, iterator, callback); }; var _mapLimit = function(limit) { return doParallelLimit(limit, _asyncMap); }; // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.reduce = function (arr, memo, iterator, callback) { async.eachSeries(arr, function (x, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; // inject alias async.inject = async.reduce; // foldl alias async.foldl = async.reduce; async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, function (x) { return x; }).reverse(); async.reduce(reversed, memo, iterator, callback); }; // foldr alias async.foldr = async.reduceRight; var _filter = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.filter = doParallel(_filter); async.filterSeries = doSeries(_filter); // select alias async.select = async.filter; async.selectSeries = async.filterSeries; var _reject = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (!v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.reject = doParallel(_reject); async.rejectSeries = doSeries(_reject); var _detect = function (eachfn, arr, iterator, main_callback) { eachfn(arr, function (x, callback) { iterator(x, function (result) { if (result) { main_callback(x); main_callback = function () {}; } else { callback(); } }); }, function (err) { main_callback(); }); }; async.detect = doParallel(_detect); async.detectSeries = doSeries(_detect); async.some = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (v) { main_callback(true); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(false); }); }; // any alias async.any = async.some; async.every = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (!v) { main_callback(false); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(true); }); }; // all alias async.all = async.every; 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 { var fn = function (left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }; callback(null, _map(results.sort(fn), function (x) { return x.value; })); } }); }; async.auto = function (tasks, callback) { callback = callback || function () {}; var keys = _keys(tasks); var remainingTasks = keys.length if (!remainingTasks) { return callback(); } var results = {}; var listeners = []; var addListener = function (fn) { listeners.unshift(fn); }; var removeListener = function (fn) { for (var i = 0; i < listeners.length; i += 1) { if (listeners[i] === fn) { listeners.splice(i, 1); return; } } }; var taskComplete = function () { remainingTasks-- _each(listeners.slice(0), function (fn) { fn(); }); }; addListener(function () { if (!remainingTasks) { var theCallback = callback; // prevent final callback from calling itself if it errors callback = function () {}; theCallback(null, results); } }); _each(keys, function (k) { var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _each(_keys(results), function(rkey) { safeResults[rkey] = results[rkey]; }); safeResults[k] = args; callback(err, safeResults); // stop subsequent errors hitting callback multiple times callback = function () {}; } else { results[k] = args; async.setImmediate(taskComplete); } }; var requires = task.slice(0, Math.abs(task.length - 1)) || []; var ready = function () { return _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); }; if (ready()) { task[task.length - 1](taskCallback, results); } else { var listener = function () { if (ready()) { removeListener(listener); task[task.length - 1](taskCallback, results); } }; addListener(listener); } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var attempts = []; // Use defaults if times not passed if (typeof times === 'function') { callback = task; task = times; times = DEFAULT_TIMES; } // Make sure times is a number times = parseInt(times, 10) || DEFAULT_TIMES; var wrappedTask = function(wrappedCallback, wrappedResults) { var retryAttempt = function(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; }; while (times) { attempts.push(retryAttempt(task, !(times-=1))); } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return callback ? wrappedTask() : wrappedTask }; async.waterfall = function (tasks, callback) { callback = callback || function () {}; 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(); } var wrapIterator = function (iterator) { return function (err) { if (err) { callback.apply(null, arguments); callback = function () {}; } else { var args = Array.prototype.slice.call(arguments, 1); var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } async.setImmediate(function () { iterator.apply(null, args); }); } }; }; wrapIterator(async.iterator(tasks))(); }; var _parallel = function(eachfn, tasks, callback) { callback = callback || function () {}; if (_isArray(tasks)) { eachfn.map(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; eachfn.each(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.parallel = function (tasks, callback) { _parallel({ map: async.map, each: async.each }, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); }; async.series = function (tasks, callback) { callback = callback || function () {}; if (_isArray(tasks)) { async.mapSeries(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; async.eachSeries(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.iterator = function (tasks) { var makeCallback = function (index) { var fn = function () { 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 = function (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply( null, args.concat(Array.prototype.slice.call(arguments)) ); }; }; var _concat = function (eachfn, arr, fn, callback) { var r = []; eachfn(arr, function (x, cb) { fn(x, function (err, y) { r = r.concat(y || []); cb(err); }); }, function (err) { callback(err, r); }); }; async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { if (test()) { iterator(function (err) { if (err) { return callback(err); } async.whilst(test, iterator, callback); }); } else { callback(); } }; async.doWhilst = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } var args = Array.prototype.slice.call(arguments, 1); if (test.apply(null, args)) { async.doWhilst(iterator, test, callback); } else { callback(); } }); }; async.until = function (test, iterator, callback) { if (!test()) { iterator(function (err) { if (err) { return callback(err); } async.until(test, iterator, callback); }); } else { callback(); } }; async.doUntil = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } var args = Array.prototype.slice.call(arguments, 1); if (!test.apply(null, args)) { async.doUntil(iterator, test, callback); } else { callback(); } }); }; async.queue = function (worker, concurrency) { if (concurrency === undefined) { concurrency = 1; } function _insert(q, data, pos, callback) { if (!q.started){ q.started = true; } if (!_isArray(data)) { data = [data]; } if(data.length == 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { if (q.drain) { q.drain(); } }); } _each(data, function(task) { var item = { data: task, callback: typeof callback === 'function' ? callback : null }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.saturated && q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } var workers = 0; var q = { tasks: [], concurrency: concurrency, saturated: null, empty: null, drain: null, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = null; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (!q.paused && workers < q.concurrency && q.tasks.length) { var task = q.tasks.shift(); if (q.empty && q.tasks.length === 0) { q.empty(); } workers += 1; var next = function () { workers -= 1; if (task.callback) { task.callback.apply(task, arguments); } if (q.drain && q.tasks.length + workers === 0) { q.drain(); } q.process(); }; var cb = only_once(next); worker(task.data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { if (q.paused === true) { return; } q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= q.concurrency; w++) { async.setImmediate(q.process); } } }; 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 (!q.started){ q.started = true; } if (!_isArray(data)) { data = [data]; } if(data.length == 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { if (q.drain) { q.drain(); } }); } _each(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : null }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.saturated && 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) { var working = false, tasks = []; var cargo = { tasks: tasks, payload: payload, saturated: null, empty: null, drain: null, drained: true, push: function (data, callback) { if (!_isArray(data)) { data = [data]; } _each(data, function(task) { tasks.push({ data: task, callback: typeof callback === 'function' ? callback : null }); cargo.drained = false; if (cargo.saturated && tasks.length === payload) { cargo.saturated(); } }); async.setImmediate(cargo.process); }, process: function process() { if (working) return; if (tasks.length === 0) { if(cargo.drain && !cargo.drained) cargo.drain(); cargo.drained = true; return; } var ts = typeof payload === 'number' ? tasks.splice(0, payload) : tasks.splice(0, tasks.length); var ds = _map(ts, function (task) { return task.data; }); if(cargo.empty) cargo.empty(); working = true; worker(ds, function () { working = false; var args = arguments; _each(ts, function (data) { if (data.callback) { data.callback.apply(null, args); } }); process(); }); }, length: function () { return tasks.length; }, running: function () { return working; } }; return cargo; }; var _console_fn = function (name) { return function (fn) { var args = Array.prototype.slice.call(arguments, 1); fn.apply(null, args.concat([function (err) { var args = Array.prototype.slice.call(arguments, 1); if (typeof console !== 'undefined') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _each(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 = {}; hasher = hasher || function (x) { return x; }; var memoized = function () { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.nextTick(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([function () { memo[key] = arguments; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, arguments); } }])); } }; memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; async.times = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.map(counter, iterator, callback); }; async.timesSeries = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.mapSeries(counter, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([function () { var err = arguments[0]; var nextargs = Array.prototype.slice.call(arguments, 1); 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)); }; var _applyEach = function (eachfn, fns /*args...*/) { var go = function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); return eachfn(fns, function (fn, cb) { fn.apply(that, args.concat([cb])); }, callback); }; if (arguments.length > 2) { var args = Array.prototype.slice.call(arguments, 2); return go.apply(this, args); } else { return go; } }; async.applyEach = doParallel(_applyEach); async.applyEachSeries = doSeries(_applyEach); async.forever = function (fn, callback) { function next(err) { if (err) { if (callback) { return callback(err); } throw err; } fn(next); } next(); }; // Node.js if (typeof module !== 'undefined' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define !== 'undefined' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process')) },{"_process":72}],38:[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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],39:[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":40}],40:[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; })); },{}],41:[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); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":40}],42:[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":40}],43:[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":40,"./hmac":45,"./sha1":64}],44:[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":39,"./core":40}],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) { (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":40}],46:[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":38,"./cipher-core":39,"./core":40,"./enc-base64":41,"./enc-utf16":42,"./evpkdf":43,"./format-hex":44,"./hmac":45,"./lib-typedarrays":47,"./md5":48,"./mode-cfb":49,"./mode-ctr":51,"./mode-ctr-gladman":50,"./mode-ecb":52,"./mode-ofb":53,"./pad-ansix923":54,"./pad-iso10126":55,"./pad-iso97971":56,"./pad-nopadding":57,"./pad-zeropadding":58,"./pbkdf2":59,"./rabbit":61,"./rabbit-legacy":60,"./rc4":62,"./ripemd160":63,"./sha1":64,"./sha224":65,"./sha256":66,"./sha3":67,"./sha384":68,"./sha512":69,"./tripledes":70,"./x64-core":71}],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 () { // 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":40}],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 (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":40}],49:[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":39,"./core":40}],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) { /** @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":39,"./core":40}],51:[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":39,"./core":40}],52:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * 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":39,"./core":40}],53:[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":39,"./core":40}],54:[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":39,"./core":40}],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) { /** * 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":39,"./core":40}],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) { /** * 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":39,"./core":40}],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) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":39,"./core":40}],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) { /** * 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":39,"./core":40}],59:[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":40,"./hmac":45,"./sha1":64}],60:[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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],61:[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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],62:[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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],63:[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":40}],64:[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":40}],65:[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":40,"./sha256":66}],66:[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":40}],67:[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":40,"./x64-core":71}],68:[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":40,"./sha512":69,"./x64-core":71}],69:[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":40,"./x64-core":71}],70:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var 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":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],71:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (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":40}],72:[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) { currentQueue[queueIndex].run(); } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],73:[function(_dereq_,module,exports){ 'use strict'; var asap = _dereq_('asap') module.exports = Promise function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new') if (typeof fn !== 'function') throw new TypeError('not a function') var state = null var value = null var deferreds = [] var self = this this.then = function(onFulfilled, onRejected) { return new Promise(function(resolve, reject) { handle(new Handler(onFulfilled, onRejected, resolve, reject)) }) } function handle(deferred) { if (state === null) { deferreds.push(deferred) return } asap(function() { var cb = state ? deferred.onFulfilled : deferred.onRejected if (cb === null) { (state ? deferred.resolve : deferred.reject)(value) return } var ret try { ret = cb(value) } catch (e) { deferred.reject(e) return } deferred.resolve(ret) }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.') if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then if (typeof then === 'function') { doResolve(then.bind(newValue), resolve, reject) return } } state = true value = newValue finale() } catch (e) { reject(e) } } function reject(newValue) { state = false value = newValue finale() } function finale() { for (var i = 0, len = deferreds.length; i < len; i++) handle(deferreds[i]) deferreds = null } doResolve(fn, resolve, reject) } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null this.onRejected = typeof onRejected === 'function' ? onRejected : null this.resolve = resolve this.reject = reject } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return done = true onFulfilled(value) }, function (reason) { if (done) return done = true onRejected(reason) }) } catch (ex) { if (done) return done = true onRejected(ex) } } },{"asap":75}],74:[function(_dereq_,module,exports){ 'use strict'; //This file contains then/promise specific extensions to the core promise API var Promise = _dereq_('./core.js') var asap = _dereq_('asap') module.exports = Promise /* Static Functions */ function ValuePromise(value) { this.then = function (onFulfilled) { if (typeof onFulfilled !== 'function') return this return new Promise(function (resolve, reject) { asap(function () { try { resolve(onFulfilled(value)) } catch (ex) { reject(ex); } }) }) } } ValuePromise.prototype = Object.create(Promise.prototype) var TRUE = new ValuePromise(true) var FALSE = new ValuePromise(false) var NULL = new ValuePromise(null) var UNDEFINED = new ValuePromise(undefined) var ZERO = new ValuePromise(0) var EMPTYSTRING = new ValuePromise('') Promise.resolve = function (value) { if (value instanceof Promise) return value if (value === null) return NULL if (value === undefined) return UNDEFINED if (value === true) return TRUE if (value === false) return FALSE if (value === 0) return ZERO if (value === '') return EMPTYSTRING if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then if (typeof then === 'function') { return new Promise(then.bind(value)) } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex) }) } } return new ValuePromise(value) } Promise.from = Promise.cast = function (value) { var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead') err.name = 'Warning' console.warn(err.stack) return Promise.resolve(value) } Promise.denodeify = function (fn, argumentCount) { argumentCount = argumentCount || Infinity return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { while (args.length && args.length > argumentCount) { args.pop() } args.push(function (err, res) { if (err) reject(err) else resolve(res) }) fn.apply(self, args) }) } } Promise.nodeify = function (fn) { return function () { var args = Array.prototype.slice.call(arguments) var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null try { return fn.apply(this, arguments).nodeify(callback) } catch (ex) { if (callback === null || typeof callback == 'undefined') { return new Promise(function (resolve, reject) { reject(ex) }) } else { asap(function () { callback(ex) }) } } } } Promise.all = function () { var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0]) var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments) if (!calledWithArray) { var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated') err.name = 'Warning' console.warn(err.stack) } return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]) var remaining = args.length function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then if (typeof then === 'function') { then.call(val, function (val) { res(i, val) }, reject) return } } args[i] = val if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex) } } for (var i = 0; i < args.length; i++) { res(i, args[i]) } }) } Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); } Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }) }); } /* Prototype Methods */ Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { asap(function () { throw err }) }) } Promise.prototype.nodeify = function (callback) { if (typeof callback != 'function') return this this.then(function (value) { asap(function () { callback(null, value) }) }, function (err) { asap(function () { callback(err) }) }) } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); } },{"./core.js":73,"asap":75}],75:[function(_dereq_,module,exports){ (function (process){ // Use the fastest possible means to execute a task in a future turn // of the event loop. // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestFlush = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestFlush = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestFlush = setImmediate.bind(window, flush); } else { requestFlush = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); channel.port1.onmessage = flush; requestFlush = function () { channel.port2.postMessage(0); }; } else { // old browsers requestFlush = function () { setTimeout(flush, 0); }; } function asap(task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestFlush(); } }; module.exports = asap; }).call(this,_dereq_('_process')) },{"_process":72}],76:[function(_dereq_,module,exports){ // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = window.BlobBuilder || window.MSBlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({status: xhr.status, response: xhr.response}); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function(resolve, reject) { var blob = _createBlob([''], {type: 'image/png'}); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function() { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore( DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function(e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function(res) { resolve(!!(res && res.type === 'image/png')); }, function() { resolve(false); }).then(function() { URL.revokeObjectURL(url); }); }; }; })['catch'](function() { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function(value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function(resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function(e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type}); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function() { reject(openreq.error); }; openreq.onupgradeneeded = function(e) { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // added when support for blob shims was added openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } }; openreq.onsuccess = function() { dbInfo.db = openreq.result; self._dbInfo = dbInfo; resolve(); }; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function() { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function() { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void(0)) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { var dbInfo; self.ready().then(function() { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function(blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function(value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function() { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function() { resolve(); }; transaction.onerror = function() { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function() { resolve(); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function() { resolve(req.result); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function() { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = asyncStorage; } else if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else { this.asyncStorage = asyncStorage; } }).call(window); },{"promise":74}],77:[function(_dereq_,module,exports){ // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; self._dbInfo = dbInfo; var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); return serializerPromise.then(function(lib) { serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; for (var i = 0; i < length; i++) { var key = localStorage.key(i); var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), i + 1); if (value !== void(0)) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function(keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function(resolve, reject) { serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { try { var dbInfo = self._dbInfo; localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.EXPORT) { module.exports = localStorageWrapper; } else if (moduleType === ModuleType.DEFINE) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else { this.localStorageWrapper = localStorageWrapper; } }).call(window); },{"./../utils/serializer":80,"promise":74}],78:[function(_dereq_,module,exports){ /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof(options[i]) !== 'string' ? options[i].toString() : options[i]; } } var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); var dbInfoPromise = new Promise(function(resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function() { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function(t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function() { self._dbInfo = dbInfo; resolve(); }, function(t, error) { reject(error); }); }); }); return serializerPromise.then(function(lib) { serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function(t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = serializer.deserialize(result); } resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function(t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void(0)) { resolve(result); return; } } resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function() { resolve(originalValue); }, function(t, error) { reject(error); }); }, function(sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function(t, results) { var result = results.rows.item(0).c; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function(t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function(t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.DEFINE) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(window); },{"./../utils/serializer":80,"promise":74}],79:[function(_dereq_,module,exports){ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [ DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE ]; var LibraryMethods = [ 'clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem' ]; var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function(self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function() { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function() { try { return (self.localStorage && ('setItem' in self.localStorage) && (self.localStorage.setItem)); } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function() { var _args = arguments; return localForageInstance.ready().then(function() { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var globalObject = this; function LocalForage(options) { this._config = extend({}, DefaultConfig, options); this._driverSet = null; this._ready = false; this._dbInfo = null; // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } this.setDriver(this._config.driver); } LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB; LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE; LocalForage.prototype.WEBSQL = DriverType.WEBSQL; // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof(options) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof(options) === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function(driverObject, callback, errorCallback) { var defineDriver = new Promise(function(resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error( 'Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver' ); var namingError = new Error( 'Custom driver name already in use: ' + driverObject._driver ); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function(supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); defineDriver.then(callback, errorCallback); return defineDriver; }; LocalForage.prototype.driver = function() { return this._driver || null; }; LocalForage.prototype.ready = function(callback) { var self = this; var ready = new Promise(function(resolve, reject) { self._driverSet.then(function() { if (self._ready === null) { self._ready = self._initStorage(self._config); } self._ready.then(resolve, reject); })['catch'](reject); }); ready.then(callback, callback); return ready; }; LocalForage.prototype.setDriver = function(drivers, callback, errorCallback) { var self = this; if (typeof drivers === 'string') { drivers = [drivers]; } this._driverSet = new Promise(function(resolve, reject) { var driverName = self._getFirstSupportedDriver(drivers); var error = new Error('No available storage method found.'); if (!driverName) { self._driverSet = Promise.reject(error); reject(error); return; } self._dbInfo = null; self._ready = null; if (isLibraryDriver(driverName)) { var driverPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_([driverName], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly switch (driverName) { case self.INDEXEDDB: resolve(_dereq_('./drivers/indexeddb')); break; case self.LOCALSTORAGE: resolve(_dereq_('./drivers/localstorage')); break; case self.WEBSQL: resolve(_dereq_('./drivers/websql')); break; } } else { resolve(globalObject[driverName]); } }); driverPromise.then(function(driver) { self._extend(driver); resolve(); }); } else if (CustomDrivers[driverName]) { self._extend(CustomDrivers[driverName]); resolve(); } else { self._driverSet = Promise.reject(error); reject(error); } }); function setDriverToConfig() { self._config.driver = self.driver(); } this._driverSet.then(setDriverToConfig, setDriverToConfig); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; // Used to determine which driver we should use as the backend for this // instance of localForage. LocalForage.prototype._getFirstSupportedDriver = function(drivers) { if (drivers && isArray(drivers)) { for (var i = 0; i < drivers.length; i++) { var driver = drivers[i]; if (this.supports(driver)) { return driver; } } } return null; }; LocalForage.prototype.createInstance = function(options) { return new LocalForage(options); }; // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localForage = new LocalForage(); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { define('localforage', function() { return localForage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(window); },{"./drivers/indexeddb":76,"./drivers/localstorage":77,"./drivers/websql":78,"promise":74}],80:[function(_dereq_,module,exports){ (function() { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function() { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], {type: blobType}); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i+=4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i+1]); encoded3 = BASE_CHARS.indexOf(serializedString[i+2]); encoded4 = BASE_CHARS.indexOf(serializedString[i+3]); /*jslint bitwise: true */ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if ((bytes.length % 3) === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = localforageSerializer; } else if (typeof define === 'function' && define.amd) { define('localforageSerializer', function() { return localforageSerializer; }); } else { this.localforageSerializer = localforageSerializer; } }).call(window); },{}],81:[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":82,"./lib/inflate":83,"./lib/utils/common":84,"./lib/zlib/constants":87}],82:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); 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); * ``` **/ var Deflate = function(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 alrorythm 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":84,"./utils/strings":85,"./zlib/deflate.js":89,"./zlib/messages":94,"./zlib/zstream":96}],83:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); 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); * ``` **/ var Inflate = function(options) { this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force sWindow 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 sWindow 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; 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_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)); } } } } while ((strm.avail_in > 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":84,"./utils/strings":85,"./zlib/constants":87,"./zlib/gzheader":90,"./zlib/inflate.js":92,"./zlib/messages":94,"./zlib/zstream":96}],84:[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); },{}],85:[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":84}],86:[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; },{}],87:[function(_dereq_,module,exports){ 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 }; },{}],88:[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 = crc ^ (-1); for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],89:[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 sWindow */ 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.sWindow; // 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 sWindow 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->sWindow+(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 sWindow 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 sWindow 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.sWindow, s.sWindow, _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.sWindow, 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.sWindow[str]; /* UPDATE_HASH(s, s->ins_h, s->sWindow[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[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->sWindow[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[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 sWindow, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->sWindow + 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 sWindow, 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->sWindow + 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 * sWindow 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 sWindow 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 sWindow[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.sWindow[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 sWindow 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.sWindow[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.sWindow[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.sWindow[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[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.sWindow[s.strstart])); /*** _tr_tally_lit(s, s.sWindow[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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 sWindow 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 sWindow[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.sWindow[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 sWindow 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.sWindow[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->sWindow[s->strstart-1])); /*** _tr_tally_lit(s, s.sWindow[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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->sWindow[s->strstart-1])); /*** _tr_tally_lit(s, s.sWindow[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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.sWindow; 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->sWindow+(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->sWindow[s->strstart])); /*** _tr_tally_lit(s, s.sWindow[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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->sWindow[s->strstart])); /*** _tr_tally_lit(s, s.sWindow[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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. */ var Config = function (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 sWindow size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.sWindow = null; /* Sliding sWindow. Input bytes are read into the second half of the sWindow, * 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 sWindow: 2*wSize, except when the user input buffer * is directly used as sliding sWindow. */ 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 sWindow 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; /* sWindow position at the beginning of the current output block. Gets * negative when the sWindow 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 sWindow */ 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 sWindow 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 sWindow 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 sWindow 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 sWindow 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 sWindow 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.sWindow = 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->sWindow 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":84,"./adler32":86,"./crc32":88,"./messages":94,"./trees":95}],90:[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; },{}],91:[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; /* sWindow size or zero if not using sWindow */ var whave; /* valid bytes in the sWindow */ var wnext; /* sWindow write index */ var sWindow; /* allocated sliding sWindow, 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 */ /* sWindow position, sWindow 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; sWindow = state.sWindow; 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 sWindow */ op = dist - op; /* distance back in sWindow */ 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; // sWindow index from_source = sWindow; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from sWindow */ len -= op; do { output[_out++] = sWindow[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around sWindow */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of sWindow */ len -= op; do { output[_out++] = sWindow[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of sWindow */ op = wnext; len -= op; do { output[_out++] = sWindow[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in sWindow */ from += wnext - op; if (op < len) { /* some from sWindow */ len -= op; do { output[_out++] = sWindow[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; }; },{}],92:[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 sWindow */ 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 sWindow */ this.wbits = 0; /* log base 2 of requested sWindow size */ this.wsize = 0; /* sWindow size or zero if not using sWindow */ this.whave = 0; /* valid bytes in the sWindow */ this.wnext = 0; /* sWindow write index */ this.sWindow = null; /* allocated sliding sWindow, 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 sWindow bits, free sWindow if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.sWindow !== null && state.wbits !== windowBits) { state.sWindow = 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.sWindow = 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 sWindow with the last wsize (normally 32K) bytes written before returning. If sWindow does not exist yet, create it. This is only called when a sWindow 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 sWindow 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 sWindow 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 sWindow */ if (state.sWindow === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.sWindow = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular sWindow */ if (copy >= state.wsize) { utils.arraySet(state.sWindow,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->sWindow + state->wnext, end - copy, dist); utils.arraySet(state.sWindow,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->sWindow, end - copy, copy); utils.arraySet(state.sWindow,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 sWindow 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 /*crc32(0L, Z_NULL, 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 sWindow */ 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.sWindow; } 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 sWindow 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.sWindow) { state.sWindow = 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":84,"./adler32":86,"./crc32":88,"./inffast":91,"./inftrees":93}],93:[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":84}],94:[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) */ }; },{}],95:[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) */ 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]; /* 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) */ var StaticTreeDesc = function (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; var TreeDesc = function(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.sWindow, 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":84}],96:[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; },{}]},{},[1]);
src/containers/NotFound/NotFound.js
shalomeir/snippod-starter-demo-app-front
import React, { Component } from 'react'; export default class NotFound extends Component { render() { return ( <div className="not-found container main-container"> <h1>Doh! 404!</h1> <p>These are <em>not</em> the droids you are looking for!</p> </div> ); } }
frontend/src/index.js
jirkae/BeerCheese
import React from 'react'; import ReactDOM from 'react-dom'; import 'bootstrap/dist/css/bootstrap.css'; import App from './App'; import { configureStore } from './store/configureStore'; const store = configureStore(); ReactDOM.render( <App store={store} />, document.getElementById('root'), );
vendors/parsleyjs/dist/parsley.js
cwtang28/servisbid
/*! * Parsley.js * Version 2.3.13 - built Tue, May 31st 2016, 8:55 am * http://parsleyjs.org * Guillaume Potier - <guillaume@wisembly.com> * Marc-Andre Lafortune - <petroselinum@marc-andre.ca> * MIT Licensed */ // The source code below is generated by babel as // Parsley is written in ECMAScript 6 // var _slice = Array.prototype.slice; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : global.parsley = factory(global.jQuery); })(this, function ($) { 'use strict'; var globalID = 1; var pastWarnings = {}; var ParsleyUtils__ParsleyUtils = { // Parsley DOM-API // returns object from dom attributes and values attr: function attr($element, namespace, obj) { var i; var attribute; var attributes; var regex = new RegExp('^' + namespace, 'i'); if ('undefined' === typeof obj) obj = {};else { // Clear all own properties. This won't affect prototype's values for (i in obj) { if (obj.hasOwnProperty(i)) delete obj[i]; } } if ('undefined' === typeof $element || 'undefined' === typeof $element[0]) return obj; attributes = $element[0].attributes; for (i = attributes.length; i--;) { attribute = attributes[i]; if (attribute && attribute.specified && regex.test(attribute.name)) { obj[this.camelize(attribute.name.slice(namespace.length))] = this.deserializeValue(attribute.value); } } return obj; }, checkAttr: function checkAttr($element, namespace, _checkAttr) { return $element.is('[' + namespace + _checkAttr + ']'); }, setAttr: function setAttr($element, namespace, attr, value) { $element[0].setAttribute(this.dasherize(namespace + attr), String(value)); }, generateID: function generateID() { return '' + globalID++; }, /** Third party functions **/ // Zepto deserialize function deserializeValue: function deserializeValue(value) { var num; try { return value ? value == "true" || (value == "false" ? false : value == "null" ? null : !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value) : value; } catch (e) { return value; } }, // Zepto camelize function camelize: function camelize(str) { return str.replace(/-+(.)?/g, function (match, chr) { return chr ? chr.toUpperCase() : ''; }); }, // Zepto dasherize function dasherize: function dasherize(str) { return str.replace(/::/g, '/').replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').replace(/_/g, '-').toLowerCase(); }, warn: function warn() { var _window$console; if (window.console && 'function' === typeof window.console.warn) (_window$console = window.console).warn.apply(_window$console, arguments); }, warnOnce: function warnOnce(msg) { if (!pastWarnings[msg]) { pastWarnings[msg] = true; this.warn.apply(this, arguments); } }, _resetWarnings: function _resetWarnings() { pastWarnings = {}; }, trimString: function trimString(string) { return string.replace(/^\s+|\s+$/g, ''); }, namespaceEvents: function namespaceEvents(events, namespace) { events = this.trimString(events || '').split(/\s+/); if (!events[0]) return ''; return $.map(events, function (evt) { return evt + '.' + namespace; }).join(' '); }, // Object.create polyfill, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill objectCreate: Object.create || (function () { var Object = function Object() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype != 'object') { throw TypeError('Argument must be an object'); } Object.prototype = prototype; var result = new Object(); Object.prototype = null; return result; }; })() }; var ParsleyUtils__default = ParsleyUtils__ParsleyUtils; // All these options could be overriden and specified directly in DOM using // `data-parsley-` default DOM-API // eg: `inputs` can be set in DOM using `data-parsley-inputs="input, textarea"` // eg: `data-parsley-stop-on-first-failing-constraint="false"` var ParsleyDefaults = { // ### General // Default data-namespace for DOM API namespace: 'data-parsley-', // Supported inputs by default inputs: 'input, textarea, select', // Excluded inputs by default excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]', // Stop validating field on highest priority failing constraint priorityEnabled: true, // ### Field only // identifier used to group together inputs (e.g. radio buttons...) multiple: null, // identifier (or array of identifiers) used to validate only a select group of inputs group: null, // ### UI // Enable\Disable error messages uiEnabled: true, // Key events threshold before validation validationThreshold: 3, // Focused field on form validation error. 'first'|'last'|'none' focus: 'first', // event(s) that will trigger validation before first failure. eg: `input`... trigger: false, // event(s) that will trigger validation after first failure. triggerAfterFailure: 'input', // Class that would be added on every failing validation Parsley field errorClass: 'parsley-error', // Same for success validation successClass: 'parsley-success', // Return the `$element` that will receive these above success or error classes // Could also be (and given directly from DOM) a valid selector like `'#div'` classHandler: function classHandler(ParsleyField) {}, // Return the `$element` where errors will be appended // Could also be (and given directly from DOM) a valid selector like `'#div'` errorsContainer: function errorsContainer(ParsleyField) {}, // ul elem that would receive errors' list errorsWrapper: '<ul class="parsley-errors-list"></ul>', // li elem that would receive error message errorTemplate: '<li></li>' }; var ParsleyAbstract = function ParsleyAbstract() { this.__id__ = ParsleyUtils__default.generateID(); }; ParsleyAbstract.prototype = { asyncSupport: true, // Deprecated _pipeAccordingToValidationResult: function _pipeAccordingToValidationResult() { var _this = this; var pipe = function pipe() { var r = $.Deferred(); if (true !== _this.validationResult) r.reject(); return r.resolve().promise(); }; return [pipe, pipe]; }, actualizeOptions: function actualizeOptions() { ParsleyUtils__default.attr(this.$element, this.options.namespace, this.domOptions); if (this.parent && this.parent.actualizeOptions) this.parent.actualizeOptions(); return this; }, _resetOptions: function _resetOptions(initOptions) { this.domOptions = ParsleyUtils__default.objectCreate(this.parent.options); this.options = ParsleyUtils__default.objectCreate(this.domOptions); // Shallow copy of ownProperties of initOptions: for (var i in initOptions) { if (initOptions.hasOwnProperty(i)) this.options[i] = initOptions[i]; } this.actualizeOptions(); }, _listeners: null, // Register a callback for the given event name // Callback is called with context as the first argument and the `this` // The context is the current parsley instance, or window.Parsley if global // A return value of `false` will interrupt the calls on: function on(name, fn) { this._listeners = this._listeners || {}; var queue = this._listeners[name] = this._listeners[name] || []; queue.push(fn); return this; }, // Deprecated. Use `on` instead subscribe: function subscribe(name, fn) { $.listenTo(this, name.toLowerCase(), fn); }, // Unregister a callback (or all if none is given) for the given event name off: function off(name, fn) { var queue = this._listeners && this._listeners[name]; if (queue) { if (!fn) { delete this._listeners[name]; } else { for (var i = queue.length; i--;) if (queue[i] === fn) queue.splice(i, 1); } } return this; }, // Deprecated. Use `off` unsubscribe: function unsubscribe(name, fn) { $.unsubscribeTo(this, name.toLowerCase()); }, // Trigger an event of the given name // A return value of `false` interrupts the callback chain // Returns false if execution was interrupted trigger: function trigger(name, target, extraArg) { target = target || this; var queue = this._listeners && this._listeners[name]; var result; var parentResult; if (queue) { for (var i = queue.length; i--;) { result = queue[i].call(target, target, extraArg); if (result === false) return result; } } if (this.parent) { return this.parent.trigger(name, target, extraArg); } return true; }, // Reset UI reset: function reset() { // Field case: just emit a reset event for UI if ('ParsleyForm' !== this.__class__) { this._resetUI(); return this._trigger('reset'); } // Form case: emit a reset event for each field for (var i = 0; i < this.fields.length; i++) this.fields[i].reset(); this._trigger('reset'); }, // Destroy Parsley instance (+ UI) destroy: function destroy() { // Field case: emit destroy event to clean UI and then destroy stored instance this._destroyUI(); if ('ParsleyForm' !== this.__class__) { this.$element.removeData('Parsley'); this.$element.removeData('ParsleyFieldMultiple'); this._trigger('destroy'); return; } // Form case: destroy all its fields and then destroy stored instance for (var i = 0; i < this.fields.length; i++) this.fields[i].destroy(); this.$element.removeData('Parsley'); this._trigger('destroy'); }, asyncIsValid: function asyncIsValid(group, force) { ParsleyUtils__default.warnOnce("asyncIsValid is deprecated; please use whenValid instead"); return this.whenValid({ group: group, force: force }); }, _findRelated: function _findRelated() { return this.options.multiple ? this.parent.$element.find('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]') : this.$element; } }; var requirementConverters = { string: function string(_string) { return _string; }, integer: function integer(string) { if (isNaN(string)) throw 'Requirement is not an integer: "' + string + '"'; return parseInt(string, 10); }, number: function number(string) { if (isNaN(string)) throw 'Requirement is not a number: "' + string + '"'; return parseFloat(string); }, reference: function reference(string) { // Unused for now var result = $(string); if (result.length === 0) throw 'No such reference: "' + string + '"'; return result; }, boolean: function boolean(string) { return string !== 'false'; }, object: function object(string) { return ParsleyUtils__default.deserializeValue(string); }, regexp: function regexp(_regexp) { var flags = ''; // Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern if (/^\/.*\/(?:[gimy]*)$/.test(_regexp)) { // Replace the regexp literal string with the first match group: ([gimy]*) // If no flag is present, this will be a blank string flags = _regexp.replace(/.*\/([gimy]*)$/, '$1'); // Again, replace the regexp literal string with the first match group: // everything excluding the opening and closing slashes and the flags _regexp = _regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1'); } else { // Anchor regexp: _regexp = '^' + _regexp + '$'; } return new RegExp(_regexp, flags); } }; var convertArrayRequirement = function convertArrayRequirement(string, length) { var m = string.match(/^\s*\[(.*)\]\s*$/); if (!m) throw 'Requirement is not an array: "' + string + '"'; var values = m[1].split(',').map(ParsleyUtils__default.trimString); if (values.length !== length) throw 'Requirement has ' + values.length + ' values when ' + length + ' are needed'; return values; }; var convertRequirement = function convertRequirement(requirementType, string) { var converter = requirementConverters[requirementType || 'string']; if (!converter) throw 'Unknown requirement specification: "' + requirementType + '"'; return converter(string); }; var convertExtraOptionRequirement = function convertExtraOptionRequirement(requirementSpec, string, extraOptionReader) { var main = null; var extra = {}; for (var key in requirementSpec) { if (key) { var value = extraOptionReader(key); if ('string' === typeof value) value = convertRequirement(requirementSpec[key], value); extra[key] = value; } else { main = convertRequirement(requirementSpec[key], string); } } return [main, extra]; }; // A Validator needs to implement the methods `validate` and `parseRequirements` var ParsleyValidator = function ParsleyValidator(spec) { $.extend(true, this, spec); }; ParsleyValidator.prototype = { // Returns `true` iff the given `value` is valid according the given requirements. validate: function validate(value, requirementFirstArg) { if (this.fn) { // Legacy style validator if (arguments.length > 3) // If more args then value, requirement, instance... requirementFirstArg = [].slice.call(arguments, 1, -1); // Skip first arg (value) and last (instance), combining the rest return this.fn.call(this, value, requirementFirstArg); } if ($.isArray(value)) { if (!this.validateMultiple) throw 'Validator `' + this.name + '` does not handle multiple values'; return this.validateMultiple.apply(this, arguments); } else { if (this.validateNumber) { if (isNaN(value)) return false; arguments[0] = parseFloat(arguments[0]); return this.validateNumber.apply(this, arguments); } if (this.validateString) { return this.validateString.apply(this, arguments); } throw 'Validator `' + this.name + '` only handles multiple values'; } }, // Parses `requirements` into an array of arguments, // according to `this.requirementType` parseRequirements: function parseRequirements(requirements, extraOptionReader) { if ('string' !== typeof requirements) { // Assume requirement already parsed // but make sure we return an array return $.isArray(requirements) ? requirements : [requirements]; } var type = this.requirementType; if ($.isArray(type)) { var values = convertArrayRequirement(requirements, type.length); for (var i = 0; i < values.length; i++) values[i] = convertRequirement(type[i], values[i]); return values; } else if ($.isPlainObject(type)) { return convertExtraOptionRequirement(type, requirements, extraOptionReader); } else { return [convertRequirement(type, requirements)]; } }, // Defaults: requirementType: 'string', priority: 2 }; var ParsleyValidatorRegistry = function ParsleyValidatorRegistry(validators, catalog) { this.__class__ = 'ParsleyValidatorRegistry'; // Default Parsley locale is en this.locale = 'en'; this.init(validators || {}, catalog || {}); }; var typeRegexes = { email: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i, // Follow https://www.w3.org/TR/html5/infrastructure.html#floating-point-numbers number: /^-?(\d*\.)?\d+(e[-+]?\d+)?$/i, integer: /^-?\d+$/, digits: /^\d+$/, alphanum: /^\w+$/i, url: new RegExp("^" + // protocol identifier "(?:(?:https?|ftp)://)?" + // ** mod: make scheme optional // user:pass authentication "(?:\\S+(?::\\S*)?@)?" + "(?:" + // IP address exclusion // private & local networks // "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + // ** mod: allow local networks // "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks // "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks // IP address dotted notation octets // excludes loopback network 0.0.0.0 // excludes reserved space >= 224.0.0.0 // excludes network & broacast addresses // (first & last IP address of each class) "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + // host name '(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' + // domain name '(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' + // TLD identifier '(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))' + ")" + // port number "(?::\\d{2,5})?" + // resource path "(?:/\\S*)?" + "$", 'i') }; typeRegexes.range = typeRegexes.number; // See http://stackoverflow.com/a/10454560/8279 var decimalPlaces = function decimalPlaces(num) { var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); if (!match) { return 0; } return Math.max(0, // Number of digits right of decimal point. (match[1] ? match[1].length : 0) - ( // Adjust for scientific notation. match[2] ? +match[2] : 0)); }; ParsleyValidatorRegistry.prototype = { init: function init(validators, catalog) { this.catalog = catalog; // Copy prototype's validators: this.validators = $.extend({}, this.validators); for (var name in validators) this.addValidator(name, validators[name].fn, validators[name].priority); window.Parsley.trigger('parsley:validator:init'); }, // Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n setLocale: function setLocale(locale) { if ('undefined' === typeof this.catalog[locale]) throw new Error(locale + ' is not available in the catalog'); this.locale = locale; return this; }, // Add a new messages catalog for a given locale. Set locale for this catalog if set === `true` addCatalog: function addCatalog(locale, messages, set) { if ('object' === typeof messages) this.catalog[locale] = messages; if (true === set) return this.setLocale(locale); return this; }, // Add a specific message for a given constraint in a given locale addMessage: function addMessage(locale, name, message) { if ('undefined' === typeof this.catalog[locale]) this.catalog[locale] = {}; this.catalog[locale][name] = message; return this; }, // Add messages for a given locale addMessages: function addMessages(locale, nameMessageObject) { for (var name in nameMessageObject) this.addMessage(locale, name, nameMessageObject[name]); return this; }, // Add a new validator // // addValidator('custom', { // requirementType: ['integer', 'integer'], // validateString: function(value, from, to) {}, // priority: 22, // messages: { // en: "Hey, that's no good", // fr: "Aye aye, pas bon du tout", // } // }) // // Old API was addValidator(name, function, priority) // addValidator: function addValidator(name, arg1, arg2) { if (this.validators[name]) ParsleyUtils__default.warn('Validator "' + name + '" is already defined.');else if (ParsleyDefaults.hasOwnProperty(name)) { ParsleyUtils__default.warn('"' + name + '" is a restricted keyword and is not a valid validator name.'); return; } return this._setValidator.apply(this, arguments); }, updateValidator: function updateValidator(name, arg1, arg2) { if (!this.validators[name]) { ParsleyUtils__default.warn('Validator "' + name + '" is not already defined.'); return this.addValidator.apply(this, arguments); } return this._setValidator.apply(this, arguments); }, removeValidator: function removeValidator(name) { if (!this.validators[name]) ParsleyUtils__default.warn('Validator "' + name + '" is not defined.'); delete this.validators[name]; return this; }, _setValidator: function _setValidator(name, validator, priority) { if ('object' !== typeof validator) { // Old style validator, with `fn` and `priority` validator = { fn: validator, priority: priority }; } if (!validator.validate) { validator = new ParsleyValidator(validator); } this.validators[name] = validator; for (var locale in validator.messages || {}) this.addMessage(locale, name, validator.messages[locale]); return this; }, getErrorMessage: function getErrorMessage(constraint) { var message; // Type constraints are a bit different, we have to match their requirements too to find right error message if ('type' === constraint.name) { var typeMessages = this.catalog[this.locale][constraint.name] || {}; message = typeMessages[constraint.requirements]; } else message = this.formatMessage(this.catalog[this.locale][constraint.name], constraint.requirements); return message || this.catalog[this.locale].defaultMessage || this.catalog.en.defaultMessage; }, // Kind of light `sprintf()` implementation formatMessage: function formatMessage(string, parameters) { if ('object' === typeof parameters) { for (var i in parameters) string = this.formatMessage(string, parameters[i]); return string; } return 'string' === typeof string ? string.replace(/%s/i, parameters) : ''; }, // Here is the Parsley default validators list. // A validator is an object with the following key values: // - priority: an integer // - requirement: 'string' (default), 'integer', 'number', 'regexp' or an Array of these // - validateString, validateMultiple, validateNumber: functions returning `true`, `false` or a promise // Alternatively, a validator can be a function that returns such an object // validators: { notblank: { validateString: function validateString(value) { return (/\S/.test(value) ); }, priority: 2 }, required: { validateMultiple: function validateMultiple(values) { return values.length > 0; }, validateString: function validateString(value) { return (/\S/.test(value) ); }, priority: 512 }, type: { validateString: function validateString(value, type) { var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var _ref$step = _ref.step; var step = _ref$step === undefined ? '1' : _ref$step; var _ref$base = _ref.base; var base = _ref$base === undefined ? 0 : _ref$base; var regex = typeRegexes[type]; if (!regex) { throw new Error('validator type `' + type + '` is not supported'); } if (!regex.test(value)) return false; if ('number' === type) { if (!/^any$/i.test(step || '')) { var nb = Number(value); var decimals = Math.max(decimalPlaces(step), decimalPlaces(base)); if (decimalPlaces(nb) > decimals) // Value can't have too many decimals return false; // Be careful of rounding errors by using integers. var toInt = function toInt(f) { return Math.round(f * Math.pow(10, decimals)); }; if ((toInt(nb) - toInt(base)) % toInt(step) != 0) return false; } } return true; }, requirementType: { '': 'string', step: 'string', base: 'number' }, priority: 256 }, pattern: { validateString: function validateString(value, regexp) { return regexp.test(value); }, requirementType: 'regexp', priority: 64 }, minlength: { validateString: function validateString(value, requirement) { return value.length >= requirement; }, requirementType: 'integer', priority: 30 }, maxlength: { validateString: function validateString(value, requirement) { return value.length <= requirement; }, requirementType: 'integer', priority: 30 }, length: { validateString: function validateString(value, min, max) { return value.length >= min && value.length <= max; }, requirementType: ['integer', 'integer'], priority: 30 }, mincheck: { validateMultiple: function validateMultiple(values, requirement) { return values.length >= requirement; }, requirementType: 'integer', priority: 30 }, maxcheck: { validateMultiple: function validateMultiple(values, requirement) { return values.length <= requirement; }, requirementType: 'integer', priority: 30 }, check: { validateMultiple: function validateMultiple(values, min, max) { return values.length >= min && values.length <= max; }, requirementType: ['integer', 'integer'], priority: 30 }, min: { validateNumber: function validateNumber(value, requirement) { return value >= requirement; }, requirementType: 'number', priority: 30 }, max: { validateNumber: function validateNumber(value, requirement) { return value <= requirement; }, requirementType: 'number', priority: 30 }, range: { validateNumber: function validateNumber(value, min, max) { return value >= min && value <= max; }, requirementType: ['number', 'number'], priority: 30 }, equalto: { validateString: function validateString(value, refOrValue) { var $reference = $(refOrValue); if ($reference.length) return value === $reference.val();else return value === refOrValue; }, priority: 256 } } }; var ParsleyUI = {}; var diffResults = function diffResults(newResult, oldResult, deep) { var added = []; var kept = []; for (var i = 0; i < newResult.length; i++) { var found = false; for (var j = 0; j < oldResult.length; j++) if (newResult[i].assert.name === oldResult[j].assert.name) { found = true; break; } if (found) kept.push(newResult[i]);else added.push(newResult[i]); } return { kept: kept, added: added, removed: !deep ? diffResults(oldResult, newResult, true).added : [] }; }; ParsleyUI.Form = { _actualizeTriggers: function _actualizeTriggers() { var _this2 = this; this.$element.on('submit.Parsley', function (evt) { _this2.onSubmitValidate(evt); }); this.$element.on('click.Parsley', 'input[type="submit"], button[type="submit"]', function (evt) { _this2.onSubmitButton(evt); }); // UI could be disabled if (false === this.options.uiEnabled) return; this.$element.attr('novalidate', ''); }, focus: function focus() { this._focusedField = null; if (true === this.validationResult || 'none' === this.options.focus) return null; for (var i = 0; i < this.fields.length; i++) { var field = this.fields[i]; if (true !== field.validationResult && field.validationResult.length > 0 && 'undefined' === typeof field.options.noFocus) { this._focusedField = field.$element; if ('first' === this.options.focus) break; } } if (null === this._focusedField) return null; return this._focusedField.focus(); }, _destroyUI: function _destroyUI() { // Reset all event listeners this.$element.off('.Parsley'); } }; ParsleyUI.Field = { _reflowUI: function _reflowUI() { this._buildUI(); // If this field doesn't have an active UI don't bother doing something if (!this._ui) return; // Diff between two validation results var diff = diffResults(this.validationResult, this._ui.lastValidationResult); // Then store current validation result for next reflow this._ui.lastValidationResult = this.validationResult; // Handle valid / invalid / none field class this._manageStatusClass(); // Add, remove, updated errors messages this._manageErrorsMessages(diff); // Triggers impl this._actualizeTriggers(); // If field is not valid for the first time, bind keyup trigger to ease UX and quickly inform user if ((diff.kept.length || diff.added.length) && !this._failedOnce) { this._failedOnce = true; this._actualizeTriggers(); } }, // Returns an array of field's error message(s) getErrorsMessages: function getErrorsMessages() { // No error message, field is valid if (true === this.validationResult) return []; var messages = []; for (var i = 0; i < this.validationResult.length; i++) messages.push(this.validationResult[i].errorMessage || this._getErrorMessage(this.validationResult[i].assert)); return messages; }, // It's a goal of Parsley that this method is no longer required [#1073] addError: function addError(name) { var _ref2 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var message = _ref2.message; var assert = _ref2.assert; var _ref2$updateClass = _ref2.updateClass; var updateClass = _ref2$updateClass === undefined ? true : _ref2$updateClass; this._buildUI(); this._addError(name, { message: message, assert: assert }); if (updateClass) this._errorClass(); }, // It's a goal of Parsley that this method is no longer required [#1073] updateError: function updateError(name) { var _ref3 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var message = _ref3.message; var assert = _ref3.assert; var _ref3$updateClass = _ref3.updateClass; var updateClass = _ref3$updateClass === undefined ? true : _ref3$updateClass; this._buildUI(); this._updateError(name, { message: message, assert: assert }); if (updateClass) this._errorClass(); }, // It's a goal of Parsley that this method is no longer required [#1073] removeError: function removeError(name) { var _ref4 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _ref4$updateClass = _ref4.updateClass; var updateClass = _ref4$updateClass === undefined ? true : _ref4$updateClass; this._buildUI(); this._removeError(name); // edge case possible here: remove a standard Parsley error that is still failing in this.validationResult // but highly improbable cuz' manually removing a well Parsley handled error makes no sense. if (updateClass) this._manageStatusClass(); }, _manageStatusClass: function _manageStatusClass() { if (this.hasConstraints() && this.needsValidation() && true === this.validationResult) this._successClass();else if (this.validationResult.length > 0) this._errorClass();else this._resetClass(); }, _manageErrorsMessages: function _manageErrorsMessages(diff) { if ('undefined' !== typeof this.options.errorsMessagesDisabled) return; // Case where we have errorMessage option that configure an unique field error message, regardless failing validators if ('undefined' !== typeof this.options.errorMessage) { if (diff.added.length || diff.kept.length) { this._insertErrorWrapper(); if (0 === this._ui.$errorsWrapper.find('.parsley-custom-error-message').length) this._ui.$errorsWrapper.append($(this.options.errorTemplate).addClass('parsley-custom-error-message')); return this._ui.$errorsWrapper.addClass('filled').find('.parsley-custom-error-message').html(this.options.errorMessage); } return this._ui.$errorsWrapper.removeClass('filled').find('.parsley-custom-error-message').remove(); } // Show, hide, update failing constraints messages for (var i = 0; i < diff.removed.length; i++) this._removeError(diff.removed[i].assert.name); for (i = 0; i < diff.added.length; i++) this._addError(diff.added[i].assert.name, { message: diff.added[i].errorMessage, assert: diff.added[i].assert }); for (i = 0; i < diff.kept.length; i++) this._updateError(diff.kept[i].assert.name, { message: diff.kept[i].errorMessage, assert: diff.kept[i].assert }); }, _addError: function _addError(name, _ref5) { var message = _ref5.message; var assert = _ref5.assert; this._insertErrorWrapper(); this._ui.$errorsWrapper.addClass('filled').append($(this.options.errorTemplate).addClass('parsley-' + name).html(message || this._getErrorMessage(assert))); }, _updateError: function _updateError(name, _ref6) { var message = _ref6.message; var assert = _ref6.assert; this._ui.$errorsWrapper.addClass('filled').find('.parsley-' + name).html(message || this._getErrorMessage(assert)); }, _removeError: function _removeError(name) { this._ui.$errorsWrapper.removeClass('filled').find('.parsley-' + name).remove(); }, _getErrorMessage: function _getErrorMessage(constraint) { var customConstraintErrorMessage = constraint.name + 'Message'; if ('undefined' !== typeof this.options[customConstraintErrorMessage]) return window.Parsley.formatMessage(this.options[customConstraintErrorMessage], constraint.requirements); return window.Parsley.getErrorMessage(constraint); }, _buildUI: function _buildUI() { // UI could be already built or disabled if (this._ui || false === this.options.uiEnabled) return; var _ui = {}; // Give field its Parsley id in DOM this.$element.attr(this.options.namespace + 'id', this.__id__); /** Generate important UI elements and store them in this **/ // $errorClassHandler is the $element that woul have parsley-error and parsley-success classes _ui.$errorClassHandler = this._manageClassHandler(); // $errorsWrapper is a div that would contain the various field errors, it will be appended into $errorsContainer _ui.errorsWrapperId = 'parsley-id-' + (this.options.multiple ? 'multiple-' + this.options.multiple : this.__id__); _ui.$errorsWrapper = $(this.options.errorsWrapper).attr('id', _ui.errorsWrapperId); // ValidationResult UI storage to detect what have changed bwt two validations, and update DOM accordingly _ui.lastValidationResult = []; _ui.validationInformationVisible = false; // Store it in this for later this._ui = _ui; }, // Determine which element will have `parsley-error` and `parsley-success` classes _manageClassHandler: function _manageClassHandler() { // An element selector could be passed through DOM with `data-parsley-class-handler=#foo` if ('string' === typeof this.options.classHandler && $(this.options.classHandler).length) return $(this.options.classHandler); // Class handled could also be determined by function given in Parsley options var $handler = this.options.classHandler.call(this, this); // If this function returned a valid existing DOM element, go for it if ('undefined' !== typeof $handler && $handler.length) return $handler; // Otherwise, if simple element (input, texatrea, select...) it will perfectly host the classes if (!this.options.multiple || this.$element.is('select')) return this.$element; // But if multiple element (radio, checkbox), that would be their parent return this.$element.parent(); }, _insertErrorWrapper: function _insertErrorWrapper() { var $errorsContainer; // Nothing to do if already inserted if (0 !== this._ui.$errorsWrapper.parent().length) return this._ui.$errorsWrapper.parent(); if ('string' === typeof this.options.errorsContainer) { if ($(this.options.errorsContainer).length) return $(this.options.errorsContainer).append(this._ui.$errorsWrapper);else ParsleyUtils__default.warn('The errors container `' + this.options.errorsContainer + '` does not exist in DOM'); } else if ('function' === typeof this.options.errorsContainer) $errorsContainer = this.options.errorsContainer.call(this, this); if ('undefined' !== typeof $errorsContainer && $errorsContainer.length) return $errorsContainer.append(this._ui.$errorsWrapper); var $from = this.$element; if (this.options.multiple) $from = $from.parent(); return $from.after(this._ui.$errorsWrapper); }, _actualizeTriggers: function _actualizeTriggers() { var _this3 = this; var $toBind = this._findRelated(); var trigger; // Remove Parsley events already bound on this field $toBind.off('.Parsley'); if (this._failedOnce) $toBind.on(ParsleyUtils__default.namespaceEvents(this.options.triggerAfterFailure, 'Parsley'), function () { _this3.validate(); });else if (trigger = ParsleyUtils__default.namespaceEvents(this.options.trigger, 'Parsley')) { $toBind.on(trigger, function (event) { _this3._eventValidate(event); }); } }, _eventValidate: function _eventValidate(event) { // For keyup, keypress, keydown, input... events that could be a little bit obstrusive // do not validate if val length < min threshold on first validation. Once field have been validated once and info // about success or failure have been displayed, always validate with this trigger to reflect every yalidation change. if (/key|input/.test(event.type)) if (!(this._ui && this._ui.validationInformationVisible) && this.getValue().length <= this.options.validationThreshold) return; this.validate(); }, _resetUI: function _resetUI() { // Reset all event listeners this._failedOnce = false; this._actualizeTriggers(); // Nothing to do if UI never initialized for this field if ('undefined' === typeof this._ui) return; // Reset all errors' li this._ui.$errorsWrapper.removeClass('filled').children().remove(); // Reset validation class this._resetClass(); // Reset validation flags and last validation result this._ui.lastValidationResult = []; this._ui.validationInformationVisible = false; }, _destroyUI: function _destroyUI() { this._resetUI(); if ('undefined' !== typeof this._ui) this._ui.$errorsWrapper.remove(); delete this._ui; }, _successClass: function _successClass() { this._ui.validationInformationVisible = true; this._ui.$errorClassHandler.removeClass(this.options.errorClass).addClass(this.options.successClass); }, _errorClass: function _errorClass() { this._ui.validationInformationVisible = true; this._ui.$errorClassHandler.removeClass(this.options.successClass).addClass(this.options.errorClass); }, _resetClass: function _resetClass() { this._ui.$errorClassHandler.removeClass(this.options.successClass).removeClass(this.options.errorClass); } }; var ParsleyForm = function ParsleyForm(element, domOptions, options) { this.__class__ = 'ParsleyForm'; this.$element = $(element); this.domOptions = domOptions; this.options = options; this.parent = window.Parsley; this.fields = []; this.validationResult = null; }; var ParsleyForm__statusMapping = { pending: null, resolved: true, rejected: false }; ParsleyForm.prototype = { onSubmitValidate: function onSubmitValidate(event) { var _this4 = this; // This is a Parsley generated submit event, do not validate, do not prevent, simply exit and keep normal behavior if (true === event.parsley) return; // If we didn't come here through a submit button, use the first one in the form var $submitSource = this._$submitSource || this.$element.find('input[type="submit"], button[type="submit"]').first(); this._$submitSource = null; this.$element.find('.parsley-synthetic-submit-button').prop('disabled', true); if ($submitSource.is('[formnovalidate]')) return; var promise = this.whenValidate({ event: event }); if ('resolved' === promise.state() && false !== this._trigger('submit')) { // All good, let event go through. We make this distinction because browsers // differ in their handling of `submit` being called from inside a submit event [#1047] } else { // Rejected or pending: cancel this submit event.stopImmediatePropagation(); event.preventDefault(); if ('pending' === promise.state()) promise.done(function () { _this4._submit($submitSource); }); } }, onSubmitButton: function onSubmitButton(event) { this._$submitSource = $(event.target); }, // internal // _submit submits the form, this time without going through the validations. // Care must be taken to "fake" the actual submit button being clicked. _submit: function _submit($submitSource) { if (false === this._trigger('submit')) return; // Add submit button's data if ($submitSource) { var $synthetic = this.$element.find('.parsley-synthetic-submit-button').prop('disabled', false); if (0 === $synthetic.length) $synthetic = $('<input class="parsley-synthetic-submit-button" type="hidden">').appendTo(this.$element); $synthetic.attr({ name: $submitSource.attr('name'), value: $submitSource.attr('value') }); } this.$element.trigger($.extend($.Event('submit'), { parsley: true })); }, // Performs validation on fields while triggering events. // @returns `true` if all validations succeeds, `false` // if a failure is immediately detected, or `null` // if dependant on a promise. // Consider using `whenValidate` instead. validate: function validate(options) { if (arguments.length >= 1 && !$.isPlainObject(options)) { ParsleyUtils__default.warnOnce('Calling validate on a parsley form without passing arguments as an object is deprecated.'); var _arguments = _slice.call(arguments); var group = _arguments[0]; var force = _arguments[1]; var event = _arguments[2]; options = { group: group, force: force, event: event }; } return ParsleyForm__statusMapping[this.whenValidate(options).state()]; }, whenValidate: function whenValidate() { var _$$when$done$fail$always, _this5 = this; var _ref7 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var group = _ref7.group; var force = _ref7.force; var event = _ref7.event; this.submitEvent = event; if (event) { this.submitEvent = $.extend({}, event, { preventDefault: function preventDefault() { ParsleyUtils__default.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`"); _this5.validationResult = false; } }); } this.validationResult = true; // fire validate event to eventually modify things before very validation this._trigger('validate'); // Refresh form DOM options and form's fields that could have changed this._refreshFields(); var promises = this._withoutReactualizingFormOptions(function () { return $.map(_this5.fields, function (field) { return field.whenValidate({ force: force, group: group }); }); }); return (_$$when$done$fail$always = $.when.apply($, _toConsumableArray(promises)).done(function () { _this5._trigger('success'); }).fail(function () { _this5.validationResult = false; _this5.focus(); _this5._trigger('error'); }).always(function () { _this5._trigger('validated'); })).pipe.apply(_$$when$done$fail$always, _toConsumableArray(this._pipeAccordingToValidationResult())); }, // Iterate over refreshed fields, and stop on first failure. // Returns `true` if all fields are valid, `false` if a failure is detected // or `null` if the result depends on an unresolved promise. // Prefer using `whenValid` instead. isValid: function isValid(options) { if (arguments.length >= 1 && !$.isPlainObject(options)) { ParsleyUtils__default.warnOnce('Calling isValid on a parsley form without passing arguments as an object is deprecated.'); var _arguments2 = _slice.call(arguments); var group = _arguments2[0]; var force = _arguments2[1]; options = { group: group, force: force }; } return ParsleyForm__statusMapping[this.whenValid(options).state()]; }, // Iterate over refreshed fields and validate them. // Returns a promise. // A validation that immediately fails will interrupt the validations. whenValid: function whenValid() { var _this6 = this; var _ref8 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var group = _ref8.group; var force = _ref8.force; this._refreshFields(); var promises = this._withoutReactualizingFormOptions(function () { return $.map(_this6.fields, function (field) { return field.whenValid({ group: group, force: force }); }); }); return $.when.apply($, _toConsumableArray(promises)); }, _refreshFields: function _refreshFields() { return this.actualizeOptions()._bindFields(); }, _bindFields: function _bindFields() { var _this7 = this; var oldFields = this.fields; this.fields = []; this.fieldsMappedById = {}; this._withoutReactualizingFormOptions(function () { _this7.$element.find(_this7.options.inputs).not(_this7.options.excluded).each(function (_, element) { var fieldInstance = new window.Parsley.Factory(element, {}, _this7); // Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && true !== fieldInstance.options.excluded) if ('undefined' === typeof _this7.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) { _this7.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance; _this7.fields.push(fieldInstance); } }); $(oldFields).not(_this7.fields).each(function (_, field) { field._trigger('reset'); }); }); return this; }, // Internal only. // Looping on a form's fields to do validation or similar // will trigger reactualizing options on all of them, which // in turn will reactualize the form's options. // To avoid calling actualizeOptions so many times on the form // for nothing, _withoutReactualizingFormOptions temporarily disables // the method actualizeOptions on this form while `fn` is called. _withoutReactualizingFormOptions: function _withoutReactualizingFormOptions(fn) { var oldActualizeOptions = this.actualizeOptions; this.actualizeOptions = function () { return this; }; var result = fn(); this.actualizeOptions = oldActualizeOptions; return result; }, // Internal only. // Shortcut to trigger an event // Returns true iff event is not interrupted and default not prevented. _trigger: function _trigger(eventName) { return this.trigger('form:' + eventName); } }; var ConstraintFactory = function ConstraintFactory(parsleyField, name, requirements, priority, isDomConstraint) { if (!/ParsleyField/.test(parsleyField.__class__)) throw new Error('ParsleyField or ParsleyFieldMultiple instance expected'); var validatorSpec = window.Parsley._validatorRegistry.validators[name]; var validator = new ParsleyValidator(validatorSpec); $.extend(this, { validator: validator, name: name, requirements: requirements, priority: priority || parsleyField.options[name + 'Priority'] || validator.priority, isDomConstraint: true === isDomConstraint }); this._parseRequirements(parsleyField.options); }; var capitalize = function capitalize(str) { var cap = str[0].toUpperCase(); return cap + str.slice(1); }; ConstraintFactory.prototype = { validate: function validate(value, instance) { var _validator; return (_validator = this.validator).validate.apply(_validator, [value].concat(_toConsumableArray(this.requirementList), [instance])); }, _parseRequirements: function _parseRequirements(options) { var _this8 = this; this.requirementList = this.validator.parseRequirements(this.requirements, function (key) { return options[_this8.name + capitalize(key)]; }); } }; var ParsleyField = function ParsleyField(field, domOptions, options, parsleyFormInstance) { this.__class__ = 'ParsleyField'; this.$element = $(field); // Set parent if we have one if ('undefined' !== typeof parsleyFormInstance) { this.parent = parsleyFormInstance; } this.options = options; this.domOptions = domOptions; // Initialize some properties this.constraints = []; this.constraintsByName = {}; this.validationResult = true; // Bind constraints this._bindConstraints(); }; var parsley_field__statusMapping = { pending: null, resolved: true, rejected: false }; ParsleyField.prototype = { // # Public API // Validate field and trigger some events for mainly `ParsleyUI` // @returns `true`, an array of the validators that failed, or // `null` if validation is not finished. Prefer using whenValidate validate: function validate(options) { if (arguments.length >= 1 && !$.isPlainObject(options)) { ParsleyUtils__default.warnOnce('Calling validate on a parsley field without passing arguments as an object is deprecated.'); options = { options: options }; } var promise = this.whenValidate(options); if (!promise) // If excluded with `group` option return true; switch (promise.state()) { case 'pending': return null; case 'resolved': return true; case 'rejected': return this.validationResult; } }, // Validate field and trigger some events for mainly `ParsleyUI` // @returns a promise that succeeds only when all validations do // or `undefined` if field is not in the given `group`. whenValidate: function whenValidate() { var _whenValid$always$done$fail$always, _this9 = this; var _ref9 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var force = _ref9.force; var group = _ref9.group; // do not validate a field if not the same as given validation group this.refreshConstraints(); if (group && !this._isInGroup(group)) return; this.value = this.getValue(); // Field Validate event. `this.value` could be altered for custom needs this._trigger('validate'); return (_whenValid$always$done$fail$always = this.whenValid({ force: force, value: this.value, _refreshed: true }).always(function () { _this9._reflowUI(); }).done(function () { _this9._trigger('success'); }).fail(function () { _this9._trigger('error'); }).always(function () { _this9._trigger('validated'); })).pipe.apply(_whenValid$always$done$fail$always, _toConsumableArray(this._pipeAccordingToValidationResult())); }, hasConstraints: function hasConstraints() { return 0 !== this.constraints.length; }, // An empty optional field does not need validation needsValidation: function needsValidation(value) { if ('undefined' === typeof value) value = this.getValue(); // If a field is empty and not required, it is valid // Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators if (!value.length && !this._isRequired() && 'undefined' === typeof this.options.validateIfEmpty) return false; return true; }, _isInGroup: function _isInGroup(group) { if ($.isArray(this.options.group)) return -1 !== $.inArray(group, this.options.group); return this.options.group === group; }, // Just validate field. Do not trigger any event. // Returns `true` iff all constraints pass, `false` if there are failures, // or `null` if the result can not be determined yet (depends on a promise) // See also `whenValid`. isValid: function isValid(options) { if (arguments.length >= 1 && !$.isPlainObject(options)) { ParsleyUtils__default.warnOnce('Calling isValid on a parsley field without passing arguments as an object is deprecated.'); var _arguments3 = _slice.call(arguments); var force = _arguments3[0]; var value = _arguments3[1]; options = { force: force, value: value }; } var promise = this.whenValid(options); if (!promise) // Excluded via `group` return true; return parsley_field__statusMapping[promise.state()]; }, // Just validate field. Do not trigger any event. // @returns a promise that succeeds only when all validations do // or `undefined` if the field is not in the given `group`. // The argument `force` will force validation of empty fields. // If a `value` is given, it will be validated instead of the value of the input. whenValid: function whenValid() { var _this10 = this; var _ref10 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _ref10$force = _ref10.force; var force = _ref10$force === undefined ? false : _ref10$force; var value = _ref10.value; var group = _ref10.group; var _refreshed = _ref10._refreshed; // Recompute options and rebind constraints to have latest changes if (!_refreshed) this.refreshConstraints(); // do not validate a field if not the same as given validation group if (group && !this._isInGroup(group)) return; this.validationResult = true; // A field without constraint is valid if (!this.hasConstraints()) return $.when(); // Value could be passed as argument, needed to add more power to 'field:validate' if ('undefined' === typeof value || null === value) value = this.getValue(); if (!this.needsValidation(value) && true !== force) return $.when(); var groupedConstraints = this._getGroupedConstraints(); var promises = []; $.each(groupedConstraints, function (_, constraints) { // Process one group of constraints at a time, we validate the constraints // and combine the promises together. var promise = $.when.apply($, _toConsumableArray($.map(constraints, function (constraint) { return _this10._validateConstraint(value, constraint); }))); promises.push(promise); if (promise.state() === 'rejected') return false; // Interrupt processing if a group has already failed }); return $.when.apply($, promises); }, // @returns a promise _validateConstraint: function _validateConstraint(value, constraint) { var _this11 = this; var result = constraint.validate(value, this); // Map false to a failed promise if (false === result) result = $.Deferred().reject(); // Make sure we return a promise and that we record failures return $.when(result).fail(function (errorMessage) { if (!(_this11.validationResult instanceof Array)) _this11.validationResult = []; _this11.validationResult.push({ assert: constraint, errorMessage: 'string' === typeof errorMessage && errorMessage }); }); }, // @returns Parsley field computed value that could be overrided or configured in DOM getValue: function getValue() { var value; // Value could be overriden in DOM or with explicit options if ('function' === typeof this.options.value) value = this.options.value(this);else if ('undefined' !== typeof this.options.value) value = this.options.value;else value = this.$element.val(); // Handle wrong DOM or configurations if ('undefined' === typeof value || null === value) return ''; return this._handleWhitespace(value); }, // Actualize options that could have change since previous validation // Re-bind accordingly constraints (could be some new, removed or updated) refreshConstraints: function refreshConstraints() { return this.actualizeOptions()._bindConstraints(); }, /** * Add a new constraint to a field * * @param {String} name * @param {Mixed} requirements optional * @param {Number} priority optional * @param {Boolean} isDomConstraint optional */ addConstraint: function addConstraint(name, requirements, priority, isDomConstraint) { if (window.Parsley._validatorRegistry.validators[name]) { var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint); // if constraint already exist, delete it and push new version if ('undefined' !== this.constraintsByName[constraint.name]) this.removeConstraint(constraint.name); this.constraints.push(constraint); this.constraintsByName[constraint.name] = constraint; } return this; }, // Remove a constraint removeConstraint: function removeConstraint(name) { for (var i = 0; i < this.constraints.length; i++) if (name === this.constraints[i].name) { this.constraints.splice(i, 1); break; } delete this.constraintsByName[name]; return this; }, // Update a constraint (Remove + re-add) updateConstraint: function updateConstraint(name, parameters, priority) { return this.removeConstraint(name).addConstraint(name, parameters, priority); }, // # Internals // Internal only. // Bind constraints from config + options + DOM _bindConstraints: function _bindConstraints() { var constraints = []; var constraintsByName = {}; // clean all existing DOM constraints to only keep javascript user constraints for (var i = 0; i < this.constraints.length; i++) if (false === this.constraints[i].isDomConstraint) { constraints.push(this.constraints[i]); constraintsByName[this.constraints[i].name] = this.constraints[i]; } this.constraints = constraints; this.constraintsByName = constraintsByName; // then re-add Parsley DOM-API constraints for (var name in this.options) this.addConstraint(name, this.options[name], undefined, true); // finally, bind special HTML5 constraints return this._bindHtml5Constraints(); }, // Internal only. // Bind specific HTML5 constraints to be HTML5 compliant _bindHtml5Constraints: function _bindHtml5Constraints() { // html5 required if (this.$element.hasClass('required') || this.$element.attr('required')) this.addConstraint('required', true, undefined, true); // html5 pattern if ('string' === typeof this.$element.attr('pattern')) this.addConstraint('pattern', this.$element.attr('pattern'), undefined, true); // range if ('undefined' !== typeof this.$element.attr('min') && 'undefined' !== typeof this.$element.attr('max')) this.addConstraint('range', [this.$element.attr('min'), this.$element.attr('max')], undefined, true); // HTML5 min else if ('undefined' !== typeof this.$element.attr('min')) this.addConstraint('min', this.$element.attr('min'), undefined, true); // HTML5 max else if ('undefined' !== typeof this.$element.attr('max')) this.addConstraint('max', this.$element.attr('max'), undefined, true); // length if ('undefined' !== typeof this.$element.attr('minlength') && 'undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('length', [this.$element.attr('minlength'), this.$element.attr('maxlength')], undefined, true); // HTML5 minlength else if ('undefined' !== typeof this.$element.attr('minlength')) this.addConstraint('minlength', this.$element.attr('minlength'), undefined, true); // HTML5 maxlength else if ('undefined' !== typeof this.$element.attr('maxlength')) this.addConstraint('maxlength', this.$element.attr('maxlength'), undefined, true); // html5 types var type = this.$element.attr('type'); if ('undefined' === typeof type) return this; // Small special case here for HTML5 number: integer validator if step attribute is undefined or an integer value, number otherwise if ('number' === type) { return this.addConstraint('type', ['number', { step: this.$element.attr('step'), base: this.$element.attr('min') || this.$element.attr('value') }], undefined, true); // Regular other HTML5 supported types } else if (/^(email|url|range)$/i.test(type)) { return this.addConstraint('type', type, undefined, true); } return this; }, // Internal only. // Field is required if have required constraint without `false` value _isRequired: function _isRequired() { if ('undefined' === typeof this.constraintsByName.required) return false; return false !== this.constraintsByName.required.requirements; }, // Internal only. // Shortcut to trigger an event _trigger: function _trigger(eventName) { return this.trigger('field:' + eventName); }, // Internal only // Handles whitespace in a value // Use `data-parsley-whitespace="squish"` to auto squish input value // Use `data-parsley-whitespace="trim"` to auto trim input value _handleWhitespace: function _handleWhitespace(value) { if (true === this.options.trimValue) ParsleyUtils__default.warnOnce('data-parsley-trim-value="true" is deprecated, please use data-parsley-whitespace="trim"'); if ('squish' === this.options.whitespace) value = value.replace(/\s{2,}/g, ' '); if ('trim' === this.options.whitespace || 'squish' === this.options.whitespace || true === this.options.trimValue) value = ParsleyUtils__default.trimString(value); return value; }, // Internal only. // Returns the constraints, grouped by descending priority. // The result is thus an array of arrays of constraints. _getGroupedConstraints: function _getGroupedConstraints() { if (false === this.options.priorityEnabled) return [this.constraints]; var groupedConstraints = []; var index = {}; // Create array unique of priorities for (var i = 0; i < this.constraints.length; i++) { var p = this.constraints[i].priority; if (!index[p]) groupedConstraints.push(index[p] = []); index[p].push(this.constraints[i]); } // Sort them by priority DESC groupedConstraints.sort(function (a, b) { return b[0].priority - a[0].priority; }); return groupedConstraints; } }; var parsley_field = ParsleyField; var ParsleyMultiple = function ParsleyMultiple() { this.__class__ = 'ParsleyFieldMultiple'; }; ParsleyMultiple.prototype = { // Add new `$element` sibling for multiple field addElement: function addElement($element) { this.$elements.push($element); return this; }, // See `ParsleyField.refreshConstraints()` refreshConstraints: function refreshConstraints() { var fieldConstraints; this.constraints = []; // Select multiple special treatment if (this.$element.is('select')) { this.actualizeOptions()._bindConstraints(); return this; } // Gather all constraints for each input in the multiple group for (var i = 0; i < this.$elements.length; i++) { // Check if element have not been dynamically removed since last binding if (!$('html').has(this.$elements[i]).length) { this.$elements.splice(i, 1); continue; } fieldConstraints = this.$elements[i].data('ParsleyFieldMultiple').refreshConstraints().constraints; for (var j = 0; j < fieldConstraints.length; j++) this.addConstraint(fieldConstraints[j].name, fieldConstraints[j].requirements, fieldConstraints[j].priority, fieldConstraints[j].isDomConstraint); } return this; }, // See `ParsleyField.getValue()` getValue: function getValue() { // Value could be overriden in DOM if ('function' === typeof this.options.value) return this.options.value(this);else if ('undefined' !== typeof this.options.value) return this.options.value; // Radio input case if (this.$element.is('input[type=radio]')) return this._findRelated().filter(':checked').val() || ''; // checkbox input case if (this.$element.is('input[type=checkbox]')) { var values = []; this._findRelated().filter(':checked').each(function () { values.push($(this).val()); }); return values; } // Select multiple case if (this.$element.is('select') && null === this.$element.val()) return []; // Default case that should never happen return this.$element.val(); }, _init: function _init() { this.$elements = [this.$element]; return this; } }; var ParsleyFactory = function ParsleyFactory(element, options, parsleyFormInstance) { this.$element = $(element); // If the element has already been bound, returns its saved Parsley instance var savedparsleyFormInstance = this.$element.data('Parsley'); if (savedparsleyFormInstance) { // If the saved instance has been bound without a ParsleyForm parent and there is one given in this call, add it if ('undefined' !== typeof parsleyFormInstance && savedparsleyFormInstance.parent === window.Parsley) { savedparsleyFormInstance.parent = parsleyFormInstance; savedparsleyFormInstance._resetOptions(savedparsleyFormInstance.options); } return savedparsleyFormInstance; } // Parsley must be instantiated with a DOM element or jQuery $element if (!this.$element.length) throw new Error('You must bind Parsley on an existing element.'); if ('undefined' !== typeof parsleyFormInstance && 'ParsleyForm' !== parsleyFormInstance.__class__) throw new Error('Parent instance must be a ParsleyForm instance'); this.parent = parsleyFormInstance || window.Parsley; return this.init(options); }; ParsleyFactory.prototype = { init: function init(options) { this.__class__ = 'Parsley'; this.__version__ = '2.3.13'; this.__id__ = ParsleyUtils__default.generateID(); // Pre-compute options this._resetOptions(options); // A ParsleyForm instance is obviously a `<form>` element but also every node that is not an input and has the `data-parsley-validate` attribute if (this.$element.is('form') || ParsleyUtils__default.checkAttr(this.$element, this.options.namespace, 'validate') && !this.$element.is(this.options.inputs)) return this.bind('parsleyForm'); // Every other element is bound as a `ParsleyField` or `ParsleyFieldMultiple` return this.isMultiple() ? this.handleMultiple() : this.bind('parsleyField'); }, isMultiple: function isMultiple() { return this.$element.is('input[type=radio], input[type=checkbox]') || this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple'); }, // Multiples fields are a real nightmare :( // Maybe some refactoring would be appreciated here... handleMultiple: function handleMultiple() { var _this12 = this; var name; var multiple; var parsleyMultipleInstance; // Handle multiple name if (this.options.multiple) ; // We already have our 'multiple' identifier else if ('undefined' !== typeof this.$element.attr('name') && this.$element.attr('name').length) this.options.multiple = name = this.$element.attr('name');else if ('undefined' !== typeof this.$element.attr('id') && this.$element.attr('id').length) this.options.multiple = this.$element.attr('id'); // Special select multiple input if (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')) { this.options.multiple = this.options.multiple || this.__id__; return this.bind('parsleyFieldMultiple'); // Else for radio / checkboxes, we need a `name` or `data-parsley-multiple` to properly bind it } else if (!this.options.multiple) { ParsleyUtils__default.warn('To be bound by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.', this.$element); return this; } // Remove special chars this.options.multiple = this.options.multiple.replace(/(:|\.|\[|\]|\{|\}|\$)/g, ''); // Add proper `data-parsley-multiple` to siblings if we have a valid multiple name if ('undefined' !== typeof name) { $('input[name="' + name + '"]').each(function (i, input) { if ($(input).is('input[type=radio], input[type=checkbox]')) $(input).attr(_this12.options.namespace + 'multiple', _this12.options.multiple); }); } // Check here if we don't already have a related multiple instance saved var $previouslyRelated = this._findRelated(); for (var i = 0; i < $previouslyRelated.length; i++) { parsleyMultipleInstance = $($previouslyRelated.get(i)).data('Parsley'); if ('undefined' !== typeof parsleyMultipleInstance) { if (!this.$element.data('ParsleyFieldMultiple')) { parsleyMultipleInstance.addElement(this.$element); } break; } } // Create a secret ParsleyField instance for every multiple field. It will be stored in `data('ParsleyFieldMultiple')` // And will be useful later to access classic `ParsleyField` stuff while being in a `ParsleyFieldMultiple` instance this.bind('parsleyField', true); return parsleyMultipleInstance || this.bind('parsleyFieldMultiple'); }, // Return proper `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple` bind: function bind(type, doNotStore) { var parsleyInstance; switch (type) { case 'parsleyForm': parsleyInstance = $.extend(new ParsleyForm(this.$element, this.domOptions, this.options), new ParsleyAbstract(), window.ParsleyExtend)._bindFields(); break; case 'parsleyField': parsleyInstance = $.extend(new parsley_field(this.$element, this.domOptions, this.options, this.parent), new ParsleyAbstract(), window.ParsleyExtend); break; case 'parsleyFieldMultiple': parsleyInstance = $.extend(new parsley_field(this.$element, this.domOptions, this.options, this.parent), new ParsleyMultiple(), new ParsleyAbstract(), window.ParsleyExtend)._init(); break; default: throw new Error(type + 'is not a supported Parsley type'); } if (this.options.multiple) ParsleyUtils__default.setAttr(this.$element, this.options.namespace, 'multiple', this.options.multiple); if ('undefined' !== typeof doNotStore) { this.$element.data('ParsleyFieldMultiple', parsleyInstance); return parsleyInstance; } // Store the freshly bound instance in a DOM element for later access using jQuery `data()` this.$element.data('Parsley', parsleyInstance); // Tell the world we have a new ParsleyForm or ParsleyField instance! parsleyInstance._actualizeTriggers(); parsleyInstance._trigger('init'); return parsleyInstance; } }; var vernums = $.fn.jquery.split('.'); if (parseInt(vernums[0]) <= 1 && parseInt(vernums[1]) < 8) { throw "The loaded version of jQuery is too old. Please upgrade to 1.8.x or better."; } if (!vernums.forEach) { ParsleyUtils__default.warn('Parsley requires ES5 to run properly. Please include https://github.com/es-shims/es5-shim'); } // Inherit `on`, `off` & `trigger` to Parsley: var Parsley = $.extend(new ParsleyAbstract(), { $element: $(document), actualizeOptions: null, _resetOptions: null, Factory: ParsleyFactory, version: '2.3.13' }); // Supplement ParsleyField and Form with ParsleyAbstract // This way, the constructors will have access to those methods $.extend(parsley_field.prototype, ParsleyUI.Field, ParsleyAbstract.prototype); $.extend(ParsleyForm.prototype, ParsleyUI.Form, ParsleyAbstract.prototype); // Inherit actualizeOptions and _resetOptions: $.extend(ParsleyFactory.prototype, ParsleyAbstract.prototype); // ### jQuery API // `$('.elem').parsley(options)` or `$('.elem').psly(options)` $.fn.parsley = $.fn.psly = function (options) { if (this.length > 1) { var instances = []; this.each(function () { instances.push($(this).parsley(options)); }); return instances; } // Return undefined if applied to non existing DOM element if (!$(this).length) { ParsleyUtils__default.warn('You must bind Parsley on an existing element.'); return; } return new ParsleyFactory(this, options); }; // ### ParsleyField and ParsleyForm extension // Ensure the extension is now defined if it wasn't previously if ('undefined' === typeof window.ParsleyExtend) window.ParsleyExtend = {}; // ### Parsley config // Inherit from ParsleyDefault, and copy over any existing values Parsley.options = $.extend(ParsleyUtils__default.objectCreate(ParsleyDefaults), window.ParsleyConfig); window.ParsleyConfig = Parsley.options; // Old way of accessing global options // ### Globals window.Parsley = window.psly = Parsley; window.ParsleyUtils = ParsleyUtils__default; // ### Define methods that forward to the registry, and deprecate all access except through window.Parsley var registry = window.Parsley._validatorRegistry = new ParsleyValidatorRegistry(window.ParsleyConfig.validators, window.ParsleyConfig.i18n); window.ParsleyValidator = {}; $.each('setLocale addCatalog addMessage addMessages getErrorMessage formatMessage addValidator updateValidator removeValidator'.split(' '), function (i, method) { window.Parsley[method] = $.proxy(registry, method); window.ParsleyValidator[method] = function () { var _window$Parsley; ParsleyUtils__default.warnOnce('Accessing the method \'' + method + '\' through ParsleyValidator is deprecated. Simply call \'window.Parsley.' + method + '(...)\''); return (_window$Parsley = window.Parsley)[method].apply(_window$Parsley, arguments); }; }); // ### ParsleyUI // Deprecated global object window.Parsley.UI = ParsleyUI; window.ParsleyUI = { removeError: function removeError(instance, name, doNotUpdateClass) { var updateClass = true !== doNotUpdateClass; ParsleyUtils__default.warnOnce('Accessing ParsleyUI is deprecated. Call \'removeError\' on the instance directly. Please comment in issue 1073 as to your need to call this method.'); return instance.removeError(name, { updateClass: updateClass }); }, getErrorsMessages: function getErrorsMessages(instance) { ParsleyUtils__default.warnOnce('Accessing ParsleyUI is deprecated. Call \'getErrorsMessages\' on the instance directly.'); return instance.getErrorsMessages(); } }; $.each('addError updateError'.split(' '), function (i, method) { window.ParsleyUI[method] = function (instance, name, message, assert, doNotUpdateClass) { var updateClass = true !== doNotUpdateClass; ParsleyUtils__default.warnOnce('Accessing ParsleyUI is deprecated. Call \'' + method + '\' on the instance directly. Please comment in issue 1073 as to your need to call this method.'); return instance[method](name, { message: message, assert: assert, updateClass: updateClass }); }; }); // ### PARSLEY auto-binding // Prevent it by setting `ParsleyConfig.autoBind` to `false` if (false !== window.ParsleyConfig.autoBind) { $(function () { // Works only on `data-parsley-validate`. if ($('[data-parsley-validate]').length) $('[data-parsley-validate]').parsley(); }); } var o = $({}); var deprecated = function deprecated() { ParsleyUtils__default.warnOnce("Parsley's pubsub module is deprecated; use the 'on' and 'off' methods on parsley instances or window.Parsley"); }; // Returns an event handler that calls `fn` with the arguments it expects function adapt(fn, context) { // Store to allow unbinding if (!fn.parsleyAdaptedCallback) { fn.parsleyAdaptedCallback = function () { var args = Array.prototype.slice.call(arguments, 0); args.unshift(this); fn.apply(context || o, args); }; } return fn.parsleyAdaptedCallback; } var eventPrefix = 'parsley:'; // Converts 'parsley:form:validate' into 'form:validate' function eventName(name) { if (name.lastIndexOf(eventPrefix, 0) === 0) return name.substr(eventPrefix.length); return name; } // $.listen is deprecated. Use Parsley.on instead. $.listen = function (name, callback) { var context; deprecated(); if ('object' === typeof arguments[1] && 'function' === typeof arguments[2]) { context = arguments[1]; callback = arguments[2]; } if ('function' !== typeof callback) throw new Error('Wrong parameters'); window.Parsley.on(eventName(name), adapt(callback, context)); }; $.listenTo = function (instance, name, fn) { deprecated(); if (!(instance instanceof parsley_field) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance'); if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong parameters'); instance.on(eventName(name), adapt(fn)); }; $.unsubscribe = function (name, fn) { deprecated(); if ('string' !== typeof name || 'function' !== typeof fn) throw new Error('Wrong arguments'); window.Parsley.off(eventName(name), fn.parsleyAdaptedCallback); }; $.unsubscribeTo = function (instance, name) { deprecated(); if (!(instance instanceof parsley_field) && !(instance instanceof ParsleyForm)) throw new Error('Must give Parsley instance'); instance.off(eventName(name)); }; $.unsubscribeAll = function (name) { deprecated(); window.Parsley.off(eventName(name)); $('form,input,textarea,select').each(function () { var instance = $(this).data('Parsley'); if (instance) { instance.off(eventName(name)); } }); }; // $.emit is deprecated. Use jQuery events instead. $.emit = function (name, instance) { var _instance; deprecated(); var instanceGiven = instance instanceof parsley_field || instance instanceof ParsleyForm; var args = Array.prototype.slice.call(arguments, instanceGiven ? 2 : 1); args.unshift(eventName(name)); if (!instanceGiven) { instance = window.Parsley; } (_instance = instance).trigger.apply(_instance, _toConsumableArray(args)); }; var pubsub = {}; $.extend(true, Parsley, { asyncValidators: { 'default': { fn: function fn(xhr) { // By default, only status 2xx are deemed successful. // Note: we use status instead of state() because responses with status 200 // but invalid messages (e.g. an empty body for content type set to JSON) will // result in state() === 'rejected'. return xhr.status >= 200 && xhr.status < 300; }, url: false }, reverse: { fn: function fn(xhr) { // If reverse option is set, a failing ajax request is considered successful return xhr.status < 200 || xhr.status >= 300; }, url: false } }, addAsyncValidator: function addAsyncValidator(name, fn, url, options) { Parsley.asyncValidators[name] = { fn: fn, url: url || false, options: options || {} }; return this; } }); Parsley.addValidator('remote', { requirementType: { '': 'string', 'validator': 'string', 'reverse': 'boolean', 'options': 'object' }, validateString: function validateString(value, url, options, instance) { var data = {}; var ajaxOptions; var csr; var validator = options.validator || (true === options.reverse ? 'reverse' : 'default'); if ('undefined' === typeof Parsley.asyncValidators[validator]) throw new Error('Calling an undefined async validator: `' + validator + '`'); url = Parsley.asyncValidators[validator].url || url; // Fill current value if (url.indexOf('{value}') > -1) { url = url.replace('{value}', encodeURIComponent(value)); } else { data[instance.$element.attr('name') || instance.$element.attr('id')] = value; } // Merge options passed in from the function with the ones in the attribute var remoteOptions = $.extend(true, options.options || {}, Parsley.asyncValidators[validator].options); // All `$.ajax(options)` could be overridden or extended directly from DOM in `data-parsley-remote-options` ajaxOptions = $.extend(true, {}, { url: url, data: data, type: 'GET' }, remoteOptions); // Generate store key based on ajax options instance.trigger('field:ajaxoptions', instance, ajaxOptions); csr = $.param(ajaxOptions); // Initialise querry cache if ('undefined' === typeof Parsley._remoteCache) Parsley._remoteCache = {}; // Try to retrieve stored xhr var xhr = Parsley._remoteCache[csr] = Parsley._remoteCache[csr] || $.ajax(ajaxOptions); var handleXhr = function handleXhr() { var result = Parsley.asyncValidators[validator].fn.call(instance, xhr, url, options); if (!result) // Map falsy results to rejected promise result = $.Deferred().reject(); return $.when(result); }; return xhr.then(handleXhr, handleXhr); }, priority: -1 }); Parsley.on('form:submit', function () { Parsley._remoteCache = {}; }); window.ParsleyExtend.addAsyncValidator = function () { ParsleyUtils.warnOnce('Accessing the method `addAsyncValidator` through an instance is deprecated. Simply call `Parsley.addAsyncValidator(...)`'); return Parsley.addAsyncValidator.apply(Parsley, arguments); }; // This is included with the Parsley library itself, // thus there is no use in adding it to your project. Parsley.addMessages('en', { defaultMessage: "This value seems to be invalid.", type: { email: "This value should be a valid email.", url: "This value should be a valid url.", number: "This value should be a valid number.", integer: "This value should be a valid integer.", digits: "This value should be digits.", alphanum: "This value should be alphanumeric." }, notblank: "This value should not be blank.", required: "This value is required.", pattern: "This value seems to be invalid.", min: "This value should be greater than or equal to %s.", max: "This value should be lower than or equal to %s.", range: "This value should be between %s and %s.", minlength: "This value is too short. It should have %s characters or more.", maxlength: "This value is too long. It should have %s characters or fewer.", length: "This value length is invalid. It should be between %s and %s characters long.", mincheck: "You must select at least %s choices.", maxcheck: "You must select %s choices or fewer.", check: "You must select between %s and %s choices.", equalto: "This value should be the same." }); Parsley.setLocale('en'); /** * inputevent - Alleviate browser bugs for input events * https://github.com/marcandre/inputevent * @version v0.0.3 - (built Thu, Apr 14th 2016, 5:58 pm) * @author Marc-Andre Lafortune <github@marc-andre.ca> * @license MIT */ function InputEvent() { var _this13 = this; var globals = window || global; // Slightly odd way construct our object. This way methods are force bound. // Used to test for duplicate library. $.extend(this, { // For browsers that do not support isTrusted, assumes event is native. isNativeEvent: function isNativeEvent(evt) { return evt.originalEvent && evt.originalEvent.isTrusted !== false; }, fakeInputEvent: function fakeInputEvent(evt) { if (_this13.isNativeEvent(evt)) { $(evt.target).trigger('input'); } }, misbehaves: function misbehaves(evt) { if (_this13.isNativeEvent(evt)) { _this13.behavesOk(evt); $(document).on('change.inputevent', evt.data.selector, _this13.fakeInputEvent); _this13.fakeInputEvent(evt); } }, behavesOk: function behavesOk(evt) { if (_this13.isNativeEvent(evt)) { $(document) // Simply unbinds the testing handler .off('input.inputevent', evt.data.selector, _this13.behavesOk).off('change.inputevent', evt.data.selector, _this13.misbehaves); } }, // Bind the testing handlers install: function install() { if (globals.inputEventPatched) { return; } globals.inputEventPatched = '0.0.3'; var _arr = ['select', 'input[type="checkbox"]', 'input[type="radio"]', 'input[type="file"]']; for (var _i = 0; _i < _arr.length; _i++) { var selector = _arr[_i]; $(document).on('input.inputevent', selector, { selector: selector }, _this13.behavesOk).on('change.inputevent', selector, { selector: selector }, _this13.misbehaves); } }, uninstall: function uninstall() { delete globals.inputEventPatched; $(document).off('.inputevent'); } }); }; var inputevent = new InputEvent(); inputevent.install(); var parsley = Parsley; return parsley; }); //# sourceMappingURL=parsley.js.map
ajax/libs/foundation/4.0.5/js/vendor/jquery.js
mikelambert/cdnjs
/*! * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-2-4 */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<9 // For `typeof node.method` instead of `node.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.9.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) checkOn: !!input.value, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.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%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var i, l, thisCache, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return jQuery.access( this, function( value ) { if ( value === undefined ) { // Try to fetch any internally stored data first return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; } this.each(function() { jQuery.data( this, key, value ); }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, notxml, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if ( typeof elem.getAttribute !== core_strundefined ) { ret = elem.getAttribute( name ); } // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( rboolean.test( name ) ) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if ( !getSetAttribute && ruseDefault.test( name ) ) { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } else { elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, 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( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop( elem, name ), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute( name ), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test( name ) ? elem[ jQuery.camelCase( "default-" + name ) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode( name ); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return jQuery.nodeName( elem, "input" ) ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret == null ? undefined : ret; } }); }); // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); event.isTrigger = true; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur != this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent 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( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== document.activeElement && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === document.activeElement && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /^[^{]+\{\s*\[native code/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Use a stripped-down slice if we can't use a native one try { slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; while ( (elem = this[i++]) ) { results.push( elem ); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( !documentIsXML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsXML = isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; support.getIdNotName = !doc.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getIdNotName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.tagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { var compare; if ( a === b ) { hasDuplicate = true; return 0; } if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { if ( a === doc || contains( preferredDoc, a ) ) { return -1; } if ( b === doc || contains( preferredDoc, b ) ) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( !documentIsXML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( documentIsXML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; function siblingCheck( a, b ) { var cur = b && a, diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[4] ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifider if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.lang) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !documentIsXML && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, documentIsXML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret, self, len = this.length; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < len; i++ ) { jQuery.find( selector, this[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true) ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { 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>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent ) { jQuery( this ).remove(); parent.insertBefore( elem, next ); } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, table ? self.html() : undefined ); } self.domManip( args, table, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.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( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.hover = function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }; var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, 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" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 ) { isSuccess = true; statusText = "nocontent"; // if not modified } else if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data, let's convert it } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv2, current, conv, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var value, name, index, easing, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /*jshint validthis:true */ var prop, index, length, value, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); doAnimation.finish = function() { anim.stop( true ); }; // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.documentElement; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
pages/validation.js
bmagic/acdh-client
import React from 'react' import {withReduxSaga} from 'configureStore' import PropTypes from 'prop-types' import { connect } from 'react-redux' import Layout from 'components/Layout' import Meta from 'components/Meta' import Title from 'components/Title' import ValidationForm from 'components/ValidationForm' import {validate} from 'actions/user' class ValidationPage extends React.Component { constructor (props) { super(props) this.handleValidation = this.handleValidation.bind(this) } handleValidation (value) { this.props.onValidation(value) } static getInitialProps ({ query: { token } }) { return {token} } render () { return ( <Layout> <div id='register-page'> <Meta title='Validation' /> <Title title='Validation' subtitle='Entrez votre code de validation' /> <section className='section'> <div className='container has-text-centered'> <div className='columns is-centered'> <div className='is-half column'> <p className='content'> Vérifiez votre boite email pour récupérer le code d'activation </p> <ValidationForm initialValues={{token: this.props.token}} onSubmit={this.handleValidation} /> </div> </div> <hr /> <p className='content'> Un soucis avec l'inscription? N'hésitez pas à me contacter <a href='mailto:balomosa@protonmail.com'>balomosa@protonmail.com</a> </p> </div> </section> </div> </Layout> ) } } ValidationPage.propTypes = { token: PropTypes.string, onValidation: PropTypes.func } export function mapDispatchToProps (dispatch) { return { onValidation: (data) => { dispatch(validate(data)) } } } export default withReduxSaga(connect(null, mapDispatchToProps)(ValidationPage))
src/forms/Predictions.js
shp54/cliff-effects
import React from 'react'; import { Form, Divider, Header, Tab } from 'semantic-ui-react'; // PROJECT COMPONENTS import { FormPartsContainer, IntervalColumnHeadings, CashFlowRow } from './formHelpers'; import { GraphHolder } from './output/GraphHolder'; import { BenefitsTable } from './output/BenefitsTable'; import { StackedBarGraph } from './output/StackedBarGraph'; import { StackedAreaGraph } from './output/StackedAreaGraph'; import { BenefitsLineGraph } from './output/BenefitsLineGraph'; // COMPONENT HELPER FUNCTIONS import { getTimeSetter } from '../utils/getTimeSetter'; // ======================================== // COMPONENTS // ======================================== /** @todo description * * @function * @param {object} props Values described below * @property {object} props.future Client future/predictive data. * @property {string} props.time Used in class names. Meant to make * this more easily decoupled in future. * @property {function} props.setClientProperty Update client state * values. * * @returns {class} Component */ const IncomeForm = function ({ future, time, setClientProperty }) { var type = 'income'; /** * As per Project Hope input, for the first prototype we're only * including the ability to change earned income. */ return ( <div className='field-aligner two-column'> <IntervalColumnHeadings type={ type } /> <CashFlowRow timeState={ future } type={ type } time={ time } setClientProperty={ setClientProperty } generic='earned' labelInfo='(Weekly income = hourly wage times average number of work hours per week)'> How much money would you get paid in the future? (You can try different amounts) </CashFlowRow> </div> ); }; // End IncomeForm() Component const TabbedVisualizations = ({ client }) => { return ( // Benefit Courses, Tracks, Routes, Traces, Progressions, Progress, Trajectories, Changes <Tab menu={{ color: 'teal', attached: true, tabular: true }} panes={ [ { menuItem: 'Changes', render: () => {return <Tab.Pane><BenefitsTable client={ client } /></Tab.Pane>;} }, { menuItem: 'Changes Chart', render: () => {return <Tab.Pane><StackedBarGraph client={ client } /></Tab.Pane>;} }, { menuItem: 'Stacked Incomes', render: () => { return ( <Tab.Pane> <GraphHolder client={ client } Graph={ StackedAreaGraph } /> </Tab.Pane> ); }, }, { menuItem: 'Benefit Programs', render: () => { return ( <Tab.Pane> <GraphHolder client={ client } Graph={ BenefitsLineGraph } /> </Tab.Pane> ); }, }, ] } /> ); }; /** @todo Abstract all the step components? * * @function * @param {object} props See below. * @property {function} props.changeClient Updates state upstream. * @property {function} props.translate Uses user chosen language-specific * snippets. * @property {object} props.client JSON object with future and current values. * @property {function} props.nextStep Go to next form section. * @property {function} props.previousStep Go to previous form section. * * @returns {object} Component */ const PredictionsStep = function (props) { const setTimeProp = getTimeSetter('future', props.changeClient); /** @todo Are these titles accurate now? */ return ( <Form className = 'income-form flex-item flex-column'> <FormPartsContainer title = 'What Might Happen?' clarifier = { null } left = {{ name: 'Previous', func: props.previousStep }} right = {{ name: 'New Client', func: props.resetClient }}> <IncomeForm setClientProperty ={ setTimeProp } future ={ props.client.future } time ={ 'future' } /> <Divider className='ui section divider hidden' /> <Header as ='h3' className ='ui Header align centered'> With the new pay, how could your benefits change? </Header> <TabbedVisualizations client={ props.client } /> </FormPartsContainer> </Form> ); }; // End FutureIncomeStep() Component export { PredictionsStep };
core/static/admin/tests/layouts/CoreLayout.spec.js
tjcunliffe/hoverfly
import React from 'react' import TestUtils from 'react-addons-test-utils' import CoreLayout from 'layouts/CoreLayout/CoreLayout' function shallowRender (component) { const renderer = TestUtils.createRenderer() renderer.render(component) return renderer.getRenderOutput() } function shallowRenderWithProps (props = {}) { return shallowRender(<CoreLayout {...props} />) } describe('(Layout) Core', function () { let _component let _props let _child beforeEach(function () { _child = <h1 className='child'>Child</h1> _props = { children: _child } _component = shallowRenderWithProps(_props) }) it('Should render as a <div>.', function () { expect(_component.type).to.equal('div') }) })
react/src/base/inputs/SprkCheckbox/SprkCheckboxItem/SprkCheckboxItem.js
sparkdesignsystem/spark-design-system
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import uniqueId from 'lodash/uniqueId'; const SprkCheckboxItem = (props) => { const { children, variant, idString, additionalClasses, analyticsString, checkboxAdditionalClasses, labelAdditionalClasses, name, value, isDisabled, onChange, id, ariaDescribedBy, isVisibilityToggle, forwardedRef, ...rest } = props; const internalId = uniqueId('sprk-checkbox-'); const onChangeFunc = onChange; return ( <div className={classnames( 'sprk-b-SelectionContainer sprk-b-Checkbox', additionalClasses, { 'sprk-b-Checkbox--huge': variant === 'huge', 'sprk-b-InputContainer__visibility-toggle': isVisibilityToggle, }, )} data-analytics={analyticsString} data-id={idString} > <input aria-describedby={ariaDescribedBy} className={classnames( 'sprk-b-Checkbox__input', checkboxAdditionalClasses, )} data-id={idString} disabled={isDisabled} id={id || internalId} name={name} onChange={onChangeFunc} type="checkbox" value={value} ref={forwardedRef} {...rest} /> <label className={classnames( 'sprk-b-Label sprk-b-Label--inline sprk-b-Checkbox__label', labelAdditionalClasses, { 'sprk-b-Label--disabled': isDisabled, }, )} htmlFor={id || internalId} > {children} </label> </div> ); }; SprkCheckboxItem.propTypes = { children: PropTypes.node, /** * Determines the style of checkbox. * Supplying no value will cause the default styles to be used. */ variant: PropTypes.oneOf(['huge']), /** * Assigned to the `data-id` attribute serving as * a unique selector for automated tools. */ /** * Assigned to the `aria-describedby` * attribute. Used to create * relationships between the * component and text that describes it, * such as helper text or an error field. */ ariaDescribedBy: PropTypes.string, /** * Assigned to the `id` attribute of the input that will connect * relationships between the label and input. */ id: PropTypes.string, /** * Assigned to the `data-analytics` attribute * serving as a unique selector for outside libraries to capture data. */ analyticsString: PropTypes.string, /** * A space-separated string of classes * to add to the outermost container of the component. */ additionalClasses: PropTypes.string, /** * A space-separated string of classes * to add to the checkbox label of the component. */ labelAdditionalClasses: PropTypes.string, /** * A space-separated string of classes * to add to the checkbox input of the component. */ checkboxAdditionalClasses: PropTypes.string, /** * Text that appears below the input, * intended to provide more information to a user. */ helperText: PropTypes.string, /** * The error message that will display * while in its error state. */ errorMessage: PropTypes.string, /** * Assigned to the `name` attribute * of the rendered input element. */ name: PropTypes.string, /** * Assigned to the `value` attribute * of the rendered input element. */ value: PropTypes.string, /** * Will render the component in its disabled state. */ isDisabled: PropTypes.bool, /** * Passes in a function that handles the onChange of the input. */ onChange: PropTypes.func, /** * If `true`, the checkbox item will receive styling to make it a * visibility toggle. Use this for "Show Password" checkboxes. */ isVisibilityToggle: PropTypes.bool, /** * Assigned to the `data-id` attribute * serving as a unique selector for * automated tools. */ idString: PropTypes.string, /** * A ref passed in will be attached to the checkbox * element of the rendered component. */ forwardedRef: PropTypes.oneOfType([PropTypes.shape(), PropTypes.func]), }; export default SprkCheckboxItem;
src/status/NetworkTraffic.js
ipfs/webui
import React from 'react' import { connect } from 'redux-bundler-react' import { withTranslation } from 'react-i18next' import Speedometer from './Speedometer' import { Title } from './Commons' class NetworkTraffic extends React.Component { state = { downSpeed: { filled: 0, total: 125000 // Starts with 1 Mb/s max }, upSpeed: { filled: 0, total: 125000 // Starts with 1 Mb/s max } } componentDidUpdate (_, prevState) { const { nodeBandwidth } = this.props const down = nodeBandwidth ? parseInt(nodeBandwidth.rateIn.toFixed(0), 10) : 0 const up = nodeBandwidth ? parseInt(nodeBandwidth.rateOut.toFixed(0), 10) : 0 if (down !== prevState.downSpeed.filled || up !== prevState.upSpeed.filled) { this.setState({ downSpeed: { filled: down, total: Math.max(down, prevState.downSpeed.total) }, upSpeed: { filled: up, total: Math.max(up, prevState.upSpeed.total) } }) } } render () { const { t } = this.props const { downSpeed, upSpeed } = this.state return ( <div> <Title>{t('networkTraffic')}</Title> <div className='flex flex-column justify-between' style={{ maxWidth: 400 }}> <div className='mh2 mv3 mt0-l'> <Speedometer title={t('app:terms.downSpeed')} color='#69c4cd' {...downSpeed} /> </div> <div className='mh2 mt3 mt0-l'> <Speedometer title={t('app:terms.upSpeed')} color='#f39021' {...upSpeed} /> </div> </div> </div> ) } } export default connect( 'selectNodeBandwidth', withTranslation('status')(NetworkTraffic) )
src/components/Tooltip.js
destruc7i0n/crafting
import React from 'react' import './Tooltip.css' const Tooltip = ({ style, ingredient, title, hidden }) => { let data = 0 let hasData = ingredient.hasCustomData() if (hasData) { data = ingredient.getCustomData().data hasData = data !== undefined && !isNaN(data) } return !hidden ? ( <div className='mc-tooltip' style={{ display: style.display, top: style.y, left: style.x }} > <div className='mc-tooltip-title'> {title} </div> <div className='mc-tooltip-description'> {ingredient.id} {/* show the custom data as well for bedrock items */} {hasData ? ':' + data : ''} </div> </div> ) : null } export default Tooltip
packages/material-ui-icons/src/PhoneForwardedTwoTone.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M15.2 18.21c1.21.41 2.48.67 3.8.76v-1.5c-.88-.07-1.75-.22-2.6-.45l-1.2 1.19zM6.54 5h-1.5c.09 1.32.34 2.58.75 3.79l1.2-1.21c-.24-.83-.39-1.7-.45-2.58z" opacity=".3" /><path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.1-.03-.21-.05-.31-.05-.26 0-.51.1-.71.29l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM5.03 5h1.5c.07.88.22 1.75.45 2.58l-1.2 1.21c-.4-1.21-.66-2.47-.75-3.79zM19 18.97c-1.32-.09-2.6-.35-3.8-.76l1.2-1.2c.85.24 1.72.39 2.6.45v1.51zM18 11l5-5-5-5v3h-4v4h4z" /></React.Fragment> , 'PhoneForwardedTwoTone');
packages/react/src/Login.js
js-accounts/react
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import isString from 'lodash/isString'; import { Form, FormInput } from 'react-form'; class Login extends Component { static propTypes = { accounts: PropTypes.object, setFormType: PropTypes.func, Avatar: PropTypes.func, LoginFields: PropTypes.func, LoginUserField: PropTypes.func, LoginPasswordField: PropTypes.func, RecoverButton: PropTypes.func, LoginButton: PropTypes.func, SignupButton: PropTypes.func, Header: PropTypes.func, Footer: PropTypes.func, Container: PropTypes.func, Content: PropTypes.func, FormError: PropTypes.func, } static defaultProps = { Container: () => <div />, Header: () => <div />, Content: () => <div />, Footer: () => <div />, }; constructor(props, context) { super(props, context); this.state = { formError: '', }; } onSubmit = async (values) => { const { accounts } = this.props; this.setState({ formError: '', }); try { await accounts.loginWithPassword(values.user, values.password); } catch (err) { this.setState({ formError: err.message, }); } } validate = ({ user, password, }) => ({ user: !user ? 'Username or Email is required' : undefined, password: !password ? 'Password is required' : undefined, }) render() { const { Container, Content, Header, Footer, Avatar, LoginFields, LoginUserField, LoginPasswordField, LoginButton, RecoverButton, FormError, ...otherProps } = this.props; return ( <Container> <Header /> <Content {...otherProps}> <Avatar {...otherProps} /> <Form onSubmit={this.onSubmit} validate={this.validate} > {form => <LoginFields> <FormInput field="user" showErrors={false}> {() => <LoginUserField {...form} label="Username or email" value={form.getValue('user', '')} onChange={e => form.setValue('user', e.target.value)} errorText={form.getTouched('user') && isString(form.getError('user')) ? form.getError('user') : ''} /> } </FormInput> <FormInput field="password" showErrors={false}> {() => <LoginPasswordField {...form} label="Password" onChange={e => form.setValue('password', e.target.value)} value={form.getValue('password', '')} errorText={form.getTouched('password') && isString(form.getError('password')) ? form.getError('password') : ''} /> } </FormInput> <LoginButton label="Sign in" onClick={form.submitForm} {...otherProps} /> </LoginFields> } </Form> <RecoverButton {...otherProps} /> <FormError errorText={this.state.formError} /> </Content> <Footer /> </Container> ); } } export default Login;
packages/material-ui-icons/src/ThreeSixtySharp.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 7C6.48 7 2 9.24 2 12c0 2.24 2.94 4.13 7 4.77V20l4-4-4-4v2.73c-3.15-.56-5-1.9-5-2.73 0-1.06 3.04-3 8-3s8 1.94 8 3c0 .73-1.46 1.89-4 2.53v2.05c3.53-.77 6-2.53 6-4.58 0-2.76-4.48-5-10-5z" /> , 'ThreeSixtySharp');
services/ui/src/components/errors/EnvironmentNotFound.stories.js
amazeeio/lagoon
import React from 'react'; import EnvironmentNotFound from './EnvironmentNotFound'; export default { component: EnvironmentNotFound, title: 'Components/Errors/EnvironmentNotFound', } export const Default = () => ( <EnvironmentNotFound variables={{ openshiftProjectName: 'fortytwo-pr-42', }} /> );
src/components/text-field.demo.js
bhongy/react-components
// @flow import React from 'react'; import TextField from './text-field'; import type { EventHandler } from './text-field'; type State = { [key: string]: string }; class TextFieldDemo extends React.PureComponent<{}, State> { state = { demo: '' }; handleInputChange: EventHandler = (event) => { const { name, value } = event.currentTarget; this.setState({ [name]: value }); }; render() { return ( <div> <h3>TextField</h3> <TextField name="demo" label="Label" value={this.state.demo} onChange={this.handleInputChange} placeholder="placeholder text ..." helperText="Helper text" /> <pre> state.demo = {JSON.stringify(this.state.demo)} </pre> </div> ); } } export default TextFieldDemo;
app/components/ReOrder/RePickupAddress.js
prudhvisays/newsb
import React from 'react'; import Input from './ReInput'; import Flatpickr from 'react-flatpickr'; import PickupLocation from './PickupLocation'; import moment from 'moment'; export default class RePickupAddress extends React.Component { //eslint-disable-line constructor(props) { super(props); this.onChange = this.onChange.bind(this); this.reFromDate = this.reFromDate.bind(this); this.emitChanges = this.emitChanges.bind(this); } onChange(e) { const { stateData } = this.props; this.emitChanges({ ...stateData, [e.target.name]: e.target.value }); } reFromDate(date) { const { stateData } = this.props; const Date = moment(date[0]).utc().format(); this.emitChanges({ ...stateData, from_date_time: Date }); } emitChanges(newFormState) { this.props.reOrder(newFormState); } render() { const { reOrder, stateData } = this.props; return ( <div className="ink-flex vertical task-address reorder-card"> <Input title={'Name'} Name={'from_name'} Holder={'Enter Name'} onChange={this.onChange} value={stateData.from_name} /> <Input title={'Phone Number'} Name={'from_phone'} Holder={'Enter Phone Number'} onChange={this.onChange} value={stateData.from_phone} /> <Input title={'Email Id'} Name={'from_email'} Holder={'Enter Email'} onChange={this.onChange} value={stateData.from_email} /> <div className="ink-flex vertical"> <div className="sub-title">Pickup Before</div> {/*<div><Flatpickr*/} {/*placeholder={'Pickup Date'}*/} {/*onChange={this.reFromDate}*/} {/*options={{minDate: 'today',enableTime: true}}*/} {/*/></div>*/} </div> <div className="ink-flex vertical"> <div className="sub-title">Address</div> <PickupLocation stateData={stateData} reOrder={reOrder} /> </div> </div> ); } }
imports/ui/components/Infinity/GetHeightWrapper.js
ShinyLeee/meteor-album-app
import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class GetHeightWrapper extends Component { static propTypes = { getHeight: PropTypes.func.isRequired, children: PropTypes.node.isRequired, }; componentDidMount() { this.setHeight(); } shouldComponentUpdate() { return false; } setHeight = () => { const { height } = this._node.getBoundingClientRect(); this.props.getHeight(height); } render() { return ( <div ref={node => { this._node = node; }}> {this.props.children} </div> ); } }
ajax/libs/react-native-web/0.17.7/exports/RefreshControl/index.js
cdnjs/cdnjs
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import View from '../View'; import React from 'react'; function RefreshControl(props) { var colors = props.colors, enabled = props.enabled, onRefresh = props.onRefresh, progressBackgroundColor = props.progressBackgroundColor, progressViewOffset = props.progressViewOffset, refreshing = props.refreshing, size = props.size, tintColor = props.tintColor, title = props.title, titleColor = props.titleColor, rest = _objectWithoutPropertiesLoose(props, ["colors", "enabled", "onRefresh", "progressBackgroundColor", "progressViewOffset", "refreshing", "size", "tintColor", "title", "titleColor"]); return /*#__PURE__*/React.createElement(View, rest); } export default RefreshControl;
web/src/components/header.js
ajmalafif/ajmalafif.com
import { Link } from 'gatsby' import React from 'react' import tw, { theme, css } from 'twin.macro' import Modal from './dialog' import DarkModeToggle from './darkModeToggle' const isPartiallyActive = ({ isPartiallyCurrent }) => { return isPartiallyCurrent ? { className: 'active' } : null } const isActive = ({ isCurrent }) => { return isCurrent ? { className: 'active' } : null } const Header = ({ siteTitle, SkipNavLink }) => { return ( <nav tw="w-full md:top-0 md:fixed md:shadow-sm md:z-10 bg-primary border-b border-opacity-5 grid" css={{ borderColor: `${theme`borderColor.accent`}`, opacity: 0.9, gridTemplateColumns: '1fr min(1024px, calc(100% - 48px)) 1fr', gridRowGap: 8, '& > *': { gridColumn: 2, }, }} > <div tw="grid grid-cols-2 md:grid-cols-4" css={{ 'a h2:hover': { color: `${theme`colors.primary`}`, }, 'a li:hover': { color: `${theme`colors.primary`}`, }, 'a.active li': { borderBottomColor: `${theme`colors.accent`}`, borderBottomWidth: 2, marginBottom: 0, color: `${theme`colors.accent`}`, fontWeight: 600, }, 'a.active h2': { fontWeight: 600, }, }} > <section tw="contents"> <div tw="flex flex-row-reverse justify-end items-stretch md:px-0"> <SkipNavLink css={{ border: 0, clip: 'rect(0 0 0 0)', height: 1, width: 1, margin: -1, padding: 0, overflow: 'hidden', position: 'absolute', '&:focus': { zIndex: '1', width: 'auto', height: 'auto', clip: 'auto', position: 'relative', }, }} tw="justify-self-center self-center ml-4 mt-1 md:mt-0 px-1 py-0.5" /> <Link to="/" activeClassName="active" getProps={isActive}> <h2 tw="pt-4 pb-2 md:pb-3 font-serif text-opacity-70 text-lg">{siteTitle}</h2> </Link> </div> <div tw="flex flex-row-reverse space-x-3 space-x-reverse items-center md:order-last leading-none"> <Modal /> <DarkModeToggle /> </div> </section> <section tw="md:ml-auto md:mr-auto md:col-start-2 md:col-span-2"> <ul tw="text-center md:text-right font-serif text-base md:text-lg flex space-x-5 md:space-x-8"> <Link to="/projects/" activeClassName="active" getProps={isPartiallyActive}> <li tw="pt-2 md:pt-4 pb-2 md:pb-3 border-b-2 border-transparent">Projects</li> </Link> <Link to="/work/" activeClassName="active" getProps={isPartiallyActive}> <li tw="pt-2 md:pt-4 pb-2 md:pb-3 border-b-2 border-transparent">Work</li> </Link> <Link to="/about/" activeClassName="active" getProps={isPartiallyActive}> <li tw="pt-2 md:pt-4 pb-2 md:pb-3 border-b-2 border-transparent">About</li> </Link> <Link to="/reviews/" activeClassName="active" getProps={isPartiallyActive}> <li tw="pt-2 md:pt-4 pb-2 md:pb-3 border-b-2 border-transparent">Reviews</li> </Link> <Link to="/notes/" activeClassName="active" getProps={isPartiallyActive}> <li tw="pt-2 md:pt-4 pb-2 md:pb-3 border-b-2 border-transparent">Notes</li> </Link> </ul> </section> </div> </nav> ) } export default Header
ajax/libs/babel-core/5.2.5/browser-polyfill.js
BobbieBel/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){(function(global){"use strict";require("core-js/shim");require("regenerator/runtime");if(global._babelPolyfill){throw new Error("only one instance of babel/polyfill is allowed")}global._babelPolyfill=true}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"core-js/shim":78,"regenerator/runtime":79}],2:[function(require,module,exports){"use strict";var $=require("./$");module.exports=function(IS_INCLUDES){return function(el){var O=$.toObject(this),length=$.toLength(O.length),index=$.toIndex(arguments[1],length),value;if(IS_INCLUDES&&el!=el)while(length>index){value=O[index++];if(value!=value)return true}else for(;length>index;index++)if(IS_INCLUDES||index in O){if(O[index]===el)return IS_INCLUDES||index}return!IS_INCLUDES&&-1}}},{"./$":21}],3:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx");module.exports=function(TYPE){var IS_MAP=TYPE==1,IS_FILTER=TYPE==2,IS_SOME=TYPE==3,IS_EVERY=TYPE==4,IS_FIND_INDEX=TYPE==6,NO_HOLES=TYPE==5||IS_FIND_INDEX;return function(callbackfn){var O=Object($.assertDefined(this)),self=$.ES5Object(O),f=ctx(callbackfn,arguments[1],3),length=$.toLength(self.length),index=0,result=IS_MAP?Array(length):IS_FILTER?[]:undefined,val,res;for(;length>index;index++)if(NO_HOLES||index in self){val=self[index];res=f(val,index,O);if(TYPE){if(IS_MAP)result[index]=res;else if(res)switch(TYPE){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(IS_EVERY)return false}}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:result}}},{"./$":21,"./$.ctx":11}],4:[function(require,module,exports){var $=require("./$");function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}assert.def=$.assertDefined;assert.fn=function(it){if(!$.isFunction(it))throw TypeError(it+" is not a function!");return it};assert.obj=function(it){if(!$.isObject(it))throw TypeError(it+" is not an object!");return it};assert.inst=function(it,Constructor,name){if(!(it instanceof Constructor))throw TypeError(name+": use the 'new' operator!");return it};module.exports=assert},{"./$":21}],5:[function(require,module,exports){var $=require("./$"),enumKeys=require("./$.enum-keys");module.exports=Object.assign||function assign(target,source){var T=Object($.assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=$.ES5Object(arguments[i++]),keys=enumKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T}},{"./$":21,"./$.enum-keys":13}],6:[function(require,module,exports){var $=require("./$"),TAG=require("./$.wks")("toStringTag"),toString={}.toString;function cof(it){return toString.call(it).slice(8,-1)}cof.classof=function(it){var O,T;return it==undefined?it===undefined?"Undefined":"Null":typeof(T=(O=Object(it))[TAG])=="string"?T:cof(O)};cof.set=function(it,tag,stat){if(it&&!$.has(it=stat?it:it.prototype,TAG))$.hide(it,TAG,tag)};module.exports=cof},{"./$":21,"./$.wks":32}],7:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),safe=require("./$.uid").safe,assert=require("./$.assert"),forOf=require("./$.for-of"),step=require("./$.iter").step,has=$.has,set=$.set,isObject=$.isObject,hide=$.hide,isFrozen=Object.isFrozen||$.core.Object.isFrozen,ID=safe("id"),O1=safe("O1"),LAST=safe("last"),FIRST=safe("first"),ITER=safe("iter"),SIZE=$.DESC?safe("size"):"size",id=0;function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,ID)){if(!create)return"E";hide(it,ID,++id)}return"O"+it[ID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}module.exports={getConstructor:function(NAME,IS_MAP,ADDER){function C(){var that=assert.inst(this,C,NAME),iterable=arguments[0];set(that,O1,$.create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);if(iterable!=undefined)forOf(iterable,IS_MAP,that[ADDER],that)}$.mix(C.prototype,{clear:function clear(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function forEach(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function has(key){return!!getEntry(this,key)}});if($.DESC)$.setDesc(C.prototype,"size",{get:function(){return assert.def(this[SIZE])}});return C},def:function(that,key,value){var entry=getEntry(that,key),prev,index;if(entry){entry.v=value}else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that},getEntry:getEntry,setIter:function(C,NAME,IS_MAP){require("./$.iter-define")(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){iter.o=undefined;return step(1)}if(kind=="keys")return step(0,entry.k);if(kind=="values")return step(0,entry.v);return step(0,[entry.k,entry.v])},IS_MAP?"entries":"values",!IS_MAP,true)}}},{"./$":21,"./$.assert":4,"./$.ctx":11,"./$.for-of":14,"./$.iter":20,"./$.iter-define":18,"./$.uid":30}],8:[function(require,module,exports){var $def=require("./$.def"),forOf=require("./$.for-of");module.exports=function(NAME){$def($def.P,NAME,{toJSON:function toJSON(){var arr=[];forOf(this,false,arr.push,arr);return arr}})}},{"./$.def":12,"./$.for-of":14}],9:[function(require,module,exports){"use strict";var $=require("./$"),safe=require("./$.uid").safe,assert=require("./$.assert"),forOf=require("./$.for-of"),_has=$.has,isObject=$.isObject,hide=$.hide,isFrozen=Object.isFrozen||$.core.Object.isFrozen,id=0,ID=safe("id"),WEAK=safe("weak"),LEAK=safe("leak"),method=require("./$.array-methods"),find=method(5),findIndex=method(6);function findFrozen(store,key){return find.call(store.array,function(it){return it[0]===key})}function leakStore(that){return that[LEAK]||hide(that,LEAK,{array:[],get:function(key){var entry=findFrozen(this,key);if(entry)return entry[1]},has:function(key){return!!findFrozen(this,key)},set:function(key,value){var entry=findFrozen(this,key);if(entry)entry[1]=value;else this.array.push([key,value])},"delete":function(key){var index=findIndex.call(this.array,function(it){return it[0]===key});if(~index)this.array.splice(index,1);return!!~index}})[LEAK]}module.exports={getConstructor:function(NAME,IS_MAP,ADDER){function C(){$.set(assert.inst(this,C,NAME),ID,id++);var iterable=arguments[0];if(iterable!=undefined)forOf(iterable,IS_MAP,this[ADDER],this)}$.mix(C.prototype,{"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return _has(key,WEAK)&&_has(key[WEAK],this[ID])&&delete key[WEAK][this[ID]]},has:function has(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);return _has(key,WEAK)&&_has(key[WEAK],this[ID])}});return C},def:function(that,key,value){if(isFrozen(assert.obj(key))){leakStore(that).set(key,value)}else{_has(key,WEAK)||hide(key,WEAK,{});key[WEAK][that[ID]]=value}return that},leakStore:leakStore,WEAK:WEAK,ID:ID}},{"./$":21,"./$.array-methods":3,"./$.assert":4,"./$.for-of":14,"./$.uid":30}],10:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),BUGGY=require("./$.iter").BUGGY,forOf=require("./$.for-of"),species=require("./$.species"),assertInstance=require("./$.assert").inst;module.exports=function(NAME,methods,common,IS_MAP,IS_WEAK){var Base=$.g[NAME],C=Base,ADDER=IS_MAP?"set":"add",proto=C&&C.prototype,O={};function fixMethod(KEY,CHAIN){var method=proto[KEY];if($.FW)proto[KEY]=function(a,b){var result=method.call(this,a===0?0:a,b);return CHAIN?this:result}}if(!$.isFunction(C)||!(IS_WEAK||!BUGGY&&proto.forEach&&proto.entries)){C=common.getConstructor(NAME,IS_MAP,ADDER);$.mix(C.prototype,methods)}else{var inst=new C,chain=inst[ADDER](IS_WEAK?{}:-0,1),buggyZero;if(!require("./$.iter-detect")(function(iter){new C(iter)})){C=function(){assertInstance(this,C,NAME);var that=new Base,iterable=arguments[0];if(iterable!=undefined)forOf(iterable,IS_MAP,that[ADDER],that);return that};C.prototype=proto;if($.FW)proto.constructor=C}IS_WEAK||inst.forEach(function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixMethod("delete");fixMethod("has");IS_MAP&&fixMethod("get")}if(buggyZero||chain!==inst)fixMethod(ADDER,true)}require("./$.cof").set(C,NAME);O[NAME]=C;$def($def.G+$def.W+$def.F*(C!=Base),O);species(C);species($.core[NAME]);if(!IS_WEAK)common.setIter(C,NAME,IS_MAP);return C}},{"./$":21,"./$.assert":4,"./$.cof":6,"./$.def":12,"./$.for-of":14,"./$.iter":20,"./$.iter-detect":19,"./$.species":27}],11:[function(require,module,exports){var assertFunction=require("./$.assert").fn;module.exports=function(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}},{"./$.assert":4}],12:[function(require,module,exports){var $=require("./$"),global=$.g,core=$.core,isFunction=$.isFunction;function ctx(fn,that){return function(){return fn.apply(that,arguments)}}global.core=core;$def.F=1;$def.G=2;$def.S=4;$def.P=8;$def.B=16;$def.W=32;function $def(type,name,source){var key,own,out,exp,isGlobal=type&$def.G,target=isGlobal?global:type&$def.S?global[name]:(global[name]||{}).prototype,exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&$def.F)&&target&&key in target;out=(own?target:source)[key];if(type&$def.B&&own)exp=ctx(out,global);else exp=type&$def.P&&isFunction(out)?ctx(Function.call,out):out;if(target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&$.hide(target,key,out)}if(exports[key]!=out)$.hide(exports,key,exp)}}module.exports=$def},{"./$":21}],13:[function(require,module,exports){var $=require("./$");module.exports=function(it){var keys=$.getKeys(it),getDesc=$.getDesc,getSymbols=$.getSymbols;if(getSymbols)$.each.call(getSymbols(it),function(key){if(getDesc(it,key).enumerable)keys.push(key)});return keys}},{"./$":21}],14:[function(require,module,exports){var ctx=require("./$.ctx"),get=require("./$.iter").get,call=require("./$.iter-call");module.exports=function(iterable,entries,fn,that){var iterator=get(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done){if(call(iterator,f,step.value,entries)===false){return call.close(iterator)}}}},{"./$.ctx":11,"./$.iter":20,"./$.iter-call":17}],15:[function(require,module,exports){module.exports=function($){$.FW=true;$.path=$.g;return $}},{}],16:[function(require,module,exports){module.exports=function(fn,args,that){var un=that===undefined;switch(args.length){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}},{}],17:[function(require,module,exports){var assertObject=require("./$.assert").obj;function close(iterator){var ret=iterator["return"];if(ret!==undefined)assertObject(ret.call(iterator))}function call(iterator,fn,value,entries){try{return entries?fn(assertObject(value)[0],value[1]):fn(value)}catch(e){close(iterator);throw e}}call.close=close;module.exports=call},{"./$.assert":4}],18:[function(require,module,exports){var $def=require("./$.def"),$=require("./$"),cof=require("./$.cof"),$iter=require("./$.iter"),SYMBOL_ITERATOR=require("./$.wks")("iterator"),FF_ITERATOR="@@iterator",VALUES="values",Iterators=$iter.Iterators;module.exports=function(Base,NAME,Constructor,next,DEFAULT,IS_SET,FORCE){$iter.create(Constructor,NAME,next);function createMethod(kind){return function(){return new Constructor(this,kind)}}var TAG=NAME+" Iterator",proto=Base.prototype,_native=proto[SYMBOL_ITERATOR]||proto[FF_ITERATOR]||DEFAULT&&proto[DEFAULT],_default=_native||createMethod(DEFAULT),methods,key;if(_native){var IteratorPrototype=$.getProto(_default.call(new Base));cof.set(IteratorPrototype,TAG,true);if($.FW&&$.has(proto,FF_ITERATOR))$iter.set(IteratorPrototype,$.that)}if($.FW)$iter.set(proto,_default);Iterators[NAME]=_default;Iterators[TAG]=$.that;if(DEFAULT){methods={keys:IS_SET?_default:createMethod("keys"),values:DEFAULT==VALUES?_default:createMethod(VALUES),entries:DEFAULT!=VALUES?_default:createMethod("entries")};if(FORCE)for(key in methods){if(!(key in proto))$.hide(proto,key,methods[key])}else $def($def.P+$def.F*$iter.BUGGY,NAME,methods)}}},{"./$":21,"./$.cof":6,"./$.def":12,"./$.iter":20,"./$.wks":32}],19:[function(require,module,exports){var SYMBOL_ITERATOR=require("./$.wks")("iterator"),SAFE_CLOSING=false;try{var riter=[7][SYMBOL_ITERATOR]();riter["return"]=function(){SAFE_CLOSING=true};Array.from(riter,function(){throw 2})}catch(e){}module.exports=function(exec){if(!SAFE_CLOSING)return false;var safe=false;try{var arr=[7],iter=arr[SYMBOL_ITERATOR]();iter.next=function(){safe=true};arr[SYMBOL_ITERATOR]=function(){return iter};exec(arr)}catch(e){}return safe}},{"./$.wks":32}],20:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),assertObject=require("./$.assert").obj,SYMBOL_ITERATOR=require("./$.wks")("iterator"),FF_ITERATOR="@@iterator",Iterators={},IteratorPrototype={};setIterator(IteratorPrototype,$.that);function setIterator(O,value){$.hide(O,SYMBOL_ITERATOR,value);if(FF_ITERATOR in[])$.hide(O,FF_ITERATOR,value)}module.exports={BUGGY:"keys"in[]&&!("next"in[].keys()),Iterators:Iterators,step:function(done,value){return{value:value,done:!!done}},is:function(it){var O=Object(it),Symbol=$.g.Symbol,SYM=Symbol&&Symbol.iterator||FF_ITERATOR;return SYM in O||SYMBOL_ITERATOR in O||$.has(Iterators,cof.classof(O))},get:function(it){var Symbol=$.g.Symbol,ext=it[Symbol&&Symbol.iterator||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[cof.classof(it)];return assertObject(getIter.call(it))},set:setIterator,create:function(Constructor,NAME,next,proto){Constructor.prototype=$.create(proto||IteratorPrototype,{next:$.desc(1,next)});cof.set(Constructor,NAME+" Iterator")}}},{"./$":21,"./$.assert":4,"./$.cof":6,"./$.wks":32}],21:[function(require,module,exports){"use strict";var global=typeof self!="undefined"?self:Function("return this")(),core={},defineProperty=Object.defineProperty,hasOwnProperty={}.hasOwnProperty,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min;var DESC=!!function(){try{return defineProperty({},"a",{get:function(){return 2}}).a==2}catch(e){}}();var hide=createDefiner(1);function toInteger(it){return isNaN(it=+it)?0:(it>0?floor:ceil)(it)}function desc(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return $.setDesc(object,key,desc(bitmap,value))}:simpleSet}function isObject(it){return it!==null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}function assertDefined(it){if(it==undefined)throw TypeError("Can't call method on "+it);return it}var $=module.exports=require("./$.fw")({g:global,core:core,html:global.document&&document.documentElement,isObject:isObject,isFunction:isFunction,it:function(it){return it},that:function(){return this},toInteger:toInteger,toLength:function(it){return it>0?min(toInteger(it),9007199254740991):0},toIndex:function(index,length){index=toInteger(index);return index<0?max(index+length,0):min(index,length)},has:function(it,key){return hasOwnProperty.call(it,key)},create:Object.create,getProto:Object.getPrototypeOf,DESC:DESC,desc:desc,getDesc:Object.getOwnPropertyDescriptor,setDesc:defineProperty,setDescs:Object.defineProperties,getKeys:Object.keys,getNames:Object.getOwnPropertyNames,getSymbols:Object.getOwnPropertySymbols,assertDefined:assertDefined,ES5Object:Object,toObject:function(it){return $.ES5Object(assertDefined(it))},hide:hide,def:createDefiner(0),set:global.Symbol?simpleSet:hide,mix:function(target,src){for(var key in src)hide(target,key,src[key]);return target},each:[].forEach});if(typeof __e!="undefined")__e=core;if(typeof __g!="undefined")__g=global},{"./$.fw":15}],22:[function(require,module,exports){var $=require("./$");module.exports=function(object,el){var O=$.toObject(object),keys=$.getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}},{"./$":21}],23:[function(require,module,exports){var $=require("./$"),assertObject=require("./$.assert").obj;module.exports=function ownKeys(it){assertObject(it);var keys=$.getNames(it),getSymbols=$.getSymbols;return getSymbols?keys.concat(getSymbols(it)):keys}},{"./$":21,"./$.assert":4}],24:[function(require,module,exports){"use strict";var $=require("./$"),invoke=require("./$.invoke"),assertFunction=require("./$.assert").fn;module.exports=function(){var fn=assertFunction(this),length=arguments.length,pargs=Array(length),i=0,_=$.path._,holder=false;while(length>i)if((pargs[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,j=0,k=0,args;if(!holder&&!_length)return invoke(fn,pargs,that);args=pargs.slice();if(holder)for(;length>j;j++)if(args[j]===_)args[j]=arguments[k++];while(_length>k)args.push(arguments[k++]);return invoke(fn,args,that)}}},{"./$":21,"./$.assert":4,"./$.invoke":16}],25:[function(require,module,exports){"use strict";module.exports=function(regExp,replace,isStatic){var replacer=replace===Object(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}},{}],26:[function(require,module,exports){var $=require("./$"),assert=require("./$.assert");function check(O,proto){assert.obj(O);assert(proto===null||$.isObject(proto),proto,": can't set as prototype!")}module.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(buggy,set){try{set=require("./$.ctx")(Function.call,$.getDesc(Object.prototype,"__proto__").set,2);set({},[])}catch(e){buggy=true}return function setPrototypeOf(O,proto){check(O,proto);if(buggy)O.__proto__=proto;else set(O,proto);return O}}():undefined),check:check}},{"./$":21,"./$.assert":4,"./$.ctx":11}],27:[function(require,module,exports){var $=require("./$"),SPECIES=require("./$.wks")("species");module.exports=function(C){if($.DESC&&!(SPECIES in C))$.setDesc(C,SPECIES,{configurable:true,get:$.that})}},{"./$":21,"./$.wks":32}],28:[function(require,module,exports){"use strict";var $=require("./$");module.exports=function(TO_STRING){return function(pos){var s=String($.assertDefined(this)),i=$.toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return TO_STRING?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?TO_STRING?s.charAt(i):a:TO_STRING?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}},{"./$":21}],29:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),cof=require("./$.cof"),invoke=require("./$.invoke"),global=$.g,isFunction=$.isFunction,html=$.html,document=global.document,process=global.process,setTask=global.setImmediate,clearTask=global.clearImmediate,postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},ONREADYSTATECHANGE="onreadystatechange",defer,channel,port;function run(){var id=+this;if($.has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run.call(event.data)}if(!isFunction(setTask)||!isFunction(clearTask)){setTask=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearTask=function(id){delete queue[id]};if(cof(process)=="process"){defer=function(id){process.nextTick(ctx(run,id,1))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document.createElement("script")){defer=function(id){html.appendChild(document.createElement("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run.call(id)}}}else{defer=function(id){setTimeout(ctx(run,id,1),0)}}}module.exports={set:setTask,clear:clearTask}},{"./$":21,"./$.cof":6,"./$.ctx":11,"./$.invoke":16}],30:[function(require,module,exports){var sid=0;function uid(key){return"Symbol("+key+")_"+(++sid+Math.random()).toString(36)}uid.safe=require("./$").g.Symbol||uid;module.exports=uid},{"./$":21}],31:[function(require,module,exports){var $=require("./$"),UNSCOPABLES=require("./$.wks")("unscopables");if($.FW&&!(UNSCOPABLES in[]))$.hide(Array.prototype,UNSCOPABLES,{});module.exports=function(key){if($.FW)[][UNSCOPABLES][key]=true}},{"./$":21,"./$.wks":32}],32:[function(require,module,exports){var global=require("./$").g,store={};module.exports=function(name){return store[name]||(store[name]=global.Symbol&&global.Symbol[name]||require("./$.uid").safe("Symbol."+name))}},{"./$":21,"./$.uid":30}],33:[function(require,module,exports){var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def"),invoke=require("./$.invoke"),arrayMethod=require("./$.array-methods"),IE_PROTO=require("./$.uid").safe("__proto__"),assert=require("./$.assert"),assertObject=assert.obj,ObjectProto=Object.prototype,A=[],slice=A.slice,indexOf=A.indexOf,classof=cof.classof,has=$.has,defineProperty=$.setDesc,getOwnDescriptor=$.getDesc,defineProperties=$.setDescs,isFunction=$.isFunction,toObject=$.toObject,toLength=$.toLength,IE8_DOM_DEFINE=false;if(!$.DESC){try{IE8_DOM_DEFINE=defineProperty(document.createElement("div"),"x",{get:function(){return 8}}).x==8}catch(e){}$.setDesc=function(O,P,Attributes){if(IE8_DOM_DEFINE)try{return defineProperty(O,P,Attributes)}catch(e){}if("get"in Attributes||"set"in Attributes)throw TypeError("Accessors not supported!");if("value"in Attributes)assertObject(O)[P]=Attributes.value;return O};$.getDesc=function(O,P){if(IE8_DOM_DEFINE)try{return getOwnDescriptor(O,P)}catch(e){}if(has(O,P))return $.desc(!ObjectProto.propertyIsEnumerable.call(O,P),O[P])};$.setDescs=defineProperties=function(O,Properties){assertObject(O);var keys=$.getKeys(Properties),length=keys.length,i=0,P;while(length>i)$.setDesc(O,P=keys[i++],Properties[P]);return O}}$def($def.S+$def.F*!$.DESC,"Object",{getOwnPropertyDescriptor:$.getDesc,defineProperty:$.setDesc,defineProperties:defineProperties});var keys1=("constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,"+"toLocaleString,toString,valueOf").split(","),keys2=keys1.concat("length","prototype"),keysLen1=keys1.length;var createDict=function(){var iframe=document.createElement("iframe"),i=keysLen1,gt=">",iframeDocument;iframe.style.display="none";$.html.appendChild(iframe);iframe.src="javascript:";iframeDocument=iframe.contentWindow.document;iframeDocument.open();iframeDocument.write("<script>document.F=Object</script"+gt);iframeDocument.close();createDict=iframeDocument.F;while(i--)delete createDict.prototype[keys1[i]];return createDict()};function createGetKeys(names,length){return function(object){var O=toObject(object),i=0,result=[],key;for(key in O)if(key!=IE_PROTO)has(O,key)&&result.push(key);while(length>i)if(has(O,key=names[i++])){~indexOf.call(result,key)||result.push(key)}return result}}function isPrimitive(it){return!$.isObject(it)}function Empty(){}$def($def.S,"Object",{getPrototypeOf:$.getProto=$.getProto||function(O){O=Object(assert.def(O));if(has(O,IE_PROTO))return O[IE_PROTO];if(isFunction(O.constructor)&&O instanceof O.constructor){return O.constructor.prototype}return O instanceof Object?ObjectProto:null},getOwnPropertyNames:$.getNames=$.getNames||createGetKeys(keys2,keys2.length,true),create:$.create=$.create||function(O,Properties){var result;if(O!==null){Empty.prototype=assertObject(O);result=new Empty;Empty.prototype=null;result[IE_PROTO]=O}else result=createDict();return Properties===undefined?result:defineProperties(result,Properties)},keys:$.getKeys=$.getKeys||createGetKeys(keys1,keysLen1,false),seal:$.it,freeze:$.it,preventExtensions:$.it,isSealed:isPrimitive,isFrozen:isPrimitive,isExtensible:$.isObject});$def($def.P,"Function",{bind:function(that){var fn=assert.fn(this),partArgs=slice.call(arguments,1);function bound(){var args=partArgs.concat(slice.call(arguments));return invoke(fn,args,this instanceof bound?$.create(fn.prototype):that)}if(fn.prototype)bound.prototype=fn.prototype;return bound}});function arrayMethodFix(fn){return function(){return fn.apply($.ES5Object(this),arguments)}}if(!(0 in Object("z")&&"z"[0]=="z")){$.ES5Object=function(it){return cof(it)=="String"?it.split(""):Object(it)}}$def($def.P+$def.F*($.ES5Object!=Object),"Array",{slice:arrayMethodFix(slice),join:arrayMethodFix(A.join)});$def($def.S,"Array",{isArray:function(arg){return cof(arg)=="Array"}});function createArrayReduce(isRight){return function(callbackfn,memo){assert.fn(callbackfn);var O=toObject(this),length=toLength(O.length),index=isRight?length-1:0,i=isRight?-1:1;if(arguments.length<2)for(;;){if(index in O){memo=O[index];index+=i;break}index+=i;assert(isRight?index>=0:length>index,"Reduce of empty array with no initial value")}for(;isRight?index>=0:length>index;index+=i)if(index in O){memo=callbackfn(memo,O[index],index,this)}return memo}}$def($def.P,"Array",{forEach:$.each=$.each||arrayMethod(0),map:arrayMethod(1),filter:arrayMethod(2),some:arrayMethod(3),every:arrayMethod(4),reduce:createArrayReduce(false),reduceRight:createArrayReduce(true),indexOf:indexOf=indexOf||require("./$.array-includes")(false),lastIndexOf:function(el,fromIndex){var O=toObject(this),length=toLength(O.length),index=length-1;if(arguments.length>1)index=Math.min(index,$.toInteger(fromIndex));if(index<0)index=toLength(length+index);for(;index>=0;index--)if(index in O)if(O[index]===el)return index;return-1}});$def($def.P,"String",{trim:require("./$.replacer")(/^\s*([\s\S]*\S)?\s*$/,"$1")});$def($def.S,"Date",{now:function(){return+new Date}});function lz(num){return num>9?num:"0"+num}var date=new Date(-5e13-1),brokenDate=!(date.toISOString&&date.toISOString()=="0385-07-25T07:06:39.999Z");$def($def.P+$def.F*brokenDate,"Date",{toISOString:function(){if(!isFinite(this))throw RangeError("Invalid time value");var d=this,y=d.getUTCFullYear(),m=d.getUTCMilliseconds(),s=y<0?"-":y>9999?"+":"";return s+("00000"+Math.abs(y)).slice(s?-6:-4)+"-"+lz(d.getUTCMonth()+1)+"-"+lz(d.getUTCDate())+"T"+lz(d.getUTCHours())+":"+lz(d.getUTCMinutes())+":"+lz(d.getUTCSeconds())+"."+(m>99?m:"0"+lz(m))+"Z"}});if(classof(function(){return arguments}())=="Object")cof.classof=function(it){var tag=classof(it);return tag=="Object"&&isFunction(it.callee)?"Arguments":tag}},{"./$":21,"./$.array-includes":2,"./$.array-methods":3,"./$.assert":4,"./$.cof":6,"./$.def":12,"./$.invoke":16,"./$.replacer":25,"./$.uid":30}],34:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),toIndex=$.toIndex;$def($def.P,"Array",{copyWithin:function copyWithin(target,start){var O=Object($.assertDefined(this)),len=$.toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=Math.min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O}});require("./$.unscope")("copyWithin")},{"./$":21,"./$.def":12,"./$.unscope":31}],35:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),toIndex=$.toIndex;$def($def.P,"Array",{fill:function fill(value){var O=Object($.assertDefined(this)),length=$.toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O}});require("./$.unscope")("fill")},{"./$":21,"./$.def":12,"./$.unscope":31}],36:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"Array",{findIndex:require("./$.array-methods")(6)});require("./$.unscope")("findIndex")},{"./$.array-methods":3,"./$.def":12,"./$.unscope":31}],37:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"Array",{find:require("./$.array-methods")(5)});require("./$.unscope")("find")},{"./$.array-methods":3,"./$.def":12,"./$.unscope":31}],38:[function(require,module,exports){var $=require("./$"),ctx=require("./$.ctx"),$def=require("./$.def"),$iter=require("./$.iter"),call=require("./$.iter-call");$def($def.S+$def.F*!require("./$.iter-detect")(function(iter){Array.from(iter)}),"Array",{from:function from(arrayLike){var O=Object($.assertDefined(arrayLike)),mapfn=arguments[1],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,arguments[2],2):undefined,index=0,length,result,step,iterator;if($iter.is(O)){iterator=$iter.get(O);result=new(typeof this=="function"?this:Array);for(;!(step=iterator.next()).done;index++){result[index]=mapping?call(iterator,f,[step.value,index],true):step.value}}else{result=new(typeof this=="function"?this:Array)(length=$.toLength(O.length));for(;length>index;index++){result[index]=mapping?f(O[index],index):O[index]}}result.length=index;return result}})},{"./$":21,"./$.ctx":11,"./$.def":12,"./$.iter":20,"./$.iter-call":17,"./$.iter-detect":19}],39:[function(require,module,exports){var $=require("./$"),setUnscope=require("./$.unscope"),ITER=require("./$.uid").safe("iter"),$iter=require("./$.iter"),step=$iter.step,Iterators=$iter.Iterators;require("./$.iter-define")(Array,"Array",function(iterated,kind){$.set(this,ITER,{o:$.toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length){iter.o=undefined;return step(1)}if(kind=="keys")return step(0,index);if(kind=="values")return step(0,O[index]);return step(0,[index,O[index]])},"values");Iterators.Arguments=Iterators.Array;setUnscope("keys");setUnscope("values");setUnscope("entries")},{"./$":21,"./$.iter":20,"./$.iter-define":18,"./$.uid":30,"./$.unscope":31}],40:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Array",{of:function of(){var index=0,length=arguments.length,result=new(typeof this=="function"?this:Array)(length);while(length>index)result[index]=arguments[index++];result.length=length;return result; }})},{"./$.def":12}],41:[function(require,module,exports){require("./$.species")(Array)},{"./$.species":27}],42:[function(require,module,exports){"use strict";var $=require("./$"),NAME="name",setDesc=$.setDesc,FunctionProto=Function.prototype;NAME in FunctionProto||$.FW&&$.DESC&&setDesc(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";$.has(this,NAME)||setDesc(this,NAME,$.desc(5,name));return name},set:function(value){$.has(this,NAME)||setDesc(this,NAME,$.desc(0,value))}})},{"./$":21}],43:[function(require,module,exports){"use strict";var strong=require("./$.collection-strong");require("./$.collection")("Map",{get:function get(key){var entry=strong.getEntry(this,key);return entry&&entry.v},set:function set(key,value){return strong.def(this,key===0?0:key,value)}},strong,true)},{"./$.collection":10,"./$.collection-strong":7}],44:[function(require,module,exports){var Infinity=1/0,$def=require("./$.def"),E=Math.E,pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,ceil=Math.ceil,floor=Math.floor,EPSILON=pow(2,-52),EPSILON32=pow(2,-23),MAX32=pow(2,127)*(2-EPSILON32),MIN32=pow(2,-126);function roundTiesToEven(n){return n+1/EPSILON-1/EPSILON}function sign(x){return(x=+x)==0||x!=x?x:x<0?-1:1}function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$def($def.S,"Math",{acosh:function acosh(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function atanh(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function cbrt(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function clz32(x){return(x>>>=0)?31-floor(log(x+.5)*Math.LOG2E):32},cosh:function cosh(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function fround(x){var $abs=abs(x),$sign=sign(x),a,result;if($abs<MIN32)return $sign*roundTiesToEven($abs/MIN32/EPSILON32)*MIN32*EPSILON32;a=(1+EPSILON32/EPSILON)*$abs;result=a-(a-$abs);if(result>MAX32||result!=result)return $sign*Infinity;return $sign*result},hypot:function hypot(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function imul(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function log1p(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function log10(x){return log(x)/Math.LN10},log2:function log2(x){return log(x)/Math.LN2},sign:sign,sinh:function sinh(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function tanh(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:function trunc(it){return(it>0?floor:ceil)(it)}})},{"./$.def":12}],45:[function(require,module,exports){"use strict";var $=require("./$"),isObject=$.isObject,isFunction=$.isFunction,NUMBER="Number",Number=$.g[NUMBER],Base=Number,proto=Number.prototype;function toPrimitive(it){var fn,val;if(isFunction(fn=it.valueOf)&&!isObject(val=fn.call(it)))return val;if(isFunction(fn=it.toString)&&!isObject(val=fn.call(it)))return val;throw TypeError("Can't convert object to number")}function toNumber(it){if(isObject(it))it=toPrimitive(it);if(typeof it=="string"&&it.length>2&&it.charCodeAt(0)==48){var binary=false;switch(it.charCodeAt(1)){case 66:case 98:binary=true;case 79:case 111:return parseInt(it.slice(2),binary?2:8)}}return+it}if($.FW&&!(Number("0o1")&&Number("0b1"))){Number=function Number(it){return this instanceof Number?new Base(toNumber(it)):toNumber(it)};$.each.call($.DESC?$.getNames(Base):("MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,"+"EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,"+"MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger").split(","),function(key){if($.has(Base,key)&&!$.has(Number,key)){$.setDesc(Number,key,$.getDesc(Base,key))}});Number.prototype=proto;proto.constructor=Number;$.hide($.g,NUMBER,Number)}},{"./$":21}],46:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),abs=Math.abs,floor=Math.floor,_isFinite=$.g.isFinite,MAX_SAFE_INTEGER=9007199254740991;function isInteger(it){return!$.isObject(it)&&_isFinite(it)&&floor(it)===it}$def($def.S,"Number",{EPSILON:Math.pow(2,-52),isFinite:function isFinite(it){return typeof it=="number"&&_isFinite(it)},isInteger:isInteger,isNaN:function isNaN(number){return number!=number},isSafeInteger:function isSafeInteger(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt})},{"./$":21,"./$.def":12}],47:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Object",{assign:require("./$.assign")})},{"./$.assign":5,"./$.def":12}],48:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Object",{is:function is(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}})},{"./$.def":12}],49:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Object",{setPrototypeOf:require("./$.set-proto").set})},{"./$.def":12,"./$.set-proto":26}],50:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),isObject=$.isObject,toObject=$.toObject;function wrapObjectMethod(METHOD,MODE){var fn=($.core.Object||{})[METHOD]||Object[METHOD],f=0,o={};o[METHOD]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function getOwnPropertyDescriptor(it,key){return fn(toObject(it),key)}:MODE==5?function getPrototypeOf(it){return fn(Object($.assertDefined(it)))}:function(it){return fn(toObject(it))};try{fn("z")}catch(e){f=1}$def($def.S+$def.F*f,"Object",o)}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf",5);wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames")},{"./$":21,"./$.def":12}],51:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),tmp={};tmp[require("./$.wks")("toStringTag")]="z";if($.FW&&cof(tmp)!="z")$.hide(Object.prototype,"toString",function toString(){return"[object "+cof.classof(this)+"]"})},{"./$":21,"./$.cof":6,"./$.wks":32}],52:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),cof=require("./$.cof"),$def=require("./$.def"),assert=require("./$.assert"),forOf=require("./$.for-of"),setProto=require("./$.set-proto").set,species=require("./$.species"),SPECIES=require("./$.wks")("species"),RECORD=require("./$.uid").safe("record"),PROMISE="Promise",global=$.g,process=global.process,asap=process&&process.nextTick||require("./$.task").set,P=global[PROMISE],isFunction=$.isFunction,isObject=$.isObject,assertFunction=assert.fn,assertObject=assert.obj,test;var useNative=isFunction(P)&&isFunction(P.resolve)&&P.resolve(test=new P(function(){}))==test;function P2(x){var self=new P(x);setProto(self,P2.prototype);return self}if(useNative){try{setProto(P2,P);P2.prototype=$.create(P.prototype,{constructor:{value:P2}});if(!(P2.resolve(5).then(function(){})instanceof P2)){useNative=false}}catch(e){useNative=false}}function getConstructor(C){var S=assertObject(C)[SPECIES];return S!=undefined?S:C}function isThenable(it){var then;if(isObject(it))then=it.then;return isFunction(then)?then:false}function notify(record){var chain=record.c;if(chain.length)asap(function(){var value=record.v,ok=record.s==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){if(!ok)record.h=true;ret=cb===true?value:cb(value);if(ret===react.P){react.rej(TypeError("Promise-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(value)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function isUnhandled(promise){var record=promise[RECORD],chain=record.a,i=0,react;if(record.h)return false;while(chain.length>i){react=chain[i++];if(react.fail||!isUnhandled(react.P))return false}return true}function $reject(value){var record=this,promise;if(record.d)return;record.d=true;record=record.r||record;record.v=value;record.s=2;asap(function(){setTimeout(function(){if(isUnhandled(promise=record.p)){if(cof(process)=="process"){process.emit("unhandledRejection",value,promise)}else if(global.console&&isFunction(console.error)){console.error("Unhandled promise rejection",value)}}},1)});notify(record)}function $resolve(value){var record=this,then,wrapper;if(record.d)return;record.d=true;record=record.r||record;try{if(then=isThenable(value)){wrapper={r:record,d:false};then.call(value,ctx($resolve,wrapper,1),ctx($reject,wrapper,1))}else{record.v=value;record.s=1;notify(record)}}catch(err){$reject.call(wrapper||{r:record,d:false},err)}}if(!useNative){P=function Promise(executor){assertFunction(executor);var record={p:assert.inst(this,P,PROMISE),c:[],a:[],s:0,d:false,v:undefined,h:false};$.hide(this,RECORD,record);try{executor(ctx($resolve,record,1),ctx($reject,record,1))}catch(err){$reject.call(record,err)}};$.mix(P.prototype,{then:function then(onFulfilled,onRejected){var S=assertObject(assertObject(this).constructor)[SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false};var promise=react.P=new(S!=undefined?S:P)(function(res,rej){react.res=assertFunction(res);react.rej=assertFunction(rej)});var record=this[RECORD];record.a.push(react);record.c.push(react);record.s&&notify(record);return promise},"catch":function(onRejected){return this.then(undefined,onRejected)}})}$def($def.G+$def.W+$def.F*!useNative,{Promise:P});cof.set(P,PROMISE);species(P);species($.core[PROMISE]);$def($def.S+$def.F*!useNative,PROMISE,{reject:function reject(r){return new(getConstructor(this))(function(res,rej){rej(r)})},resolve:function resolve(x){return isObject(x)&&RECORD in x&&$.getProto(x)===this.prototype?x:new(getConstructor(this))(function(res){res(x)})}});$def($def.S+$def.F*!(useNative&&require("./$.iter-detect")(function(iter){P.all(iter)["catch"](function(){})})),PROMISE,{all:function all(iterable){var C=getConstructor(this),values=[];return new C(function(res,rej){forOf(iterable,false,values.push,values);var remaining=values.length,results=Array(remaining);if(remaining)$.each.call(values,function(promise,index){C.resolve(promise).then(function(value){results[index]=value;--remaining||res(results)},rej)});else res(results)})},race:function race(iterable){var C=getConstructor(this);return new C(function(res,rej){forOf(iterable,false,function(promise){C.resolve(promise).then(res,rej)})})}})},{"./$":21,"./$.assert":4,"./$.cof":6,"./$.ctx":11,"./$.def":12,"./$.for-of":14,"./$.iter-detect":19,"./$.set-proto":26,"./$.species":27,"./$.task":29,"./$.uid":30,"./$.wks":32}],53:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),setProto=require("./$.set-proto"),$iter=require("./$.iter"),ITER=require("./$.uid").safe("iter"),step=$iter.step,assert=require("./$.assert"),isObject=$.isObject,getDesc=$.getDesc,setDesc=$.setDesc,getProto=$.getProto,apply=Function.apply,assertObject=assert.obj,_isExtensible=Object.isExtensible||$.it;function Enumerate(iterated){$.set(this,ITER,{o:iterated,k:undefined,i:0})}$iter.create(Enumerate,"Object",function(){var iter=this[ITER],keys=iter.k,key;if(keys==undefined){iter.k=keys=[];for(key in iter.o)keys.push(key)}do{if(iter.i>=keys.length)return step(1)}while(!((key=keys[iter.i++])in iter.o));return step(0,key)});function wrap(fn){return function(it){assertObject(it);try{fn.apply(undefined,arguments);return true}catch(e){return false}}}function get(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getDesc(assertObject(target),propertyKey),proto;if(desc)return $.has(desc,"value")?desc.value:desc.get===undefined?undefined:desc.get.call(receiver);return isObject(proto=getProto(target))?get(proto,propertyKey,receiver):undefined}function set(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],ownDesc=getDesc(assertObject(target),propertyKey),existingDescriptor,proto;if(!ownDesc){if(isObject(proto=getProto(target))){return set(proto,propertyKey,V,receiver)}ownDesc=$.desc(0)}if($.has(ownDesc,"value")){if(ownDesc.writable===false||!isObject(receiver))return false;existingDescriptor=getDesc(receiver,propertyKey)||$.desc(0);existingDescriptor.value=V;setDesc(receiver,propertyKey,existingDescriptor);return true}return ownDesc.set===undefined?false:(ownDesc.set.call(receiver,V),true)}var reflect={apply:require("./$.ctx")(Function.call,apply,3),construct:function construct(target,argumentsList){var proto=assert.fn(arguments.length<3?target:arguments[2]).prototype,instance=$.create(isObject(proto)?proto:Object.prototype),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance},defineProperty:wrap(setDesc),deleteProperty:function deleteProperty(target,propertyKey){var desc=getDesc(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function enumerate(target){return new Enumerate(assertObject(target))},get:get,getOwnPropertyDescriptor:function getOwnPropertyDescriptor(target,propertyKey){return getDesc(assertObject(target),propertyKey)},getPrototypeOf:function getPrototypeOf(target){return getProto(assertObject(target))},has:function has(target,propertyKey){return propertyKey in target},isExtensible:function isExtensible(target){return!!_isExtensible(assertObject(target))},ownKeys:require("./$.own-keys"),preventExtensions:wrap(Object.preventExtensions||$.it),set:set};if(setProto)reflect.setPrototypeOf=function setPrototypeOf(target,proto){setProto.check(target,proto);try{setProto.set(target,proto);return true}catch(e){return false}};$def($def.G,{Reflect:{}});$def($def.S,"Reflect",reflect)},{"./$":21,"./$.assert":4,"./$.ctx":11,"./$.def":12,"./$.iter":20,"./$.own-keys":23,"./$.set-proto":26,"./$.uid":30}],54:[function(require,module,exports){var $=require("./$"),cof=require("./$.cof"),RegExp=$.g.RegExp,Base=RegExp,proto=RegExp.prototype;function regExpBroken(){try{var a=/a/g;if(a===new RegExp(a)){return true}return RegExp(/a/g,"i")!="/a/i"}catch(e){return true}}if($.FW&&$.DESC){if(regExpBroken()){RegExp=function RegExp(pattern,flags){return new Base(cof(pattern)=="RegExp"?pattern.source:pattern,flags===undefined?pattern.flags:flags)};$.each.call($.getNames(Base),function(key){key in RegExp||$.setDesc(RegExp,key,{configurable:true,get:function(){return Base[key]},set:function(it){Base[key]=it}})});proto.constructor=RegExp;RegExp.prototype=proto;$.hide($.g,"RegExp",RegExp)}if(/./g.flags!="g")$.setDesc(proto,"flags",{configurable:true,get:require("./$.replacer")(/^.*\/(\w*)$/,"$1")})}require("./$.species")(RegExp)},{"./$":21,"./$.cof":6,"./$.replacer":25,"./$.species":27}],55:[function(require,module,exports){"use strict";var strong=require("./$.collection-strong");require("./$.collection")("Set",{add:function add(value){return strong.def(this,value=value===0?0:value,value)}},strong)},{"./$.collection":10,"./$.collection-strong":7}],56:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"String",{codePointAt:require("./$.string-at")(false)})},{"./$.def":12,"./$.string-at":28}],57:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def"),toLength=$.toLength;$def($def.P,"String",{endsWith:function endsWith(searchString){if(cof(searchString)=="RegExp")throw TypeError();var that=String($.assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:Math.min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString}})},{"./$":21,"./$.cof":6,"./$.def":12}],58:[function(require,module,exports){var $def=require("./$.def"),toIndex=require("./$").toIndex,fromCharCode=String.fromCharCode;$def($def.S,"String",{fromCodePoint:function fromCodePoint(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fromCharCode(code):fromCharCode(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")}})},{"./$":21,"./$.def":12}],59:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def");$def($def.P,"String",{includes:function includes(searchString){if(cof(searchString)=="RegExp")throw TypeError();return!!~String($.assertDefined(this)).indexOf(searchString,arguments[1])}})},{"./$":21,"./$.cof":6,"./$.def":12}],60:[function(require,module,exports){var set=require("./$").set,at=require("./$.string-at")(true),ITER=require("./$.uid").safe("iter"),$iter=require("./$.iter"),step=$iter.step;require("./$.iter-define")(String,"String",function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return step(1);point=at.call(O,index);iter.i+=point.length;return step(0,point)})},{"./$":21,"./$.iter":20,"./$.iter-define":18,"./$.string-at":28,"./$.uid":30}],61:[function(require,module,exports){var $=require("./$"),$def=require("./$.def");$def($def.S,"String",{raw:function raw(callSite){var tpl=$.toObject(callSite.raw),len=$.toLength(tpl.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(tpl[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}})},{"./$":21,"./$.def":12}],62:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def");$def($def.P,"String",{repeat:function repeat(count){var str=String($.assertDefined(this)),res="",n=$.toInteger(count);if(n<0||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res}})},{"./$":21,"./$.def":12}],63:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def");$def($def.P,"String",{startsWith:function startsWith(searchString){if(cof(searchString)=="RegExp")throw TypeError();var that=String($.assertDefined(this)),index=$.toLength(Math.min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}})},{"./$":21,"./$.cof":6,"./$.def":12}],64:[function(require,module,exports){"use strict";var $=require("./$"),setTag=require("./$.cof").set,uid=require("./$.uid"),$def=require("./$.def"),keyOf=require("./$.keyof"),enumKeys=require("./$.enum-keys"),assertObject=require("./$.assert").obj,has=$.has,$create=$.create,getDesc=$.getDesc,setDesc=$.setDesc,desc=$.desc,getNames=$.getNames,toObject=$.toObject,Symbol=$.g.Symbol,setter=false,TAG=uid("tag"),HIDDEN=uid("hidden"),SymbolRegistry={},AllSymbols={},useNative=$.isFunction(Symbol);function wrap(tag){var sym=AllSymbols[tag]=$.set($create(Symbol.prototype),TAG,tag);$.DESC&&setter&&setDesc(Object.prototype,tag,{configurable:true,set:function(value){if(has(this,HIDDEN)&&has(this[HIDDEN],tag))this[HIDDEN][tag]=false;setDesc(this,tag,desc(1,value))}});return sym}function defineProperty(it,key,D){if(D&&has(AllSymbols,key)){if(!D.enumerable){if(!has(it,HIDDEN))setDesc(it,HIDDEN,desc(1,{}));it[HIDDEN][key]=true}else{if(has(it,HIDDEN)&&it[HIDDEN][key])it[HIDDEN][key]=false;D.enumerable=false}}return setDesc(it,key,D)}function defineProperties(it,P){assertObject(it);var keys=enumKeys(P=toObject(P)),i=0,l=keys.length,key;while(l>i)defineProperty(it,key=keys[i++],P[key]);return it}function create(it,P){return P===undefined?$create(it):defineProperties($create(it),P)}function getOwnPropertyDescriptor(it,key){var D=getDesc(it=toObject(it),key);if(D&&has(AllSymbols,key)&&!(has(it,HIDDEN)&&it[HIDDEN][key]))D.enumerable=true;return D}function getOwnPropertyNames(it){var names=getNames(toObject(it)),result=[],i=0,key;while(names.length>i)if(!has(AllSymbols,key=names[i++])&&key!=HIDDEN)result.push(key);return result}function getOwnPropertySymbols(it){var names=getNames(toObject(it)),result=[],i=0,key;while(names.length>i)if(has(AllSymbols,key=names[i++]))result.push(AllSymbols[key]);return result}if(!useNative){Symbol=function Symbol(description){if(this instanceof Symbol)throw TypeError("Symbol is not a constructor");return wrap(uid(description))};$.hide(Symbol.prototype,"toString",function(){return this[TAG]});$.create=create;$.setDesc=defineProperty;$.getDesc=getOwnPropertyDescriptor;$.setDescs=defineProperties;$.getNames=getOwnPropertyNames;$.getSymbols=getOwnPropertySymbols}var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},keyFor:function keyFor(key){return keyOf(SymbolRegistry,key)},useSetter:function(){setter=true},useSimple:function(){setter=false}};$.each.call(("hasInstance,isConcatSpreadable,iterator,match,replace,search,"+"species,split,toPrimitive,toStringTag,unscopables").split(","),function(it){var sym=require("./$.wks")(it);symbolStatics[it]=useNative?sym:wrap(sym)});setter=true;$def($def.G+$def.W,{Symbol:Symbol});$def($def.S,"Symbol",symbolStatics);$def($def.S+$def.F*!useNative,"Object",{create:create,defineProperty:defineProperty,defineProperties:defineProperties,getOwnPropertyDescriptor:getOwnPropertyDescriptor,getOwnPropertyNames:getOwnPropertyNames,getOwnPropertySymbols:getOwnPropertySymbols});setTag(Symbol,"Symbol");setTag(Math,"Math",true);setTag($.g.JSON,"JSON",true)},{"./$":21,"./$.assert":4,"./$.cof":6,"./$.def":12,"./$.enum-keys":13,"./$.keyof":22,"./$.uid":30,"./$.wks":32}],65:[function(require,module,exports){"use strict";var $=require("./$"),weak=require("./$.collection-weak"),leakStore=weak.leakStore,ID=weak.ID,WEAK=weak.WEAK,has=$.has,isObject=$.isObject,isFrozen=Object.isFrozen||$.core.Object.isFrozen,tmp={};var WeakMap=require("./$.collection")("WeakMap",{get:function get(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[ID]]}},set:function set(key,value){return weak.def(this,key,value)}},weak,true,true);if($.FW&&(new WeakMap).set((Object.freeze||Object)(tmp),7).get(tmp)!=7){$.each.call(["delete","has","get","set"],function(key){var method=WeakMap.prototype[key];WeakMap.prototype[key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result}return method.call(this,a,b)}})}},{"./$":21,"./$.collection":10,"./$.collection-weak":9}],66:[function(require,module,exports){"use strict";var weak=require("./$.collection-weak");require("./$.collection")("WeakSet",{add:function add(value){return weak.def(this,value,true)}},weak,false,true)},{"./$.collection":10,"./$.collection-weak":9}],67:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"Array",{includes:require("./$.array-includes")(true)});require("./$.unscope")("includes")},{"./$.array-includes":2,"./$.def":12,"./$.unscope":31}],68:[function(require,module,exports){require("./$.collection-to-json")("Map")},{"./$.collection-to-json":8}],69:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),ownKeys=require("./$.own-keys");$def($def.S,"Object",{getOwnPropertyDescriptors:function getOwnPropertyDescriptors(object){var O=$.toObject(object),result={};$.each.call(ownKeys(O),function(key){$.setDesc(result,key,$.desc(0,$.getDesc(O,key)))});return result}})},{"./$":21,"./$.def":12,"./$.own-keys":23}],70:[function(require,module,exports){var $=require("./$"),$def=require("./$.def");function createObjectToArray(isEntries){return function(object){var O=$.toObject(object),keys=$.getKeys(O),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$def($def.S,"Object",{values:createObjectToArray(false),entries:createObjectToArray(true)})},{"./$":21,"./$.def":12}],71:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"RegExp",{escape:require("./$.replacer")(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})},{"./$.def":12,"./$.replacer":25}],72:[function(require,module,exports){require("./$.collection-to-json")("Set")},{"./$.collection-to-json":8}],73:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"String",{at:require("./$.string-at")(true)})},{"./$.def":12,"./$.string-at":28}],74:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),$Array=$.core.Array||Array,statics={};function setStatics(keys,length){$.each.call(keys.split(","),function(key){if(length==undefined&&key in $Array)statics[key]=$Array[key];else if(key in[])statics[key]=require("./$.ctx")(Function.call,[][key],length)})}setStatics("pop,reverse,shift,keys,values,entries",1);setStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$def($def.S,"Array",statics)},{"./$":21,"./$.ctx":11,"./$.def":12}],75:[function(require,module,exports){require("./es6.array.iterator");var $=require("./$"),Iterators=require("./$.iter").Iterators,ITERATOR=require("./$.wks")("iterator"),ArrayValues=Iterators.Array,NodeList=$.g.NodeList;if($.FW&&NodeList&&!(ITERATOR in NodeList.prototype)){$.hide(NodeList.prototype,ITERATOR,ArrayValues)}Iterators.NodeList=ArrayValues},{"./$":21,"./$.iter":20,"./$.wks":32,"./es6.array.iterator":39}],76:[function(require,module,exports){var $def=require("./$.def"),$task=require("./$.task");$def($def.G+$def.B,{setImmediate:$task.set,clearImmediate:$task.clear})},{"./$.def":12,"./$.task":29}],77:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),invoke=require("./$.invoke"),partial=require("./$.partial"),navigator=$.g.navigator,MSIE=!!navigator&&/MSIE .\./.test(navigator.userAgent);function wrap(set){return MSIE?function(fn,time){return set(invoke(partial,[].slice.call(arguments,2),$.isFunction(fn)?fn:Function(fn)),time)}:set}$def($def.G+$def.B+$def.F*MSIE,{setTimeout:wrap($.g.setTimeout),setInterval:wrap($.g.setInterval)})},{"./$":21,"./$.def":12,"./$.invoke":16,"./$.partial":24}],78:[function(require,module,exports){require("./modules/es5");require("./modules/es6.symbol");require("./modules/es6.object.assign");require("./modules/es6.object.is");require("./modules/es6.object.set-prototype-of");require("./modules/es6.object.to-string");require("./modules/es6.object.statics-accept-primitives");require("./modules/es6.function.name");require("./modules/es6.number.constructor");require("./modules/es6.number.statics");require("./modules/es6.math");require("./modules/es6.string.from-code-point");require("./modules/es6.string.raw");require("./modules/es6.string.iterator");require("./modules/es6.string.code-point-at");require("./modules/es6.string.ends-with");require("./modules/es6.string.includes");require("./modules/es6.string.repeat");require("./modules/es6.string.starts-with");require("./modules/es6.array.from");require("./modules/es6.array.of");require("./modules/es6.array.iterator");require("./modules/es6.array.species");require("./modules/es6.array.copy-within");require("./modules/es6.array.fill");require("./modules/es6.array.find");require("./modules/es6.array.find-index");require("./modules/es6.regexp");require("./modules/es6.promise");require("./modules/es6.map");require("./modules/es6.set");require("./modules/es6.weak-map");require("./modules/es6.weak-set");require("./modules/es6.reflect");require("./modules/es7.array.includes");require("./modules/es7.string.at");require("./modules/es7.regexp.escape");require("./modules/es7.object.get-own-property-descriptors");require("./modules/es7.object.to-array");require("./modules/es7.map.to-json");require("./modules/es7.set.to-json");require("./modules/js.array.statics");require("./modules/web.timers");require("./modules/web.immediate");require("./modules/web.dom.iterable");module.exports=require("./modules/$").core},{"./modules/$":21,"./modules/es5":33,"./modules/es6.array.copy-within":34,"./modules/es6.array.fill":35,"./modules/es6.array.find":37,"./modules/es6.array.find-index":36,"./modules/es6.array.from":38,"./modules/es6.array.iterator":39,"./modules/es6.array.of":40,"./modules/es6.array.species":41,"./modules/es6.function.name":42,"./modules/es6.map":43,"./modules/es6.math":44,"./modules/es6.number.constructor":45,"./modules/es6.number.statics":46,"./modules/es6.object.assign":47,"./modules/es6.object.is":48,"./modules/es6.object.set-prototype-of":49,"./modules/es6.object.statics-accept-primitives":50,"./modules/es6.object.to-string":51,"./modules/es6.promise":52,"./modules/es6.reflect":53,"./modules/es6.regexp":54,"./modules/es6.set":55,"./modules/es6.string.code-point-at":56,"./modules/es6.string.ends-with":57,"./modules/es6.string.from-code-point":58,"./modules/es6.string.includes":59,"./modules/es6.string.iterator":60,"./modules/es6.string.raw":61,"./modules/es6.string.repeat":62,"./modules/es6.string.starts-with":63,"./modules/es6.symbol":64,"./modules/es6.weak-map":65,"./modules/es6.weak-set":66,"./modules/es7.array.includes":67,"./modules/es7.map.to-json":68,"./modules/es7.object.get-own-property-descriptors":69,"./modules/es7.object.to-array":70,"./modules/es7.regexp.escape":71,"./modules/es7.set.to-json":72,"./modules/es7.string.at":73,"./modules/js.array.statics":74,"./modules/web.dom.iterable":75,"./modules/web.immediate":76,"./modules/web.timers":77}],79:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryLocsList){var generator=Object.create((outerFn||Generator).prototype);generator._invoke=makeInvokeMethod(innerFn,self||null,new Context(tryLocsList||[]));return generator}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryLocsList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryLocsList);var callNext=step.bind(generator,"next");var callThrow=step.bind(generator,"throw");function step(method,arg){var record=tryCatch(generator[method],generator,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function makeInvokeMethod(innerFn,self,context){ var state=GenStateSuspendedStart;return function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){if(method==="return"||method==="throw"&&delegate.iterator[method]===undefined){context.delegate=null;var returnMethod=delegate.iterator["return"];if(returnMethod){var record=tryCatch(returnMethod,delegate.iterator,arg);if(record.type==="throw"){method="throw";arg=record.arg;continue}}if(method==="return"){continue}}var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;method="throw";arg=record.arg}}}}function defineGeneratorMethod(method){Gp[method]=function(arg){return this._invoke(method,arg)}}defineGeneratorMethod("next");defineGeneratorMethod("throw");defineGeneratorMethod("return");Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(locs){var entry={tryLoc:locs[0]};if(1 in locs){entry.catchLoc=locs[1]}if(2 in locs){entry.finallyLoc=locs[2];entry.afterLoc=locs[3]}this.tryEntries.push(entry)}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal";delete record.arg;entry.completion=record}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}];tryLocsList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},abrupt:function(type,arg){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev<entry.finallyLoc){var finallyEntry=entry;break}}if(finallyEntry&&(type==="break"||type==="continue")&&finallyEntry.tryLoc<=arg&&arg<=finallyEntry.finallyLoc){finallyEntry=null}var record=finallyEntry?finallyEntry.completion:{};record.type=type;record.arg=arg;if(finallyEntry){this.next=finallyEntry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record,afterLoc){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}else if(record.type==="normal"&&afterLoc){this.next=afterLoc}return ContinueSentinel},finish:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc){return this.complete(entry.completion,entry.afterLoc)}}},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:typeof self==="object"?self:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[1]);
RNApp/app/index.js
spencercarli/react-native-meteor-boilerplate
import React from 'react'; import Meteor, { createContainer } from 'react-native-meteor'; import { AuthStack, Tabs } from './config/routes'; import Loading from './components/Loading'; import settings from './config/settings'; Meteor.connect(settings.METEOR_URL); const RNApp = (props) => { const { status, user, loggingIn } = props; if (status.connected === false || loggingIn) { return <Loading />; } else if (user !== null) { return <Tabs />; } return <AuthStack />; }; RNApp.propTypes = { status: React.PropTypes.object, user: React.PropTypes.object, loggingIn: React.PropTypes.bool, }; export default createContainer(() => { return { status: Meteor.status(), user: Meteor.user(), loggingIn: Meteor.loggingIn(), }; }, RNApp);
packages/material-ui-icons/src/BatteryCharging20.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M11 20v-3H7v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17h-4.4L11 20z" /><path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h4v-2.5H9L13 7v5.5h2L12.6 17H17V5.33C17 4.6 16.4 4 15.67 4z" /></React.Fragment> , 'BatteryCharging20');
node_modules/react-icons/fa/quote-left.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const FaQuoteLeft = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m18.6 21.4v8.6q0 1.8-1.2 3t-3 1.3h-8.6q-1.8 0-3-1.3t-1.3-3v-15.7q0-2.3 0.9-4.4t2.4-3.7 3.7-2.4 4.4-0.9h1.5q0.5 0 1 0.4t0.4 1v2.8q0 0.6-0.4 1t-1 0.5h-1.5q-2.3 0-4 1.6t-1.7 4.1v0.7q0 0.9 0.6 1.5t1.6 0.6h5q1.7 0 3 1.3t1.2 3z m20 0v8.6q0 1.8-1.2 3t-3 1.3h-8.6q-1.8 0-3-1.3t-1.3-3v-15.7q0-2.3 0.9-4.4t2.4-3.7 3.7-2.4 4.4-0.9h1.5q0.5 0 1 0.4t0.4 1v2.8q0 0.6-0.4 1t-1 0.5h-1.5q-2.3 0-4 1.6t-1.7 4.1v0.7q0 0.9 0.6 1.5t1.6 0.6h5q1.7 0 3 1.3t1.2 3z"/></g> </Icon> ) export default FaQuoteLeft
docs/src/components/AppWrapper.js
mattBlackDesign/react-materialize
import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router-dom'; class AppWrapper extends React.Component { componentDidUpdate (prevProps) { if (this.props.location !== prevProps.location) { window.scrollTo(0, 0); } } render () { const { children, ...otherProps } = this.props; return ( <div> { React.Children.map(children, child => React.cloneElement(child, { ...otherProps })) } </div> ) } } AppWrapper.propTypes = { children: PropTypes.any.isRequired, location: PropTypes.any }; export default withRouter(AppWrapper);
test/testUtils.js
YouCanBookMe/react-datetime
import React from 'react'; // eslint-disable-line no-unused-vars import { mount, shallow } from 'enzyme'; import Datetime from '../dist/react-datetime.cjs'; // eslint-disable-line no-unused-vars const _simulateClickOnElement = (element) => { if (element.length === 0) { // eslint-disable-next-line no-console console.warn('Element not clicked since it doesn\'t exist'); return; } return element.simulate('click'); }; module.exports = { createDatetime: (props) => { return mount(<Datetime {...props} />); }, createDatetimeShallow: (props) => { return shallow(<Datetime {...props} />); }, /* * Click Simulations */ openDatepicker: (datetime) => { datetime.find('.form-control').simulate('focus'); }, openDatepickerByClick: datetime => { datetime.find('.form-control').simulate('click'); }, clickOnElement: (element) => { return _simulateClickOnElement(element); }, clickNthDay: (datetime, n) => { return _simulateClickOnElement(datetime.find('.rdtDay').at(n)); }, clickNthMonth: (datetime, n) => { return _simulateClickOnElement(datetime.find('.rdtMonth').at(n)); }, clickNthYear: (datetime, n) => { return _simulateClickOnElement(datetime.find('.rdtYear').at(n)); }, clickClassItem: (datetime, cn, n) => { return _simulateClickOnElement( datetime.find(cn).at(n) ); }, /* * Boolean Checks */ isOpen: (datetime) => { var open = datetime.find('.rdt.rdtOpen').length > 0; return open; }, isDayView: (datetime) => { return datetime.find('.rdtPicker .rdtDays').length > 0; }, isMonthView: (datetime) => { return datetime.find('.rdtPicker .rdtMonths').length > 0; }, isYearView: (datetime) => { return datetime.find('.rdtPicker .rdtYears').length > 0; }, isTimeView: (datetime) => { return datetime.find('.rdtPicker .rdtTime').length > 0; }, /* * Change Time Values * * These functions only work when the time view is open */ increaseHour: (datetime) => { datetime.find('.rdtCounter .rdtBtn').at(0).simulate('mouseDown'); }, decreaseHour: (datetime) => { datetime.find('.rdtCounter .rdtBtn').at(1).simulate('mouseDown'); }, increaseMinute: (datetime) => { datetime.find('.rdtCounter .rdtBtn').at(2).simulate('mouseDown'); }, decreaseMinute: (datetime) => { datetime.find('.rdtCounter .rdtBtn').at(3).simulate('mouseDown'); }, increaseSecond: (datetime) => { datetime.find('.rdtCounter .rdtBtn').at(4).simulate('mouseDown'); }, decreaseSecond: (datetime) => { datetime.find('.rdtCounter .rdtBtn').at(5).simulate('mouseDown'); }, /* * Get Values */ getNthDay: (datetime, n) => { return datetime.find('.rdtDay').at(n); }, getNthMonth: (datetime, n) => { return datetime.find('.rdtMonth').at(n); }, getNthYear: (datetime, n) => { return datetime.find('.rdtYear').at(n); }, getHours: (datetime) => { return datetime.find('.rdtCount').at(0).text(); }, getMinutes: (datetime) => { return datetime.find('.rdtCount').at(1).text(); }, getSeconds: (datetime) => { return datetime.find('.rdtCount').at(2).text(); }, getInputValue: (datetime) => { return datetime.find('.rdt > .form-control').getDOMNode().value; }, getViewDateValue: (datetime) => { return datetime.find('.rdtSwitch').getDOMNode().innerHTML; } };
src/svg-icons/device/signal-cellular-1-bar.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellular1Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M2 22h20V2z"/><path d="M12 12L2 22h10z"/> </SvgIcon> ); DeviceSignalCellular1Bar = pure(DeviceSignalCellular1Bar); DeviceSignalCellular1Bar.displayName = 'DeviceSignalCellular1Bar'; DeviceSignalCellular1Bar.muiName = 'SvgIcon'; export default DeviceSignalCellular1Bar;
src/components/Header/Header.js
cheshire137/steamfit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; import s from './Header.scss'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; import Navigation from '../Navigation'; @withStyles(s) class Header extends Component { render() { return ( <div className={s.root}> <div className={s.container}> <Navigation className={s.nav} /> <div className={s.banner}> <h1 className={s.bannerTitle}> <Link className={s.brand} to="/"> SteamFit </Link> </h1> <p className={s.bannerDesc}>Correlate your Steam activity with your Fitbit activity.</p> </div> </div> </div> ); } } export default Header;
ajax/libs/yui/3.7.0pr2/simpleyui/simpleyui.js
dhowe/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 * @main 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(); Configuring the YUI object: YUI({ debug: true, combine: false }).use('node', function(Y) { //Node is ready to use }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. @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 GlobalConfig @type {Object} @global @static @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/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', 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, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; 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; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); 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.5.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, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } 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, el, 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 = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'], loaderExtras: ['loader-rollup', 'loader-yui3'], 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-davglass" 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-davglass/yui-davglass.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, '_').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 || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } 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 || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** * 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 && 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 }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @param {Array} r The array of modules to attach * @param {Boolean} [moot=false] Don't throw a warning if the module is not attached * @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, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, def, go, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); 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 ^davglass 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); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; for (j in loader.moduleInfo[name].expanded_map) { if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } 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) { if (Y.config.throwFail) { mod.fn(Y, name); } else { 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; }, /** * Delays the `use` callback until another event has taken place. Like: window.onload, domready, contentready, available. * @private * @method _delayCallback * @param {Callback} cb The original `use` callback * @param {String|Object} until Either an event (load, domready) or an Object containing event/args keys for contentready/available */ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } return function() { var args = arguments; Y._use(mod, function() { Y.on(until.event, function() { args[1].delayUntil = until.event; cb.apply(Y, args); }, until.args); }); }; }, /** * 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|Array} 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. * @param callback.Y {YUI} The `YUI` instance created for this sandbox * @param callback.status {Object} Object containing `success`, `msg` and `data` properties * * @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, a = [], 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(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } 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._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) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { 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, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; 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 ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { 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()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // 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._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { 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'); } 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) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { 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 a method on a YUI <em>instance</em>, 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 with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace("really.long.nested.namespace"); <em>Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function.</em> @method namespace @param {String} namespace* namespaces to create. @return {Object} A reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present 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] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } 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 controlled by * the `throwFail` configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown. If an `errorFn` is specified in the config * it must return `true` to keep the error from being thrown. * @method error * @param msg {String} the error message. * @param e {Error|String} Optional JS error that was caught, or an error string. * @param src Optional additional info (passed to `Y.config.errorFn` and `Y.message`) * and `throwFail` is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // 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 * @param o {Object} The object to check. * @param type {Object} The class to check against. * @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]; } } /** Static method on the Global YUI object to apply a config to all YUI instances. It's main use case is "mashups" where several third party scripts are trying to write to a global YUI config at the same time. This way they can all call `YUI.applyConfig({})` instead of overwriting other scripts configs. @static @since 3.5.0 @method applyConfig @param {Object} o the configuration object. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function(Y) { //Module davglass will be available here.. }); */ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // 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 */ /** * Turns on writing Ylog messages to the browser console. * * @property debug * @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 list). * * @property core * @type Array * @default [ get,features,intl-base,yui-log,yui-later,loader-base, loader-rollup, loader-yui3 ] */ /** * 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: '/mymod1/mymod1.js' * }, * mymod2: { * requires: ['mymod1'], * fullpath: '/mymod2/mymod2.js' * }, * mymod3: '/js/mymod3.js', * mycssmod: '/css/mycssmod.css' * } * * * @property modules * @type object */ /** * Aliases are dynamic groups of modules that can be used as * shortcuts. * * YUI({ * aliases: { * davglass: [ 'node', 'yql', 'dd' ], * mine: [ 'davglass', 'autocomplete'] * } * }).use('mine', function(Y) { * //Node, YQL, DD &amp; AutoComplete available here.. * }); * * @property aliases * @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 comboSeperator to use with this group's combo handler * comboSep: ';', * * // The maxURLLength for this server * maxURLLength: 500, * * // 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.9.0 */ /** * 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 4 */ /** * 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. Returning `true` from this * function will stop the Error from being thrown. * * @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 */ /** * Whether or not YUI should use native ES5 functionality when available for * features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will * always use its own fallback implementations instead of relying on ES5 * functionality, even when it's available. * * @property useNativeES5 * @type Boolean * @default true * @since 3.5.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property delayUntil @type String|Object @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function(Y) { //This will not fire until 'domeready' }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args: '#foo' } }, function(Y) { //This will not fire until '#foo' is // available in the DOM }); */ YUI.add('yui-base', function (Y, NAME) { /* * 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, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * 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 = L._isNative(Array.isArray) ? 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'; }; /** * 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); }; /** * <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 * &nbsp; * 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 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'; }; /** * 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; } }; /** * 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(); }; /** * 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 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+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @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'); }; /** @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; /** 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 = Lang._isNative(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. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } 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 = Lang._isNative(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; }; /** 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; }; /** * 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) : String(arg); if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** 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 i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. 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 {Number} [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 // property existence check 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; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; 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; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; 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 Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, 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 = Lang._isNative(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'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * 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 = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { 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) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * 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 (!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(Object(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 on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {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, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 0, /** * 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 Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * 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, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0 }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } 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; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // 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; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).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.os = 'ios'; 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]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } 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) if (/Opera/.test(ua)) { 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+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } 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]); } } } } } } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process == 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","router","view","view-node-map"], "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"], "controller": ["router"], "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-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatable-deprecated": ["datatable-base-deprecated","datatable-datasource-deprecated","datatable-sort-deprecated","datatable-scroll-deprecated"], "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","editor-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-touch","event-move","event-flick","event-valuechange"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "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-skin","widget-uievents"] }; }, '@VERSION@', {"use": ["yui-base", "get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { } else { } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { } else { } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { } else { } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes async: doc && doc.createElement('script').async === true, // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+. cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(function () { item.callback && item.callback.apply(this, arguments); Get._pending = null; Get._next(); }); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._waiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._waiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } for (i = 0, len = requests.length; i < len; ++i) { req = self.requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, cachedNode, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. node.onerror = onError; node.onload = onLoad; // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this._waiting += 1; this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._waiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._waiting -= 1; this._next(); } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ 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(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } 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.js */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style); } return false; }, "trigger": "app-transitions" }); // 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" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "test": function(Y) { return ((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.chrome && Y.UA.chrome < 6)); }, "trigger": "dd-drag" }); // dom-style-ie add('load', '3', { "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" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "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" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "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" }); // graphics-vml-default add('load', '11', { "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" }); // history-hash-ie add('load', '12', { "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" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // scrollview-base-ie add('load', '14', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '15', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '16', { "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" }); // widget-base-ie add('load', '17', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * 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, NAME) { /** * 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 src = src || ""; if (typeof src !== "undefined") { 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, NAME) { /** * 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) : NO_ARGS; o = o || Y.config.win || Y; 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('yui', function (Y, NAME) {}, '@VERSION@', {"use": ["yui-base", "get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('oop', function (Y, NAME) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Copies object properties from the supplier to the receiver. If the target has * the property, and the property is an object, the target object will be * augmented with the supplier's value. * * @method aggregate * @param {Object} receiver Object to receive the augmentation. * @param {Object} supplier Object that supplies the properties with which to * augment the receiver. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver * will be overwritten if found on the supplier. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this * list will be applied to the receiver. * @return {Object} Augmented object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** * Deep object/array copy. Function clones are actually * wrappers around the original function. * Array-like objects are treated as arrays. * Primitives are returned untouched. Optionally, a * function can be provided to handle other data types, * filter keys, validate values, etc. * * NOTE: Cloning a non-trivial object is a reasonably heavy operation, due to * the need to recurrsively iterate down non-primitive properties. Clone * should be used only when a deep clone down to leaf level properties * is explicitly required. * * In many cases (for example, when trying to isolate objects used as * hashes for configuration properties), a shallow copy, using Y.merge is * normally sufficient. If more than one level of isolation is required, * Y.merge can be used selectively at each level which needs to be * isolated from the original without going all the way to leaf properties. * * @method clone * @param {object} o what to clone. * @param {boolean} safe if true, objects will not have prototype * items from the source. If false, they will. In this case, the * original is initially protected, but the clone is not completely * immune from changes to the source object prototype. Also, cloned * prototype items that are deleted from the clone will result * in the value of the source prototype being exposed. If operating * on a non-safe clone, items should be nulled out rather than deleted. * @param {function} f optional function to apply to each item in a * collection; it will be executed prior to applying the value to * the new object. Return false to prevent the copy. * @param {object} c optional execution context for f. * @param {object} owner Owner object passed when clone is iterating * an object. Used to set up context for cloned functions. * @param {object} cloned hash of previously cloned objects to avoid * multiple clones. * @return {Array|Object} the cloned object. */ Y.clone = function(o, safe, f, c, owner, cloned) { if (!L.isObject(o)) { return o; } // @todo cloning YUI instances doesn't currently work if (Y.instanceOf(o, YUI)) { return o; } var o2, marked = cloned || {}, stamp, yeach = Y.each; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } // #2528250 don't try to clone element properties if (!o.addEventListener && !o.attachEvent) { yeach(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); } if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ 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(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } 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.js */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style); } return false; }, "trigger": "app-transitions" }); // 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" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "test": function(Y) { return ((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.chrome && Y.UA.chrome < 6)); }, "trigger": "dd-drag" }); // dom-style-ie add('load', '3', { "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" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "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" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "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" }); // graphics-vml-default add('load', '11', { "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" }); // history-hash-ie add('load', '12', { "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" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // scrollview-base-ie add('load', '14', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '15', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '16', { "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" }); // widget-base-ie add('load', '17', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dom-core', function (Y, NAME) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], // IE < 8 throws on node.contains(textNode) supportsContainsTextNode = (function() { var node = Y.config.doc.createElement('div'), textNode = node.appendChild(Y.config.doc.createTextNode('')), result = false; try { result = node.contains(textNode); } catch(e) {} return result; })(), /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @main dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, getId: function(node) { var id; // HTMLElement returned from FORM when INPUT name === "id" // IE < 8: HTMLCollection returned when INPUT id === "id" // via both getAttribute and form.id if (node.id && !node.id.tagName && !node.id.item) { id = node.id; } else if (node.attributes && node.attributes.id) { id = node.attributes.id.value; } return id; }, setId: function(node, id) { if (node.setAttribute) { node.setAttribute('id', id); } else { node.id = id; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf, stopFn) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf, stopFn) { var ancestor = element, ret = []; while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) { testSelf = false; if (ancestor) { ret.unshift(ancestor); if (stopFn && stopFn(ancestor)) { return ret; } } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all, stopAt) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } if (stopAt && stopAt(element)) { return null; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS] && // IE < 8 throws on node.contains(textNode) so fall back to brute. // Falling back for other nodeTypes as well. (needle[NODE_TYPE] === 1 || supportsContainsTextNode)) { ret = element[CONTAINS](needle); } else if (element[COMPARE_DOCUMENT_POSITION]) { // Match contains behavior (node.contains(node) === true). // Needed for Firefox < 4. if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } else { ret = Y_DOM._bruteContains(element, needle); } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.alert && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@', {"requires": ["oop", "features"]}); YUI.add('dom-base', function (Y, NAME) { /** * @for DOM * @module dom */ var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } } } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { } else if (node.selectedIndex > -1) { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _children: function(node, tag) { var i = 0, children = node.children, childNodes, hasComments, child; if (children && children.tags) { // use tags filter when possible if (tag) { children = node.children.tags(tag); } else { // IE leaks comments into children hasComments = children.tags('!').length; } } if (!children || (!children.tags && tag) || hasComments) { childNodes = children || node.childNodes; children = []; while ((child = childNodes[i++])) { if (child.nodeType === 1) { if (!tag || tag === child.tagName) { children.push(child); } } } } return children || []; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (newNode && where.parentNode) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': if (newNode) { nodeParent.insertBefore(newNode, node); } break; case 'after': if (newNode) { if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } } break; default: if (newNode) { node.appendChild(newNode); } } } } else if (newNode) { node.appendChild(newNode); } return ret; }, wrap: function(node, html) { var parent = (html && html.nodeType) ? html : Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = Y.DOM._children(frag, 'tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; } creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@', {"requires": ["dom-core"]}); YUI.add('dom-style', function (Y, NAME) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', TRANSFORMORIGIN = 'transformOrigin', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('dom-style-ie', function (Y, NAME) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@', {"requires": ["dom-style"]}); YUI.add('dom-screen', function (Y, NAME) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, mode, box, offX, offY, doc, win, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; mode = doc[COMPAT_MODE]; if (mode !== _BACK_COMPAT) { rootNode = doc[DOCUMENT_ELEMENT]; } else { rootNode = doc.body; } // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { win = doc.defaultView; // inline scroll calc for perf if (win && 'pageXOffset' in win) { scrollLeft = win.pageXOffset; scrollTop = win.pageYOffset; } else { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); } if (Y.UA.ie) { // IE < 8, quirks, or compatMode if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) { offX = rootNode.clientLeft; offY = rootNode.clientTop; } } box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (offX || offY) { xy[0] -= offX; xy[1] -= offY; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** Gets the width of vertical scrollbars on overflowed containers in the body content. @method getScrollbarWidth @return {Number} Pixel width of a scrollbar in the current browser **/ getScrollbarWidth: Y.cached(function () { var doc = Y.config.doc, testNode = doc.createElement('div'), body = doc.getElementsByTagName('body')[0], // 0.1 because cached doesn't support falsy refetch values width = 0.1; if (body) { testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;"; testNode.appendChild(doc.createElement('p')).style.height = '1px'; body.insertBefore(testNode, body.firstChild); width = testNode.offsetWidth - testNode.clientWidth; body.removeChild(testNode); } return width; }, null, 0.1), /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Number} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Number} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } } else { } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Number} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Number} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passed nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node The node to get the region from * @param {Object} node2 The second node to get the region from or an Object literal of the region * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@', {"requires": ["dom-base", "dom-style"]}); YUI.add('selector-native', function (Y, NAME) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _types: { esc: { token: '\uE000', re: /\\[:\[\]\(\)#\.\'\>+~"]/gi }, attr: { token: '\uE001', re: /(\[[^\]]*\])/g }, pseudo: { token: '\uE002', re: /(\([^\)]*\))/g } }, useNative: true, _escapeId: function(id) { if (id) { id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1'); } return id; }, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } return (firstOnly) ? (ret[0] || null) : ret; }, _replaceSelector: function(selector) { var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc. attrs, pseudos; // first replace escaped chars, which could be present in attrs or pseudos selector = Y.Selector._replace('esc', selector); // then replace pseudos before attrs to avoid replacing :not([foo]) pseudos = Y.Selector._parse('pseudo', selector); selector = Selector._replace('pseudo', selector); attrs = Y.Selector._parse('attr', selector); selector = Y.Selector._replace('attr', selector); return { esc: esc, attrs: attrs, pseudos: pseudos, selector: selector } }, _restoreSelector: function(replaced) { var selector = replaced.selector; selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _replaceCommas: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; if (selector) { selector = selector.replace(/,/g, '\uE007'); replaced.selector = selector; selector = Y.Selector._restoreSelector(replaced); } return selector; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { if (selector.indexOf(',') > -1) { selector = Y.Selector._replaceCommas(selector); } var groups = selector.split('\uE007'), // split on replaced comma token queries = [], prefix = '', id, i, len; if (node) { // enforce for element scoping if (node.nodeType === 1) { // Elements only id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } prefix = '[id="' + id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, id, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); }, _parse: function(name, selector) { return selector.match(Y.Selector._types[name].re); }, _replace: function(name, selector) { var o = Y.Selector._types[name]; return selector.replace(o.re, o.token); }, _restore: function(name, selector, items) { if (items) { var token = Y.Selector._types[name].token, i, len; for (i = 0, len = items.length; i < len; ++i) { selector = selector.replace(token, items[i]); } } return selector; } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('selector', function (Y, NAME) { }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { this._kds = Y.CustomEvent.keepDeprecatedSubs; o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ if (this._kds) { this.subscribers = {}; } /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ this._subscribers = []; /** * 'After' subscribers * @property afters * @type Subscriber {} */ if (this._kds) { this.afters = {}; } /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ this._afters = []; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.subCount = 0; // this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this._subscribers.length, a = this._afters.length, sib = this.sibling; if (sib) { s += sib._subscribers.length; a += sib._afters.length; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = this._subscribers, a = this._afters, sib = this.sibling; s = (sib) ? s.concat(sib._subscribers) : s.concat(); a = (sib) ? a.concat(sib._afters) : a.concat(); return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this._afters.push(s); } else { this._subscribers.push(s); } if (this._kds) { if (when == AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = nativeSlice.call(arguments, 0); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; i = YArray.indexOf(subs, s, 0); } if (s && subs[i] === s) { subs.splice(i, 1); } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; events = edata.events; ce = events[type]; this._monitor('publish', type, { args: arguments }); if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // TODO: Lazy publish goes here. defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, defaults); if (opts) { ce.applyConfig(opts, true); } events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), yuievt = this._yuievt, pre = yuievt.config.prefix, ce, ret, ce2, args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } this._monitor('fire', (ce || t), { args: args }); // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]}); YUI.add('event-custom-complex', function (Y, NAME) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, key, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype, mixFacadeProps = function(facade, payload) { var p; for (p in payload) { if (!(FACADE_KEYS.hasOwnProperty(p))) { facade[p] = payload[p]; } } }; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || EMPTY; this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property _type * @type string * @private */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.mix(Y.EventFacade.prototype, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret, events, subs, postponed, self = this, host = self.host || self, next, oldbubble; if (self.stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != self.stack.next.type) { self.log('queue ' + self.type); self.stack.queue.push([self, args]); return true; } } es = self.stack || { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; if (self.stoppedFn) { events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } if (subs[0]) { self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; es.bubbling = self.type; if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); es.bubbling = oldbubble; } if (self.prevented) { if (self.preventedFn) { self.preventedFn.apply(host, args); } } else if (self.defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { postponed = subs[1]; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } self.stack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } // Kill the cached facade to free up memory. // Otherwise we have the facade from the last fire, sitting around forever. self._facade = null; return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { // protect the event facade properties mixFacadeProps(ef, o); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } if (this.events) { this.events.fire('stopped', this); } }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } if (this.events) { this.events.fire('stopped', this); } }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = {}; // Flatten whitelist for (key in FACADE) { FACADE_KEYS[key] = true; } }, '@VERSION@', {"requires": ["event-custom-base"]}); YUI.add('node-core', function (Y, NAME) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @main node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @type DOMNode * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @type String * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @type Object * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Node | HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Node | NodeList | Any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && args[0]._node) { args[0] = args[0]._node; } if (args[1] && args[1]._node) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { DATA_PREFIX: 'data-', /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (refNode && refNode._node) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @param {String | Function} stopFn optional A selector string or boolean * method to indicate when the search should stop. The search bails when the function * returns true or the selector matches. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf, stopFn) { // testSelf is optional, check for stopFn as 2nd arg if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf, stopFn) { if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a Node instance of nodes based on the given CSS selector. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node} A Node instance for the matching HTMLElement. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; return nodelist; }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Node | HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } else { // purge in case added by other means Y.Event.purgeElement(node); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && a._node) { a = a._node; } if (b && b._node) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor * @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList. */ var NodeList = function(nodes) { var tmp = []; if (nodes) { if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (nodes._node) { // Y.Node nodes = [nodes._node]; } else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes || []; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { _invoke: function(method, args, getter) { var ret = (getter) ? [] : this; this.each(function(node) { var val = node[method].apply(node, args); if (getter) { ret.push(val); } }); return ret; }, /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return {Node} a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Node | DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance. Nulls internal node references, * removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to * remove listeners from the node's subtree (default is false) * @see Node.destroy */ 'destroy', /** * Called on each Node instance. Removes and destroys all of the nodes * within the node * @method empty * @chainable * @see Node.empty */ 'empty', /** * Called on each Node instance. Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * @see Node.remove */ 'remove', /** * Called on each Node instance. Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node} The last item in the NodeList. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node} The first item in the NodeList. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method unshift * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ // one-off implementation due to IE returning boolean, breaking chaining Y.Node.prototype.removeAttribute = function(attr) { var node = this._node; if (node) { node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive } return this; }; Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@', {"requires": ["dom-core", "selector"]}); YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @for Node * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { var name = this.DATA_PREFIX + name, node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '@VERSION@', {"requires": ["event-base", "node-core", "dom-base"]}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function (Y, NAME) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; // charCode is unknown in keyup, keydown. keyCode is unknown in keypress. // FF 3.6 - 8+? pass 0 for keyCode in keypress events. // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup. // Webkit and IE9+? duplicate charCode in keyCode. // Opera never sets charCode, always keyCode (though with the charCode). // IE6-8 don't set charCode or which. // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and // which=charCode in keypress. // // Moral of the story: (e.which || e.keyCode) will always return the // known code for that key event phase. e.keyCode is often different in // keypress from keydown and keyup. c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; // Fill in e.which for IE - implementers should always use this over // e.keyCode or e.charCode. this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event * @type {Native DOM Event} * @private */ /** The name of the event (e.g. "click") @property type @type {String} **/ /** `true` if the "alt" or "option" key is pressed. @property altKey @type {Boolean} **/ /** `true` if the shift key is pressed. @property shiftKey @type {Boolean} **/ /** `true` if the "Windows" key on a Windows keyboard, "command" key on an Apple keyboard, or "meta" key on other keyboards is pressed. @property metaKey @type {Boolean} **/ /** `true` if the "Ctrl" or "control" key is pressed. @property ctrlKey @type {Boolean} **/ /** * The X location of the event on the page (including scroll) * @property pageX * @type {Number} */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type {Number} */ /** * The X location of the event in the viewport * @property clientX * @type {Number} */ /** * The Y location of the event in the viewport * @property clientY * @type {Number} */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type {Number} */ /** * The charCode for key events. Same as keyCode * @property charCode * @type {Number} */ /** * The button that was pushed. 1 for left click, 2 for middle click, 3 for * right click. This is only reliably populated on `mouseup` events. * @property button * @type {Number} */ /** * The button that was pushed. Same as button. * @property which * @type {Number} */ /** * Node reference for the targeted element * @property target * @type {Node} */ /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type {Node} */ /** * Node reference to the relatedTarget * @property relatedTarget * @type {Node} */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type {Number} */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * @module event * @main event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !o.alert); } catch(ex) { return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.hasSubs()) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = Y.DOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { ret = Event.onAvailable(el, function() { ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = Y.DOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return Y.DOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; try { if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } } catch (e) { } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { executeItem(el, item); _avail[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); i = 0; len = children.length; for (; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {CustomEvent} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } try { add(win, "unload", onUnload); } catch(e) { } Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); })(); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@', {"requires": ["event-custom-base"]}); YUI.add('pluginhost-base', function (Y, NAME) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config if (this[ns].setAttrs) { this[ns].setAttrs(config); } } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namespace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { if (this[ns].destroy) { this[ns].destroy(); } delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('pluginhost-config', function (Y, NAME) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin * @for Plugin.Host */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes * @for Plugin.Host */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@', {"requires": ["pluginhost-base"]}); YUI.add('event-delegate', function (Y, NAME) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('node-event-delegate', function (Y, NAME) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@', {"requires": ["node-base", "event-delegate"]}); YUI.add('node-pluginhost', function (Y, NAME) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) /** * Adds a plugin to each node in the NodeList. * This will instantiate the plugin and attach it to the configured namespace on each node * @method plug * @for NodeList * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @chainable */ Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); return this; }; /** * Removes a plugin from all nodes in the NodeList. This will destroy the * plugin instance and delete the namespace each node. * @method unplug * @for NodeList * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @chainable */ Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); return this; }; }, '@VERSION@', {"requires": ["node-base", "pluginhost"]}); YUI.add('node-screen', function (Y, NAME) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config docWidth * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Node | HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@', {"requires": ["dom-screen", "node-base"]}); YUI.add('node-style', function (Y, NAME) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); }, '@VERSION@', {"requires": ["dom-style", "node-base"]}); YUI.add('querystring-stringify-simple', function (Y, NAME) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple * @for QueryString * @static */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; /** * <p>Converts a simple object to a Query String representation.</p> * <p>Nested objects, Arrays, and so on, are not supported.</p> * * @method stringify * @for QueryString * @public * @submodule querystring-stringify-simple * @param obj {Object} A single-level object to convert to a querystring. * @param cfg {Object} (optional) Configuration object. In the simple * module, only the arrayKey setting is * supported. When set to true, the key of an * array will have the '[]' notation appended * to the key;. * @static */ QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('io-base', function (Y, NAME) { /** Base IO functionality. Provides basic XHR transport support. @module io @submodule io-base @for IO **/ var // List of events that comprise the IO event lifecycle. EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'], // Whitelist of used XHR response object properties. XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'], win = Y.config.win, uid = 0; /** The IO class is a utility that brokers HTTP requests through a simplified interface. Specifically, it allows JavaScript to make HTTP requests to a resource without a page reload. The underlying transport for making same-domain requests is the XMLHttpRequest object. IO can also use Flash, if specified as a transport, for cross-domain requests. @class IO @constructor @param {Object} config Object of EventTarget's publish method configurations used to configure IO's events. **/ function IO (config) { var io = this; io._uid = 'io:' + uid++; io._init(config); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * A counter that increments for each transaction. * * @property _id * @private * @type {Number} */ _id: 0, /** * Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type {Object} */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * Object that stores timeout values for any transaction with a defined * "timeout" configuration property. * * @property _timeout * @private * @type {Object} */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(config) { var io = this, i, len; io.cfg = config || {}; Y.augment(io, Y.EventTarget); for (i = 0, len = EVENTS.length; i < len; ++i) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + EVENTS[i], config); } }, /** * Method that creates a unique transaction object for each request. * * @method _create * @private * @param {Object} cfg Configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {Number} id Transaction id * @return {Object} The transaction object */ _create: function(config, id) { var io = this, transaction = { id : Y.Lang.isNumber(id) ? id : io._id++, uid: io._uid }, alt = config.xdr ? config.xdr.use : null, form = config.form && config.form.upload ? 'iframe' : null, use; if (alt === 'native') { // Non-IE can use XHR level 2 and not rely on an // external transport. alt = Y.UA.ie ? 'xdr' : null; // Prevent "pre-flight" OPTIONS request by removing the // `X-Requested-With` HTTP header from CORS requests. This header // can be added back on a per-request basis, if desired. io.setHeader('X-Requested-With'); } use = alt || form; transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) : Y.merge(Y.IO.defaultTransport(), transaction); if (transaction.notify) { config.notify = function (e, t, c) { io.notify(e, t, c); }; } if (!use) { if (win && win.FormData && config.data instanceof win.FormData) { transaction.c.upload.onprogress = function (e) { io.progress(transaction, e, config); }; transaction.c.onload = function (e) { io.load(transaction, e, config); }; transaction.c.onerror = function (e) { io.error(transaction, e, config); }; transaction.upload = true; } } return transaction; }, _destroy: function(transaction) { if (win && !transaction.notify && !transaction.xdr) { if (XHR && !transaction.upload) { transaction.c.onreadystatechange = null; } else if (transaction.upload) { transaction.c.upload.onprogress = null; transaction.c.onload = null; transaction.c.onerror = null; } else if (Y.UA.ie && !transaction.e) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". transaction.c.abort(); } } transaction = transaction.c = null; }, /** * Method for creating and firing events. * * @method _evt * @private * @param {String} eventName Event to be published. * @param {Object} transaction Transaction object. * @param {Object} config Configuration data subset for event subscription. */ _evt: function(eventName, transaction, config) { var io = this, params, args = config['arguments'], emitFacade = io.cfg.emitFacade, globalEvent = "io:" + eventName, trnEvent = "io-trn:" + eventName; // Workaround for #2532107 this.detach(trnEvent); if (transaction.e) { transaction.c = { status: 0, statusText: transaction.e }; } // Fire event with parameters or an Event Facade. params = [ emitFacade ? { id: transaction.id, data: transaction.c, cfg: config, 'arguments': args } : transaction.id ]; if (!emitFacade) { if (eventName === EVENTS[0] || eventName === EVENTS[2]) { if (args) { params.push(args); } } else { if (transaction.evt) { params.push(transaction.evt); } else { params.push(transaction.c); } if (args) { params.push(args); } } } params.unshift(globalEvent); // Fire global events. io.fire.apply(io, params); // Fire transaction events, if receivers are defined. if (config.on) { params[0] = trnEvent; io.once(trnEvent, config.on[eventName], config.context || Y); io.fire.apply(io, params); } }, /** * Fires event "io:start" and creates, fires a transaction-specific * start event, if `config.on.start` is defined. * * @method start * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ start: function(transaction, config) { /** * Signals the start of an IO request. * @event io:start */ this._evt(EVENTS[0], transaction, config); }, /** * Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ complete: function(transaction, config) { /** * Signals the completion of the request-response phase of a * transaction. Response status and data are accessible, if * available, in this event. * @event io:complete */ this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:end" and creates, fires a transaction-specific "end" * event, if config.on.end is defined. * * @method end * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ end: function(transaction, config) { /** * Signals the end of the transaction lifecycle. * @event io:end */ this._evt(EVENTS[2], transaction, config); this._destroy(transaction); }, /** * Fires event "io:success" and creates, fires a transaction-specific * "success" event, if config.on.success is defined. * * @method success * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ success: function(transaction, config) { /** * Signals an HTTP response with status in the 2xx range. * Fires after io:complete. * @event io:success */ this._evt(EVENTS[3], transaction, config); this.end(transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event, if config.on.failure is defined. * * @method failure * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ failure: function(transaction, config) { /** * Signals an HTTP response with status outside of the 2xx range. * Fires after io:complete. * @event io:failure */ this._evt(EVENTS[4], transaction, config); this.end(transaction, config); }, /** * Fires event "io:progress" and creates, fires a transaction-specific * "progress" event -- for XMLHttpRequest file upload -- if * config.on.progress is defined. * * @method progress * @param {Object} transaction Transaction object. * @param {Object} progress event. * @param {Object} config Configuration object for the transaction. */ progress: function(transaction, e, config) { /** * Signals the interactive state during a file upload transaction. * This event fires after io:start and before io:complete. * @event io:progress */ transaction.evt = e; this._evt(EVENTS[5], transaction, config); }, /** * Fires event "io:complete" and creates, fires a transaction-specific * "complete" event -- for XMLHttpRequest file upload -- if * config.on.complete is defined. * * @method load * @param {Object} transaction Transaction object. * @param {Object} load event. * @param {Object} config Configuration object for the transaction. */ load: function (transaction, e, config) { transaction.evt = e.target; this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event -- for XMLHttpRequest file upload -- if * config.on.failure is defined. * * @method error * @param {Object} transaction Transaction object. * @param {Object} error event. * @param {Object} config Configuration object for the transaction. */ error: function (transaction, e, config) { transaction.evt = e; this._evt(EVENTS[4], transaction, config); }, /** * Retry an XDR transaction, using the Flash tranport, if the native * transport fails. * * @method _retry * @private * @param {Object} transaction Transaction object. * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. */ _retry: function(transaction, uri, config) { this._destroy(transaction); config.xdr.use = 'flash'; return this.send(uri, config, transaction.id); }, /** * Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {String} uri URI or root data. * @param {String} data Data to be concatenated onto URI. * @return {String} */ _concat: function(uri, data) { uri += (uri.indexOf('?') === -1 ? '?' : '&') + data; return uri; }, /** * Stores default client headers for all transactions. If a label is * passed with no value argument, the header will be deleted. * * @method setHeader * @param {String} name HTTP header * @param {String} value HTTP header value */ setHeader: function(name, value) { if (value) { this._headers[name] = value; } else { delete this._headers[name]; } }, /** * Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {Object} transaction - XHR instance for the specific transaction. * @param {Object} headers - HTTP headers for the specific transaction, as * defined in the configuration object passed to YUI.io(). */ _setHeaders: function(transaction, headers) { headers = Y.merge(this._headers, headers); Y.Object.each(headers, function(value, name) { if (value !== 'disable') { transaction.setRequestHeader(name, headers[name]); } }); }, /** * Starts timeout count if the configuration object has a defined * timeout property. * * @method _startTimeout * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} timeout Timeout in milliseconds. */ _startTimeout: function(transaction, timeout) { var io = this; io._timeout[transaction.id] = setTimeout(function() { io._abort(transaction, 'timeout'); }, timeout); }, /** * Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {Number} id - Transaction id. */ _clearTimeout: function(id) { clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * Method that determines if a transaction response qualifies as success * or failure, based on the response HTTP status code, and fires the * appropriate success or failure events. * * @method _result * @private * @static * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to io(). */ _result: function(transaction, config) { var status; // Firefox will throw an exception if attempting to access // an XHR object's status property, after a request is aborted. try { status = transaction.c.status; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 304 || status === 1223) { this.success(transaction, config); } else { this.failure(transaction, config); } }, /** * Event handler bound to onreadystatechange. * * @method _rS * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to YUI.io(). */ _rS: function(transaction, config) { var io = this; if (transaction.c.readyState === 4) { if (config.timeout) { io._clearTimeout(transaction.id); } // Yield in the event of request timeout or abort. setTimeout(function() { io.complete(transaction, config); io._result(transaction, config); }, 0); } }, /** * Terminates a transaction due to an explicit abort or timeout. * * @method _abort * @private * @param {Object} transaction Transaction object generated by _create(). * @param {String} type Identifies timed out or aborted transaction. */ _abort: function(transaction, type) { if (transaction && transaction.c) { transaction.e = type; transaction.c.abort(); } }, /** * Requests a transaction. `send()` is implemented as `Y.io()`. Each * transaction may include a configuration object. Its properties are: * * <dl> * <dt>method</dt> * <dd>HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET.</dd> * * <dt>data</dt> * <dd>This is the name-value string that will be sent as the * transaction data. If the request is HTTP GET, the data become * part of querystring. If HTTP POST, the data are sent in the * message body.</dd> * * <dt>xdr</dt> * <dd>Defines the transport to be used for cross-domain requests. * By setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. The properties of the * transport object are: * <dl> * <dt>use</dt> * <dd>The transport to be used: 'flash' or 'native'</dd> * <dt>dataType</dt> * <dd>Set the value to 'XML' if that is the expected response * content type.</dd> * </dl></dd> * * <dt>form</dt> * <dd>Form serialization configuration object. Its properties are: * <dl> * <dt>id</dt> * <dd>Node object or id of HTML form</dd> * <dt>useDisabled</dt> * <dd>`true` to also serialize disabled form field values * (defaults to `false`)</dd> * </dl></dd> * * <dt>on</dt> * <dd>Assigns transaction event subscriptions. Available events are: * <dl> * <dt>start</dt> * <dd>Fires when a request is sent to a resource.</dd> * <dt>complete</dt> * <dd>Fires when the transaction is complete.</dd> * <dt>success</dt> * <dd>Fires when the HTTP response status is within the 2xx * range.</dd> * <dt>failure</dt> * <dd>Fires when the HTTP response status is outside the 2xx * range, if an exception occurs, if the transation is aborted, * or if the transaction exceeds a configured `timeout`.</dd> * <dt>end</dt> * <dd>Fires at the conclusion of the transaction * lifecycle, after `success` or `failure`.</dd> * </dl> * * <p>Callback functions for `start` and `end` receive the id of the * transaction as a first argument. For `complete`, `success`, and * `failure`, callbacks receive the id and the response object * (usually the XMLHttpRequest instance). If the `arguments` * property was included in the configuration object passed to * `Y.io()`, the configured data will be passed to all callbacks as * the last argument.</p> * </dd> * * <dt>sync</dt> * <dd>Pass `true` to make a same-domain transaction synchronous. * <strong>CAVEAT</strong>: This will negatively impact the user * experience. Have a <em>very</em> good reason if you intend to use * this.</dd> * * <dt>context</dt> * <dd>The "`this'" object for all configured event handlers. If a * specific context is needed for individual callbacks, bind the * callback to a context using `Y.bind()`.</dd> * * <dt>headers</dt> * <dd>Object map of transaction headers to send to the server. The * object keys are the header names and the values are the header * values.</dd> * * <dt>timeout</dt> * <dd>Millisecond threshold for the transaction before being * automatically aborted.</dd> * * <dt>arguments</dt> * <dd>User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" and * "end" event handlers. It is the third argument in the "complete", * "success", and "failure" event handlers. <strong>Be sure to quote * this property name in the transaction configuration as * "arguments" is a reserved word in JavaScript</strong> (e.g. * `Y.io({ ..., "arguments": stuff })`).</dd> * </dl> * * @method send * @public * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. * @param {Number} id Transaction id, if already set. * @return {Object} */ send: function(uri, config, id) { var transaction, method, i, len, sync, data, io = this, u = uri, response = {}; config = config ? Y.Object(config) : {}; transaction = io._create(config, id); method = config.method ? config.method.toUpperCase() : 'GET'; sync = config.sync; data = config.data; // Serialize an map object into a key-value string using // querystring-stringify-simple. if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) { data = Y.QueryString.stringify(data); } if (config.form) { if (config.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(transaction, uri, config); } else { // Serialize HTML form data into a key-value string. data = io._serialize(config.form, data); } } if (data) { switch (method) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, data); data = ''; break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers); break; } } if (transaction.xdr) { // Route data to io-xdr module for flash and XDomainRequest. return io.xdr(u, transaction, config); } else if (transaction.notify) { // Route data to custom transport return transaction.c.send(transaction, uri, config); } if (!sync && !transaction.upload) { transaction.c.onreadystatechange = function() { io._rS(transaction, config); }; } try { // Determine if request is to be set as // synchronous or asynchronous. transaction.c.open(method, u, !sync, config.username || null, config.password || null); io._setHeaders(transaction.c, config.headers || {}); io.start(transaction, config); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (config.xdr && config.xdr.credentials) { if (!Y.UA.ie) { transaction.c.withCredentials = true; } } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. transaction.c.send(data); if (sync) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. for (i = 0, len = XHR_PROPS.length; i < len; ++i) { response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]]; } response.getAllResponseHeaders = function() { return transaction.c.getAllResponseHeaders(); }; response.getResponseHeader = function(name) { return transaction.c.getResponseHeader(name); }; io.complete(transaction, config); io._result(transaction, config); return response; } } catch(e) { if (transaction.xdr) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(transaction, uri, config); } else { io.complete(transaction, config); io._result(transaction, config); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (config.timeout) { io._startTimeout(transaction, config.timeout); } return { id: transaction.id, abort: function() { return transaction.c ? io._abort(transaction, 'abort') : false; }, isInProgress: function() { return transaction.c ? (transaction.c.readyState % 4) : false; }, io: io }; } }; /** Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties: <dl> <dt>method</dt> <dd>HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.</dd> <dt>data</dt> <dd>This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.</dd> <dt>xdr</dt> <dd>Defines the transport to be used for cross-domain requests. By setting this property, the transaction will use the specified transport instead of XMLHttpRequest. The properties of the transport object are: <dl> <dt>use</dt> <dd>The transport to be used: 'flash' or 'native'</dd> <dt>dataType</dt> <dd>Set the value to 'XML' if that is the expected response content type.</dd> </dl></dd> <dt>form</dt> <dd>Form serialization configuration object. Its properties are: <dl> <dt>id</dt> <dd>Node object or id of HTML form</dd> <dt>useDisabled</dt> <dd>`true` to also serialize disabled form field values (defaults to `false`)</dd> </dl></dd> <dt>on</dt> <dd>Assigns transaction event subscriptions. Available events are: <dl> <dt>start</dt> <dd>Fires when a request is sent to a resource.</dd> <dt>complete</dt> <dd>Fires when the transaction is complete.</dd> <dt>success</dt> <dd>Fires when the HTTP response status is within the 2xx range.</dd> <dt>failure</dt> <dd>Fires when the HTTP response status is outside the 2xx range, if an exception occurs, if the transation is aborted, or if the transaction exceeds a configured `timeout`.</dd> <dt>end</dt> <dd>Fires at the conclusion of the transaction lifecycle, after `success` or `failure`.</dd> </dl> <p>Callback functions for `start` and `end` receive the id of the transaction as a first argument. For `complete`, `success`, and `failure`, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If the `arguments` property was included in the configuration object passed to `Y.io()`, the configured data will be passed to all callbacks as the last argument.</p> </dd> <dt>sync</dt> <dd>Pass `true` to make a same-domain transaction synchronous. <strong>CAVEAT</strong>: This will negatively impact the user experience. Have a <em>very</em> good reason if you intend to use this.</dd> <dt>context</dt> <dd>The "`this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using `Y.bind()`.</dd> <dt>headers</dt> <dd>Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.</dd> <dt>timeout</dt> <dd>Millisecond threshold for the transaction before being automatically aborted.</dd> <dt>arguments</dt> <dd>User-defined data passed to all registered event handlers. This value is available as the second argument in the "start" and "end" event handlers. It is the third argument in the "complete", "success", and "failure" event handlers. <strong>Be sure to quote this property name in the transaction configuration as "arguments" is a reserved word in JavaScript</strong> (e.g. `Y.io({ ..., "arguments": stuff })`).</dd> </dl> @method io @static @param {String} url qualified path to transaction resource. @param {Object} config configuration object for the transaction. @return {Object} @for YUI **/ Y.io = function(url, config) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); return transaction.send.apply(transaction, [url, config]); }; /** Method for setting and deleting IO HTTP headers to be sent with every request. Hosted as a property on the `io` function (e.g. `Y.io.header`). @method header @param {String} name HTTP header @param {String} value HTTP header value @static **/ Y.io.header = function(name, value) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); transaction.setHeader(name, value); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; var XHR = win && win.XMLHttpRequest, XDR = win && win.XDomainRequest, AX = win && win.ActiveXObject; Y.mix(Y.IO, { /** * The ID of the default IO transport, defaults to `xhr` * @property _default * @type {String} * @static */ _default: 'xhr', /** * * @method defaultTransport * @static * @param {String} [id] The transport to set as the default, if empty a new transport is created. * @return {Object} The transport object with a `send` method */ defaultTransport: function(id) { if (id) { Y.IO._default = id; } else { var o = { c: Y.IO.transports[Y.IO._default](), notify: Y.IO._default === 'xhr' ? false : true }; return o; } }, /** * An object hash of custom transports available to IO * @property transports * @type {Object} * @static */ transports: { xhr: function () { return XHR ? new XMLHttpRequest() : AX ? new ActiveXObject('Microsoft.XMLHTTP') : null; }, xdr: function () { return XDR ? new XDomainRequest() : null; }, iframe: function () { return {}; }, flash: null, nodejs: null }, /** * Create a custom transport of type and return it's object * @method customTransport * @param {String} id The id of the transport to create. * @static */ customTransport: function(id) { var o = { c: Y.IO.transports[id]() }; o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true; return o; } }); Y.mix(Y.IO.prototype, { /** * Fired from the notify method of the transport which in turn fires * the event on the IO object. * @method notify * @param {String} event The name of the event * @param {Object} transaction The transaction object * @param {Object} config The configuration object for this transaction */ notify: function(event, transaction, config) { var io = this; switch (event) { case 'timeout': case 'abort': case 'transport error': transaction.c = { status: 0, statusText: event }; event = 'failure'; default: io[event].apply(io, [transaction, config]); } } }); }, '@VERSION@', {"requires": ["event-custom-base", "querystring-stringify-simple"]}); YUI.add('json-parse', function (Y, NAME) { /** * <p>The JSON module adds support for serializing JavaScript objects into * JSON strings and parsing JavaScript objects from strings in JSON format.</p> * * <p>The JSON namespace is added to your YUI instance including static methods * Y.JSON.parse(..) and Y.JSON.stringify(..).</p> * * <p>The functionality and method signatures follow the ECMAScript 5 * specification. In browsers with native JSON support, the native * implementation is used.</p> * * <p>The <code>json</code> module is a rollup of <code>json-parse</code> and * <code>json-stringify</code>.</p> * * <p>As their names suggest, <code>json-parse</code> adds support for parsing * JSON data (Y.JSON.parse) and <code>json-stringify</code> for serializing * JavaScript data into JSON strings (Y.JSON.stringify). You may choose to * include either of the submodules individually if you don't need the * complementary functionality, or include the rollup for both.</p> * * @module json * @main json * @class JSON * @static */ /** * Provides Y.JSON.parse method to accept JSON strings and return native * JavaScript objects. * * @module json * @submodule json-parse * @for JSON * @static */ // All internals kept private for security reasons function fromGlobal(ref) { return (Y.config.win || this || {})[ref]; } /** * Alias to native browser implementation of the JSON object if available. * * @property Native * @type {Object} * @private */ var _JSON = fromGlobal('JSON'), Native = (Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON), useNative = !!Native, /** * Replace certain Unicode characters that JavaScript may handle incorrectly * during eval--either by deleting them or treating them as line * endings--with escape sequences. * IMPORTANT NOTE: This regex will be used to modify the input if a match is * found. * * @property _UNICODE_EXCEPTIONS * @type {RegExp} * @private */ _UNICODE_EXCEPTIONS = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, /** * First step in the safety evaluation. Regex used to replace all escape * sequences (i.e. "\\", etc) with '@' characters (a non-JSON character). * * @property _ESCAPES * @type {RegExp} * @private */ _ESCAPES = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, /** * Second step in the safety evaluation. Regex used to replace all simple * values with ']' characters. * * @property _VALUES * @type {RegExp} * @private */ _VALUES = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, /** * Third step in the safety evaluation. Regex used to remove all open * square brackets following a colon, comma, or at the beginning of the * string. * * @property _BRACKETS * @type {RegExp} * @private */ _BRACKETS = /(?:^|:|,)(?:\s*\[)+/g, /** * Final step in the safety evaluation. Regex used to test the string left * after all previous replacements for invalid characters. * * @property _UNSAFE * @type {RegExp} * @private */ _UNSAFE = /[^\],:{}\s]/, /** * Replaces specific unicode characters with their appropriate \unnnn * format. Some browsers ignore certain characters during eval. * * @method escapeException * @param c {String} Unicode character * @return {String} the \unnnn escapement of the character * @private */ _escapeException = function (c) { return '\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4); }, /** * Traverses nested objects, applying a reviver function to each (key,value) * from the scope if the key:value's containing object. The value returned * from the function will replace the original value in the key:value pair. * If the value returned is undefined, the key will be omitted from the * returned object. * * @method _revive * @param data {MIXED} Any JavaScript data * @param reviver {Function} filter or mutation function * @return {MIXED} The results of the filtered data * @private */ _revive = function (data, reviver) { var walk = function (o,key) { var k,v,value = o[key]; if (value && typeof value === 'object') { for (k in value) { if (value.hasOwnProperty(k)) { v = walk(value, k); if (v === undefined) { delete value[k]; } else { value[k] = v; } } } } return reviver.call(o,key,value); }; return typeof reviver === 'function' ? walk({'':data},'') : data; }, /** * Parse a JSON string, returning the native JavaScript representation. * * @param s {string} JSON string data * @param reviver {function} (optional) function(k,v) passed each key value * pair of object literals, allowing pruning or altering values * @return {MIXED} the native JavaScript representation of the JSON string * @throws SyntaxError * @method parse * @static */ // JavaScript implementation in lieu of native browser support. Based on // the json2.js library from http://json.org _parse = function (s,reviver) { // Replace certain Unicode characters that are otherwise handled // incorrectly by some browser implementations. // NOTE: This modifies the input if such characters are found! s = s.replace(_UNICODE_EXCEPTIONS, _escapeException); // Test for any remaining invalid characters if (!_UNSAFE.test(s.replace(_ESCAPES,'@'). replace(_VALUES,']'). replace(_BRACKETS,''))) { // Eval the text into a JavaScript data structure, apply any // reviver function, and return return _revive( eval('(' + s + ')'), reviver ); } throw new SyntaxError('JSON.parse'); }; Y.namespace('JSON').parse = function (s,reviver) { if (typeof s !== 'string') { s += ''; } return Native && Y.JSON.useNativeParse ? Native.parse(s,reviver) : _parse(s,reviver); }; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( Native ) { try { useNative = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { useNative = false; } } /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeParse * @type Boolean * @default true * @static */ Y.JSON.useNativeParse = useNative; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition', function (Y, NAME) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', TRANSITION = 'transition', TRANSITION_CAMEL = 'Transition', TRANSITION_PROPERTY_CAMEL, TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, TRANSFORM_CAMEL, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + TRANSITION_CAMEL; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + TRANSITION_CAMEL; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; TRANSFORM_CAMEL = CAMEL_VENDOR_PREFIX + 'Transform'; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration != 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay != 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[TRANSFORM_CAMEL]) { config[TRANSFORM_CAMEL] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur); return dur + 's'; }, _runNative: function(time) { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = node.ownerDocument.defaultView.getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } style.cssText += transitionText + duration + easing + delay + cssText; }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; name = Transition._toHyphen(name); if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style } } }, destroy: function() { var anim = this, node = anim._node; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback) { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else { this._hide(); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name == 'boolean') { // no transition, just toggle on = name; name = null; } name = name || Y.Transition.DEFAULT_TOGGLE; if (typeof on == 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).toggleView(name, on, callback); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); Transition.DEFAULT_TOGGLE = 'fade'; }, '@VERSION@', {"requires": ["node-style"]}); YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('selector-css3', function (Y, NAME) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.DOM._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.DOM._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.DOM._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.DOM._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@', {"requires": ["selector-native", "selector-css2"]}); YUI.add('yui-log', function (Y, NAME) { /** * 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 src = src || ""; if (typeof src !== "undefined") { 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('dump', function (Y, NAME) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition-timer', function (Y, NAME) { /** * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@', {"requires": ["transition"]}); YUI.add('yui', function (Y, NAME) { // empty }, '@VERSION@', {"use": ["yui", "oop", "dom", "event-custom-base", "event-base", "pluginhost", "node", "event-delegate", "io-base", "json-parse", "transition", "selector-css3", "dom-style-ie", "querystring-stringify-simple"]}); var Y = YUI().use('*');
src/config.js
takahashik/todo-app
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable max-len */ if (process.env.BROWSER) { throw new Error('Do not import `config.js` from inside the client-side code.'); } module.exports = { // Node.js app port: process.env.PORT || 3000, // API Gateway api: { // API URL to be used in the client-side code clientUrl: process.env.API_CLIENT_URL || '', // API URL to be used in the server-side code serverUrl: process.env.API_SERVER_URL || `http://localhost:${process.env.PORT || 3000}`, }, // Database databaseUrl: process.env.DATABASE_URL || 'sqlite:database.sqlite', // Web analytics analytics: { // https://analytics.google.com/ googleTrackingId: process.env.GOOGLE_TRACKING_ID, // UA-XXXXX-X }, // Authentication auth: { jwt: { secret: process.env.JWT_SECRET || 'React Starter Kit' }, // https://developers.facebook.com/ facebook: { id: process.env.FACEBOOK_APP_ID || '186244551745631', secret: process.env.FACEBOOK_APP_SECRET || 'a970ae3240ab4b9b8aae0f9f0661c6fc', }, // https://cloud.google.com/console/project google: { id: process.env.GOOGLE_CLIENT_ID || '251410730550-ahcg0ou5mgfhl8hlui1urru7jn5s12km.apps.googleusercontent.com', secret: process.env.GOOGLE_CLIENT_SECRET || 'Y8yR9yZAhm9jQ8FKAL8QIEcd', }, // https://apps.twitter.com/ twitter: { key: process.env.TWITTER_CONSUMER_KEY || 'Ie20AZvLJI2lQD5Dsgxgjauns', secret: process.env.TWITTER_CONSUMER_SECRET || 'KTZ6cxoKnEakQCeSpZlaUCJWGAlTEBJj0y2EMkUBujA7zWSvaQ', }, }, };
app/javascript/mastodon/features/compose/components/autosuggest_account.js
pfm-eyesightjp/mastodon
import React from 'react'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class AutosuggestAccount extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, }; render () { const { account } = this.props; return ( <div className='autosuggest-account'> <div className='autosuggest-account-icon'><Avatar account={account} size={18} /></div> <DisplayName account={account} /> </div> ); } }
app/pages/about/contact.spec.js
jelliotartz/Panoptes-Front-End
/* eslint prefer-arrow-callback: 0, func-names: 0, 'react/jsx-filename-extension': [1, { "extensions": [".js", ".jsx"] }] */ import React from 'react'; import assert from 'assert'; import { shallow } from 'enzyme'; import Contact from './contact'; describe('Contact', function () { it('renders without crashing', function () { const wrapper = shallow(<Contact />); }); it('renders markdown elements', function () { const wrapper = shallow(<Contact />); const markdownElements = wrapper.find('Markdown'); assert.equal(markdownElements.length, 6); }); });
src/parser/priest/discipline/modules/spells/Contrition.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import StatTracker from 'parser/shared/modules/StatTracker'; import { TooltipElement } from 'common/Tooltip'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import { formatPercentage, formatNumber } from 'common/format'; import Analyzer from 'parser/core/Analyzer'; import Penance from './Penance'; import { calculateOverhealing ,OffensivePenanceBoltEstimation } from '../../SpellCalculations'; class Contrition extends Analyzer { static dependencies = { statTracker: StatTracker, penance: Penance, // we need this to add `penanceBoltNumber` to the damage and heal events }; healing = 0; damagePenalty = 0; penanceBoltEstimation; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent( SPELLS.CONTRITION_TALENT.id ); this.penanceBoltEstimation = OffensivePenanceBoltEstimation( this.statTracker ); } /** * Theory behind this is as follows * By casting a contrition penance, you lose an offensive penance worth of healing * To hone in on the true value of contrition, we estimate the healing of an offensive * penance hit, and subtract that from the contrition amount. * * We keep the penance heal as that is a true gain from choosing a contrition * penance over a regular offensive one. */ on_byPlayer_heal(event) { if ( event.ability.guid !== SPELLS.CONTRITION_HEAL.id && event.ability.guid !== SPELLS.PENANCE_HEAL.id ) { return; } // Add the healing to our count this.healing += event.amount; // Get an estimated amount of damage and healing for a bolt const { boltDamage, boltHealing } = this.penanceBoltEstimation(); // Calculate the difference between contrition and an offensive penance if (event.ability.guid === SPELLS.CONTRITION_HEAL.id) { const estimatedBoltHealing = boltHealing * event.hitType; const estimatedOverhealing = calculateOverhealing( estimatedBoltHealing, event.amount, event.overheal ); this.healing -= estimatedBoltHealing - estimatedOverhealing; } // Calculate (if applicable), the damage penalty per bolt of friendly penance if (event.ability.guid === SPELLS.PENANCE_HEAL.id) { this.damagePenalty += boltDamage; } } statistic() { const healing = this.healing || 0; return ( <StatisticBox icon={<SpellIcon id={SPELLS.CONTRITION_TALENT.id} />} value={`${formatNumber(healing / this.owner.fightDuration * 1000)} HPS`} label={( <TooltipElement content={ `The effective healing contributed by Contrition (${formatPercentage(this.owner.getPercentageOfTotalHealingDone(healing))}% of total healing done). You lost roughly ${formatNumber(this.damagePenalty / this.owner.fightDuration * 1000)} DPS, or ${formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.damagePenalty))}% more damage.` } > Contrition healing </TooltipElement> )} /> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(); } export default Contrition;
packages/material-ui-icons/src/BatteryCharging30Rounded.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M15.67 4H14V3c0-.55-.45-1-1-1h-2c-.55 0-1 .45-1 1v1H8.33C7.6 4 7 4.6 7 5.33v9.17h2.83c-.38 0-.62-.4-.44-.74l2.67-5c.24-.45.94-.28.94.24v3.5h1.17c.38 0 .62.4.44.74l-.67 1.26H17V5.33C17 4.6 16.4 4 15.67 4z" /><path d="M11.94 18.24c-.24.45-.94.28-.94-.24v-3.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07l-1.99 3.74z" /></React.Fragment> , 'BatteryCharging30Rounded');
examples/paragraphs/src/App.js
josepot/react-redux-scroll
import React from 'react'; import rebassConfig from './rebass-config'; import Navbar from './components/Navbar'; import Content from './components/Content'; export default rebassConfig(() => <div> <Navbar /> <Content /> </div> );
client/components/auth/signout.js
raymestalez/vertex
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from '../../actions/auth'; class Signout extends Component { componentWillMount(){ // as soon as it renders - login user out console.log(">>>> src/components/auth/signout.js:"); console.log("Calling signoutUser action creator."); this.props.signoutUser(); } render(){ return ( <div>Signed out!</div> ); } } export default connect(null, actions)(Signout);
docs/app/Examples/modules/Dropdown/Types/DropdownExampleMultipleSearchSelection.js
ben174/Semantic-UI-React
import React from 'react' import { Dropdown } from 'semantic-ui-react' import { stateOptions } from '../common' const DropdownExampleMultipleSearchSelection = () => ( <Dropdown placeholder='State' fluid multiple search selection options={stateOptions} /> ) export default DropdownExampleMultipleSearchSelection
ajax/libs/forerunnerdb/1.3.40/fdb-core+persist.js
BenjaminVanRyseghem/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), Persist = _dereq_('../lib/Persist'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":4,"../lib/Persist":23}],2:[function(_dereq_,module,exports){ "use strict"; /** * The main collection class. Collections store multiple documents and * can operate on them using the query language to insert, read, update * and delete. */ var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Collection object used to store data. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name) { 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._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // 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'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the 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'); /** * Get the internal data * @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._state !== 'dropped') { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log('Dropping collection ' + this._name); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } 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); }; /** * 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()); } } return this.$super.apply(this, arguments); }); /** * Sets the collection's data to the array of documents passed. * @param data * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw('ForerunnerDB.Collection "' + this.name() + '": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = JSON.stringify(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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this.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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Handle transform update = this.transformIn(update); if (this.debug()) { console.log('Updating some collection data for collection "' + this.name() + '"'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (originalDoc) { var newDoc = self.decouple(originalDoc), triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { 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, originalDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, 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, originalDoc, 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(originalDoc, update, query, options, ''); } return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; 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('ForerunnerDB.Collection "' + this.name() + '": 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 true; }; /** * 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 {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * 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, 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': // 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; 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], '', {})) { 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': 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('ForerunnerDB.Collection "' + this.name() + '": 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('ForerunnerDB.Collection "' + this.name() + '": 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], '', {})) { 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('ForerunnerDB.Collection "' + this.name() + '": 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 = JSON.stringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (JSON.stringify(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('ForerunnerDB.Collection "' + this.name() + '": 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('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!'); } } else { throw('ForerunnerDB.Collection "' + this.name() + '": 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], '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!'); } break; } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": 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('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')'); } 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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { 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); }; // 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); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this.deferEmit('change', {type: 'remove', data: dataSet}); } if (callback) { callback(false, dataSet); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * 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. * @private */ Collection.prototype.deferEmit = function () { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout if (this._changeTimeout) { clearTimeout(this._changeTimeout); } // Set a timeout this._changeTimeout = setTimeout(function () { if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); } self.emit.apply(self, args); }, 100); } else { this.emit.apply(this, arguments); } }; /** * 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. */ Collection.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { 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); } this[type](dataArr); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { 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.insert = function (data, index, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": 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, 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 (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // 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 }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); this._onInsert(inserted, failed); if (callback) { callback(); } this.deferEmit('change', {type: 'insert', data: inserted}); return { inserted: inserted, failed: failed }; }; /** * 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; 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); }; 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 false; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = JSON.stringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = JSON.stringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * 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(); } } }; /** * Returns the index of the document identified by the passed item's primary key. * @param {Object} item The item whose primary key should be used to lookup. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (item) { return this._data.indexOf( this._primaryIndex.get( item[this._primaryKey] ) ); }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets the collection that this collection is a subset of. * @returns {Collection} */ Collection.prototype.subsetOf = function () { return this.__subsetOf; }; /** * Sets the collection that this collection is a subset of. * @param {Collection} collection The collection to set as the parent of this subset. * @returns {*} This object for chaining. * @private */ Collection.prototype._subsetOf = function (collection) { this.__subsetOf = collection; return this; }; /** * 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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": 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 = JSON.stringify(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. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, //finalQuery, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearch, joinMulti, joinRequire, joinFindResults, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, matcher = function (doc) { return self._match(doc, query, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(query, options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); } 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) { // 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); } // 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'); } op.time('tableScan: ' + scanLength); } if (options.$limit && resultArr && resultArr.length > options.$limit) { resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB joinCollectionInstance = this._db.collection(joinCollectionName); // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearch = {}; joinMulti = false; joinRequire = false; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; /*default: // Check for a double-dollar which is a back-reference to the root collection item if (joinMatchIndex.substr(0, 3) === '$$.') { // Back reference // TODO: Support complex joins } break;*/ } } else { // TODO: Could optimise this by caching path objects // Get the data to match against and store in the search object joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0]; } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearch); // 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 resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // 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], '', {})) { // 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], '', {})) { // 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'); } op.stop(); resultArr.__fdbOp = op; 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. * @returns {Number} */ Collection.prototype.indexOf = function (query) { var item = this.find(query, {$decouple: false})[0]; if (item) { return this._data.indexOf(item); } }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // 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 = 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, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets buckets = this.bucket(keyObj.___fdbKey, arr); // Loop buckets and sort contents for (i in buckets) { if (buckets.hasOwnProperty(i)) { arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i])); } } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * 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('ForerunnerDB.Collection "' + this.name() + '": $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * 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, buckets = {}; for (i = 0; i < arr.length; i++) { buckets[arr[i][key]] = buckets[arr[i][key]] || []; buckets[arr[i][key]].push(arr[i]); } return buckets; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param match * @param path * @param subDocQuery * @param subDocOptions * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; 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]; } resultObj.subDocs.push(subDocResults); resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.noStats) { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * 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._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw('ForerunnerDB.Collection "' + this.name() + '": Collection 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[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // 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[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); break; case 'update': obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); break; case 'remove': obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); break; default: } }); }, 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {Object} options An options object. * @returns {Collection} */ 'object': function (options) { 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. * @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. * @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. * @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. * @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 get's called by all the other variants and * handles the actual logic of the overloaded method. * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log('Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name).db(this); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @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. * @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 = [], i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { if (search) { if (search.exec(i)) { arr.push({ name: i, count: this._collection[i].count() }); } } else { arr.push({ name: i, count: this._collection[i].count() }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":21,"./Path":22,"./ReactorIO":24,"./Shared":25}],3:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); 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'); 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'); 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('ForerunnerDB.CollectionGroup "' + this.name() + '": All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function () { if (this._state !== 'dropped') { var i, collArr, viewArr; if (this._debug) { console.log('Dropping collection group ' + this._name); } 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); } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":2,"./Shared":25}],4:[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; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The main ForerunnerDB core object. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function () { this._db = {}; this._debug = {}; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @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. * @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; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @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; // 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'); Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = 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 browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":6,"./Metrics.js":10,"./Overload":21,"./Shared":25}],5:[function(_dereq_,module,exports){ "use strict"; var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],6:[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, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The main ForerunnerDB db object. * @constructor */ var Db = function (name) { this.init.apply(this, arguments); }; Db.prototype.init = function (name) { this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @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. * @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; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @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'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; /** * 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. */ '': function () { if (this._state !== 'dropped') { 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._core._db[this._name]; } return true; }, /** * Drops the database. * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (this._state !== 'dropped') { 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._core._db[this._name]; } return true; }, /** * Drops the database. * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (this._state !== 'dropped') { 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._core._db[this._name]; } return true; }, /** * Drops the database. * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (this._state !== 'dropped') { 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._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name).core(this); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @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. */ Core.prototype.databases = function (search) { var arr = [], 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)) { if (search) { if (search.exec(i)) { arr.push({ name: i, collectionCount: this._db[i].collections().length }); } } else { arr.push({ name: i, collectionCount: this._db[i].collections().length }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; module.exports = Db; },{"./Collection.js":2,"./Crc.js":5,"./Metrics.js":10,"./Overload":21,"./Shared":25}],7:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), btree = function () {}; /** * The index class used to instantiate hash map 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 (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); 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('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 = new (btree.create(2, this.sortAsc))(); 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, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; 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) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.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); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./Path":22,"./Shared":25}],8:[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 = {}; 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.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":22,"./Shared":25}],9:[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 {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * 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":25}],10:[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":20,"./Shared":25}],11:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],12:[function(_dereq_,module,exports){ "use strict"; // TODO: Document the methods in this mixin var ChainReactor = { chain: function (obj) { this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, count = arr.length, index; for (index = 0; index < count; index++) { arr[index].chainReceive(this, type, data, options); } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],13:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Common; Common = { /** * 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) { if (!copies) { return JSON.parse(JSON.stringify(data)); } else { var i, json = JSON.stringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(JSON.parse(json)); } return copyArr; } } return undefined; }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]) }; module.exports = Common; },{"./Overload":21}],14:[function(_dereq_,module,exports){ "use strict"; var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],15:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); 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; } }), 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 (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; // Handle global emit if (this._listeners[event]['*']) { var arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].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 var listenerIdArr = this._listeners[event], listenerIdCount, listenerIdIndex; 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++) { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } return this; } }; module.exports = Events; },{"./Overload":21}],16:[function(_dereq_,module,exports){ "use strict"; 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 {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, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; // 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 the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; 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], 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 (typeof(source) === '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], 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], 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], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], 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], 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], 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=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, 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 '$ne': // Not equals return source != test; // jshint ignore:line case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], '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], '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 (inArr[inArrIndex] === source) { return true; } } return false; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootQuery['//distinctLookup'] = options.$rootQuery['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootQuery['//distinctLookup'][distinctProp] = options.$rootQuery['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; } return -1; } }; module.exports = Matching; },{}],17:[function(_dereq_,module,exports){ "use strict"; 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; },{}],18:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":21}],19:[function(_dereq_,module,exports){ "use strict"; 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('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "' + prop + '" for "' + this.name() + '"'); } }, /** * 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('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for "' + this.name() + '"'); } }, /** * 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 delete. * @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 from the array stack. * @param {Object} doc The document to modify. * @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false; if (doc.length > 0) { if (val === 1) { doc.pop(); updated = true; } else if (val === -1) { doc.shift(); updated = true; } } return updated; } }; module.exports = Updating; },{}],20:[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":22,"./Shared":25}],21:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type; // 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); } } } } throw('ForerunnerDB.Overload "' + this.name() + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],22:[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.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. * * @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') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * 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(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; 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])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * 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; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * 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; }; /** * 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":25}],23:[function(_dereq_,module,exports){ "use strict"; // TODO: Add doc comments to this class // Import external names locally var Shared = _dereq_('./Shared'), localforage = _dereq_('localforage'), Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload; Persist = function () { this.init.apply(this, arguments); }; Persist.prototype.init = function (db) { // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: 'ForerunnerDB', storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); 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; Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; 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(); }; Persist.prototype.save = function (key, data, callback) { var encode; encode = function (val, finished) { if (typeof val === 'object') { val = 'json::fdb::' + JSON.stringify(val); } else { val = 'raw::fdb::' + val; } if (finished) { finished(false, val); } }; switch (this.mode()) { case 'localforage': encode(data, function (err, data) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data); } }, function (err) { if (callback) { callback(err); } }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; Persist.prototype.load = function (key, callback) { var parts, data, decode; decode = function (val, finished) { if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = JSON.parse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (finished) { finished(false, data); } } else { if (finished) { finished(false, val); } } }; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; 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._state !== 'dropped') { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (this._state !== 'dropped') { 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._state !== 'dropped') { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Save the collection data this._db.persist.drop(this._name); } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.apply(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) { if (this._state !== 'dropped') { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Save the collection data this._db.persist.drop(this._name, callback); } 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!'); } } } // Call the original method CollectionDrop.apply(this, callback); } } }); Collection.prototype.save = function (callback) { if (this._name) { if (this._db) { // Save the collection data this._db.persist.save(this._name, this._data, callback); } 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!'); } } }; Collection.prototype.load = function (callback) { var self = this; if (this._name) { if (this._db) { // Load the collection data this._db.persist.load(this._name, function (err, data) { if (!err) { if (data) { self.setData(data); } if (callback) { callback(false); } } 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!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { this.persist = new Persist(this); DbInit.apply(this, arguments); }; Db.prototype.load = function (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 obj[index].load(loadCallback); } } }; Db.prototype.save = function (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 obj[index].save(saveCallback); } } }; Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":2,"./CollectionGroup":3,"./Shared":25,"localforage":33}],24:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { 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); ReactorIO.prototype.drop = function () { if (this._state !== 'dropped') { 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); } 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.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":25}],25:[function(_dereq_,module,exports){ "use strict"; var Shared = { version: '1.3.40', modules: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { this.modules[name] = 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. * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { this.modules[name]._fdbFinished = true; 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. * @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. * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: function (obj, mixinName) { var system = this.mixins[mixinName]; if (system) { for (var i in system) { if (system.hasOwnProperty(i)) { obj[i] = system[i]; } } } else { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } }, /** * Generates a generic getter/setter method for the passed method name. * @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. * @param arr * @returns {Function} * @constructor */ overload: _dereq_('./Overload'), /** * Define the mixins that other modules can use as required. */ 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') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Triggers":18,"./Mixin.Updating":19,"./Overload":21}],26:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],27:[function(_dereq_,module,exports){ 'use strict'; var asap = _dereq_('asap') module.exports = Promise function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new') if (typeof fn !== 'function') throw new TypeError('not a function') var state = null var value = null var deferreds = [] var self = this this.then = function(onFulfilled, onRejected) { return new Promise(function(resolve, reject) { handle(new Handler(onFulfilled, onRejected, resolve, reject)) }) } function handle(deferred) { if (state === null) { deferreds.push(deferred) return } asap(function() { var cb = state ? deferred.onFulfilled : deferred.onRejected if (cb === null) { (state ? deferred.resolve : deferred.reject)(value) return } var ret try { ret = cb(value) } catch (e) { deferred.reject(e) return } deferred.resolve(ret) }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.') if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then if (typeof then === 'function') { doResolve(then.bind(newValue), resolve, reject) return } } state = true value = newValue finale() } catch (e) { reject(e) } } function reject(newValue) { state = false value = newValue finale() } function finale() { for (var i = 0, len = deferreds.length; i < len; i++) handle(deferreds[i]) deferreds = null } doResolve(fn, resolve, reject) } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null this.onRejected = typeof onRejected === 'function' ? onRejected : null this.resolve = resolve this.reject = reject } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return done = true onFulfilled(value) }, function (reason) { if (done) return done = true onRejected(reason) }) } catch (ex) { if (done) return done = true onRejected(ex) } } },{"asap":29}],28:[function(_dereq_,module,exports){ 'use strict'; //This file contains then/promise specific extensions to the core promise API var Promise = _dereq_('./core.js') var asap = _dereq_('asap') module.exports = Promise /* Static Functions */ function ValuePromise(value) { this.then = function (onFulfilled) { if (typeof onFulfilled !== 'function') return this return new Promise(function (resolve, reject) { asap(function () { try { resolve(onFulfilled(value)) } catch (ex) { reject(ex); } }) }) } } ValuePromise.prototype = Object.create(Promise.prototype) var TRUE = new ValuePromise(true) var FALSE = new ValuePromise(false) var NULL = new ValuePromise(null) var UNDEFINED = new ValuePromise(undefined) var ZERO = new ValuePromise(0) var EMPTYSTRING = new ValuePromise('') Promise.resolve = function (value) { if (value instanceof Promise) return value if (value === null) return NULL if (value === undefined) return UNDEFINED if (value === true) return TRUE if (value === false) return FALSE if (value === 0) return ZERO if (value === '') return EMPTYSTRING if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then if (typeof then === 'function') { return new Promise(then.bind(value)) } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex) }) } } return new ValuePromise(value) } Promise.from = Promise.cast = function (value) { var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead') err.name = 'Warning' console.warn(err.stack) return Promise.resolve(value) } Promise.denodeify = function (fn, argumentCount) { argumentCount = argumentCount || Infinity return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { while (args.length && args.length > argumentCount) { args.pop() } args.push(function (err, res) { if (err) reject(err) else resolve(res) }) fn.apply(self, args) }) } } Promise.nodeify = function (fn) { return function () { var args = Array.prototype.slice.call(arguments) var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null try { return fn.apply(this, arguments).nodeify(callback) } catch (ex) { if (callback === null || typeof callback == 'undefined') { return new Promise(function (resolve, reject) { reject(ex) }) } else { asap(function () { callback(ex) }) } } } } Promise.all = function () { var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0]) var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments) if (!calledWithArray) { var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated') err.name = 'Warning' console.warn(err.stack) } return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]) var remaining = args.length function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then if (typeof then === 'function') { then.call(val, function (val) { res(i, val) }, reject) return } } args[i] = val if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex) } } for (var i = 0; i < args.length; i++) { res(i, args[i]) } }) } Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); } Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }) }); } /* Prototype Methods */ Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { asap(function () { throw err }) }) } Promise.prototype.nodeify = function (callback) { if (typeof callback != 'function') return this this.then(function (value) { asap(function () { callback(null, value) }) }, function (err) { asap(function () { callback(err) }) }) } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); } },{"./core.js":27,"asap":29}],29:[function(_dereq_,module,exports){ (function (process){ // Use the fastest possible means to execute a task in a future turn // of the event loop. // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestFlush = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestFlush = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestFlush = setImmediate.bind(window, flush); } else { requestFlush = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); channel.port1.onmessage = flush; requestFlush = function () { channel.port2.postMessage(0); }; } else { // old browsers requestFlush = function () { setTimeout(flush, 0); }; } function asap(task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestFlush(); } }; module.exports = asap; }).call(this,_dereq_('_process')) },{"_process":26}],30:[function(_dereq_,module,exports){ // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function() { reject(openreq.error); }; openreq.onupgradeneeded = function() { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); }; openreq.onsuccess = function() { dbInfo.db = openreq.result; self._dbInfo = dbInfo; resolve(); }; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function() { var value = req.result; if (value === undefined) { value = null; } resolve(value); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(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 result = iterator(cursor.value, cursor.key, iterationNumber++); if (result !== void(0)) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function() { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function() { resolve(); }; transaction.onerror = function() { reject(req.error); }; // The request will be aborted if we've exceeded our storage // space. In this case, we will reject with a specific // "QuotaExceededError". transaction.onabort = function(event) { var error = event.target.error; if (error === 'QuotaExceededError') { reject(error); } }; })['catch'](reject); }); executeDeferedCallback(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() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(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); }); } } function executeDeferedCallback(promise, callback) { if (callback) { promise.then(function(result) { deferCallback(callback, result); }, function(error) { callback(error); }); } } // Under Chrome the callback is called before the changes (save, clear) // are actually made. So we use a defer function which wait that the // call stack to be empty. // For more info : https://github.com/mozilla/localForage/issues/175 // Pull request : https://github.com/mozilla/localForage/pull/178 function deferCallback(callback, result) { if (callback) { return setTimeout(function() { return callback(null, result); }, 0); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (typeof module !== 'undefined' && module.exports) { module.exports = asyncStorage; } else if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else { this.asyncStorage = asyncStorage; } }).call(window); },{"promise":28}],31:[function(_dereq_,module,exports){ // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; self._dbInfo = dbInfo; var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); return serializerPromise.then(function(lib) { serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; for (var i = 0; i < length; i++) { var key = localStorage.key(i); var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), i + 1); if (value !== void(0)) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function(keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function(resolve, reject) { serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { try { var dbInfo = self._dbInfo; localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.EXPORT) { module.exports = localStorageWrapper; } else if (moduleType === ModuleType.DEFINE) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else { this.localStorageWrapper = localStorageWrapper; } }).call(window); },{"./../utils/serializer":34,"promise":28}],32:[function(_dereq_,module,exports){ /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof(options[i]) !== 'string' ? options[i].toString() : options[i]; } } var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); var dbInfoPromise = new Promise(function(resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function() { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function(t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function() { self._dbInfo = dbInfo; resolve(); }, function(t, error) { reject(error); }); }); }); return serializerPromise.then(function(lib) { serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function(t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = serializer.deserialize(result); } resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function(t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void(0)) { resolve(result); return; } } resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function() { resolve(originalValue); }, function(t, error) { reject(error); }); }, function(sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function(t, results) { var result = results.rows.item(0).c; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function(t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function(t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.DEFINE) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(window); },{"./../utils/serializer":34,"promise":28}],33:[function(_dereq_,module,exports){ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [ DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE ]; var LibraryMethods = [ 'clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem' ]; var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function(self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function() { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function() { try { return (self.localStorage && ('setItem' in self.localStorage) && (self.localStorage.setItem)); } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function() { var _args = arguments; return localForageInstance.ready().then(function() { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var globalObject = this; function LocalForage(options) { this._config = extend({}, DefaultConfig, options); this._driverSet = null; this._ready = false; this._dbInfo = null; // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } this.setDriver(this._config.driver); } LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB; LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE; LocalForage.prototype.WEBSQL = DriverType.WEBSQL; // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof(options) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof(options) === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function(driverObject, callback, errorCallback) { var defineDriver = new Promise(function(resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error( 'Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver' ); var namingError = new Error( 'Custom driver name already in use: ' + driverObject._driver ); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function(supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); defineDriver.then(callback, errorCallback); return defineDriver; }; LocalForage.prototype.driver = function() { return this._driver || null; }; LocalForage.prototype.ready = function(callback) { var self = this; var ready = new Promise(function(resolve, reject) { self._driverSet.then(function() { if (self._ready === null) { self._ready = self._initStorage(self._config); } self._ready.then(resolve, reject); })['catch'](reject); }); ready.then(callback, callback); return ready; }; LocalForage.prototype.setDriver = function(drivers, callback, errorCallback) { var self = this; if (typeof drivers === 'string') { drivers = [drivers]; } this._driverSet = new Promise(function(resolve, reject) { var driverName = self._getFirstSupportedDriver(drivers); var error = new Error('No available storage method found.'); if (!driverName) { self._driverSet = Promise.reject(error); reject(error); return; } self._dbInfo = null; self._ready = null; if (isLibraryDriver(driverName)) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_([driverName], function(lib) { self._extend(lib); resolve(); }); return; } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly var driver; switch (driverName) { case self.INDEXEDDB: driver = _dereq_('./drivers/indexeddb'); break; case self.LOCALSTORAGE: driver = _dereq_('./drivers/localstorage'); break; case self.WEBSQL: driver = _dereq_('./drivers/websql'); } self._extend(driver); } else { self._extend(globalObject[driverName]); } } else if (CustomDrivers[driverName]) { self._extend(CustomDrivers[driverName]); } else { self._driverSet = Promise.reject(error); reject(error); return; } resolve(); }); function setDriverToConfig() { self._config.driver = self.driver(); } this._driverSet.then(setDriverToConfig, setDriverToConfig); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; // Used to determine which driver we should use as the backend for this // instance of localForage. LocalForage.prototype._getFirstSupportedDriver = function(drivers) { if (drivers && isArray(drivers)) { for (var i = 0; i < drivers.length; i++) { var driver = drivers[i]; if (this.supports(driver)) { return driver; } } } return null; }; LocalForage.prototype.createInstance = function(options) { return new LocalForage(options); }; // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localForage = new LocalForage(); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { define('localforage', function() { return localForage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(window); },{"./drivers/indexeddb":30,"./drivers/localstorage":31,"./drivers/websql":32,"promise":28}],34:[function(_dereq_,module,exports){ (function() { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var 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; // 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() { var str = bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { window.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 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 new Blob([buffer]); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i+=4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i+1]); encoded3 = BASE_CHARS.indexOf(serializedString[i+2]); encoded4 = BASE_CHARS.indexOf(serializedString[i+3]); /*jslint bitwise: true */ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if ((bytes.length % 3) === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; if (typeof module !== 'undefined' && module.exports) { module.exports = localforageSerializer; } else if (typeof define === 'function' && define.amd) { define('localforageSerializer', function() { return localforageSerializer; }); } else { this.localforageSerializer = localforageSerializer; } }).call(window); },{}]},{},[1]);
src/Components/Coffees.js
Zangriev/SampleApplication
import React, { Component } from 'react'; import { Link } from 'react-router' import CoffeeStore from "../Stores/Coffee"; let getState = () => { return { coffees: CoffeeStore.getCoffees(), filter: CoffeeStore.getFilter() }; }; class Coffees extends Component { constructor(props) { super(props); this.state = getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { CoffeeStore.addChangeListener(this.onChange); CoffeeStore.provideCoffees(); } componentWillUnmount() { CoffeeStore.removeChangeListener(this.onChange); } onChange() { this.setState(getState()); } render() { let formatPrice = (price) => { return price.toLocaleString("en-US", { style: "currency", currency: "USD" }); }; let renderProductStatus = (productStatus) => { if (productStatus.value.length === 0) { return <span /> } let text = productStatus.value.map((x) => x.name).join(", "); return ( <span className="product-tile-status"> {text} </span> ); }; let filter = (coffee) => { return this.state.filter.matches(coffee); }; let coffees = this.state.coffees.filter(filter).map((coffee, index) => { let e = coffee.elements; let price = formatPrice(e.price.value); let name = e.product_name.value; let imageLink = e.image.value[0].url; let status = renderProductStatus(e.product_status); let link = "store/coffees/" + coffee.elements.url_pattern.value; return ( <div className="col-md-6 col-lg-4" key={index}> <article className="product-tile"> <Link to={link}> <h1 className="product-heading">{name}</h1> {status} <figure className="product-tile-image"> <img alt={name} className="" src={imageLink} title={name} /> </figure> <div className="product-tile-info"> <span className="product-tile-price"> {price} </span> </div> </Link> </article> </div> ); }); return ( <div id="product-list" className="col-md-8 col-lg-9 product-list"> {coffees} </div> ); } } export default Coffees;
src/svg-icons/notification/do-not-disturb.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationDoNotDisturb = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8 0-1.85.63-3.55 1.69-4.9L16.9 18.31C15.55 19.37 13.85 20 12 20zm6.31-3.1L7.1 5.69C8.45 4.63 10.15 4 12 4c4.42 0 8 3.58 8 8 0 1.85-.63 3.55-1.69 4.9z"/> </SvgIcon> ); NotificationDoNotDisturb = pure(NotificationDoNotDisturb); NotificationDoNotDisturb.displayName = 'NotificationDoNotDisturb'; NotificationDoNotDisturb.muiName = 'SvgIcon'; export default NotificationDoNotDisturb;
ajax/libs/redux-little-router/7.3.2/redux-little-router.js
froala/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReduxLittleRouter"] = factory(require("react")); else root["ReduxLittleRouter"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_30__) { 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'; Object.defineProperty(exports, "__esModule", { value: true }); exports.createMatcher = exports.locationDidChange = exports.routerReducer = exports.GO_BACK = exports.GO_FORWARD = exports.GO = exports.REPLACE = exports.PUSH = exports.LOCATION_CHANGED = exports.Fragment = exports.PersistentQueryLink = exports.Link = exports.RouterProvider = exports.provideRouter = exports.initializeCurrentLocation = exports.createStoreWithRouter = undefined; var _storeEnhancer = __webpack_require__(1); var _storeEnhancer2 = _interopRequireDefault(_storeEnhancer); var _provider = __webpack_require__(29); var _provider2 = _interopRequireDefault(_provider); var _link = __webpack_require__(31); var _fragment = __webpack_require__(32); var _fragment2 = _interopRequireDefault(_fragment); var _reducer = __webpack_require__(27); var _reducer2 = _interopRequireDefault(_reducer); var _createMatcher = __webpack_require__(24); var _createMatcher2 = _interopRequireDefault(_createMatcher); var _actionTypes = __webpack_require__(23); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.createStoreWithRouter = _storeEnhancer2.default; exports.initializeCurrentLocation = _storeEnhancer.initializeCurrentLocation; exports.provideRouter = _provider2.default; exports.RouterProvider = _provider.RouterProvider; exports.Link = _link.Link; exports.PersistentQueryLink = _link.PersistentQueryLink; exports.Fragment = _fragment2.default; exports.LOCATION_CHANGED = _actionTypes.LOCATION_CHANGED; exports.PUSH = _actionTypes.PUSH; exports.REPLACE = _actionTypes.REPLACE; exports.GO = _actionTypes.GO; exports.GO_FORWARD = _actionTypes.GO_FORWARD; exports.GO_BACK = _actionTypes.GO_BACK; exports.routerReducer = _reducer2.default; exports.locationDidChange = _storeEnhancer.locationDidChange; exports.createMatcher = _createMatcher2.default; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.initializeCurrentLocation = exports.locationDidChange = undefined; 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; }; var _createBrowserHistory = __webpack_require__(2); var _createBrowserHistory2 = _interopRequireDefault(_createBrowserHistory); var _createMemoryHistory = __webpack_require__(17); var _createMemoryHistory2 = _interopRequireDefault(_createMemoryHistory); var _useBasename = __webpack_require__(18); var _useBasename2 = _interopRequireDefault(_useBasename); var _useQueries = __webpack_require__(19); var _useQueries2 = _interopRequireDefault(_useQueries); var _actionTypes = __webpack_require__(23); var _createMatcher = __webpack_require__(24); var _createMatcher2 = _interopRequireDefault(_createMatcher); var _reducer = __webpack_require__(27); var _reducer2 = _interopRequireDefault(_reducer); var _initialRouterState = __webpack_require__(28); var _initialRouterState2 = _interopRequireDefault(_initialRouterState); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var README_MESSAGE = '\n See the README for more information:\n https://github.com/FormidableLabs/redux-little-router#wiring-up-the-boilerplate\n'; var locationDidChange = exports.locationDidChange = function locationDidChange(_ref) { var location = _ref.location; var matchRoute = _ref.matchRoute; // Extract the pathname so that we don't match against the basename. // This avoids requiring basename-hardcoded routes. var pathname = location.pathname; return { type: _actionTypes.LOCATION_CHANGED, payload: _extends({}, location, matchRoute(pathname)) }; }; var initializeCurrentLocation = exports.initializeCurrentLocation = function initializeCurrentLocation(location) { return { type: _actionTypes.LOCATION_CHANGED, payload: location }; }; var resolveHistory = function resolveHistory(_ref2) { var basename = _ref2.basename; var forServerRender = _ref2.forServerRender; var historyFactory = forServerRender ? _createMemoryHistory2.default : _createBrowserHistory2.default; return (0, _useBasename2.default)((0, _useQueries2.default)(historyFactory))({ basename: basename }); }; exports.default = function (_ref3) { var routes = _ref3.routes; var pathname = _ref3.pathname; var query = _ref3.query; var _ref3$basename = _ref3.basename; var basename = _ref3$basename === undefined ? '' : _ref3$basename; var _ref3$forServerRender = _ref3.forServerRender; var forServerRender = _ref3$forServerRender === undefined ? false : _ref3$forServerRender; var _ref3$createMatcher = _ref3.createMatcher; var createMatcher = _ref3$createMatcher === undefined ? _createMatcher2.default : _ref3$createMatcher; var userHistory = _ref3.history; if (!routes) { throw Error('\n Missing route configuration. You must define your routes as\n an object where the keys are routes and the values are any\n route-specific data.\n\n ' + README_MESSAGE + '\n '); } // eslint-disable-next-line no-magic-numbers if (!Object.keys(routes).every(function (route) { return route.indexOf('/') === 0; })) { throw Error('\n The route configuration you provided is malformed. Make sure\n that all of your routes start with a slash.\n\n ' + README_MESSAGE + '\n '); } var history = userHistory || resolveHistory({ basename: basename, forServerRender: forServerRender }); return function (createStore) { return function (reducer, initialState, enhancer) { var enhancedReducer = function enhancedReducer(state, action) { var vanillaState = _extends({}, state); delete vanillaState.router; var newState = reducer(vanillaState, action); // Support redux-loop if (Array.isArray(newState)) { var nextState = newState[0]; // eslint-disable-line no-magic-numbers var nextEffects = newState[1]; // eslint-disable-line no-magic-numbers return [_extends({}, nextState, { router: (0, _reducer2.default)(state && state.router, action) }), nextEffects]; } return _extends({}, reducer(vanillaState, action), { router: (0, _reducer2.default)(state && state.router, action) }); }; var store = createStore(enhancedReducer, pathname || query ? _extends({}, initialState, { router: (0, _initialRouterState2.default)({ pathname: pathname, query: query || {}, routes: routes, history: history }) }) : initialState, enhancer); var matchRoute = createMatcher(routes); history.listen(function (location) { if (location) { store.dispatch(locationDidChange({ location: location, matchRoute: matchRoute })); } }); var dispatch = function dispatch(action) { switch (action.type) { case _actionTypes.PUSH: history.push(action.payload); return null; case _actionTypes.REPLACE: history.replace(action.payload); return null; case _actionTypes.GO: history.go(action.payload); return null; case _actionTypes.GO_BACK: history.goBack(); return null; case _actionTypes.GO_FORWARD: history.goForward(); return null; default: // We return the result of dispatch here // to retain compatibility with enhancers // that return a promise from dispatch. return store.dispatch(action); } }; return _extends({}, store, { dispatch: dispatch, history: history, matchRoute: matchRoute }); }; }; }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _invariant = __webpack_require__(4); var _invariant2 = _interopRequireDefault(_invariant); var _ExecutionEnvironment = __webpack_require__(5); var _BrowserProtocol = __webpack_require__(6); var BrowserProtocol = _interopRequireWildcard(_BrowserProtocol); var _RefreshProtocol = __webpack_require__(13); var RefreshProtocol = _interopRequireWildcard(_RefreshProtocol); var _DOMUtils = __webpack_require__(11); var _createHistory = __webpack_require__(14); var _createHistory2 = _interopRequireDefault(_createHistory); 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 }; } /** * Creates and returns a history object that uses HTML5's history API * (pushState, replaceState, and the popstate event) to manage history. * This is the recommended method of managing history in browsers because * it provides the cleanest URLs. * * Note: In browsers that do not support the HTML5 history API full * page reloads will be used to preserve clean URLs. You can force this * behavior using { forceRefresh: true } in options. */ var createBrowserHistory = function createBrowserHistory() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; !_ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Browser history needs a DOM') : (0, _invariant2.default)(false) : void 0; var useRefresh = options.forceRefresh || !(0, _DOMUtils.supportsHistory)(); var Protocol = useRefresh ? RefreshProtocol : BrowserProtocol; var getUserConfirmation = Protocol.getUserConfirmation; var getCurrentLocation = Protocol.getCurrentLocation; var pushLocation = Protocol.pushLocation; var replaceLocation = Protocol.replaceLocation; var go = Protocol.go; var history = (0, _createHistory2.default)(_extends({ getUserConfirmation: getUserConfirmation }, options, { getCurrentLocation: getCurrentLocation, pushLocation: pushLocation, replaceLocation: replaceLocation, go: go })); var listenerCount = 0, stopListener = void 0; var startListener = function startListener(listener, before) { if (++listenerCount === 1) stopListener = BrowserProtocol.startListener(history.transitionTo); var unlisten = before ? history.listenBefore(listener) : history.listen(listener); return function () { unlisten(); if (--listenerCount === 0) stopListener(); }; }; var listenBefore = function listenBefore(listener) { return startListener(listener, true); }; var listen = function listen(listener) { return startListener(listener, false); }; return _extends({}, history, { listenBefore: listenBefore, listen: listen }); }; exports.default = createBrowserHistory; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 3 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; (function () { try { cachedSetTimeout = setTimeout; } catch (e) { cachedSetTimeout = function () { throw new Error('setTimeout is not defined'); } } try { cachedClearTimeout = clearTimeout; } catch (e) { cachedClearTimeout = function () { throw new Error('clearTimeout is not defined'); } } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { 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]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 5 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var canUseDOM = exports.canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.go = exports.replaceLocation = exports.pushLocation = exports.startListener = exports.getUserConfirmation = exports.getCurrentLocation = undefined; var _LocationUtils = __webpack_require__(7); var _DOMUtils = __webpack_require__(11); var _DOMStateStorage = __webpack_require__(12); var _PathUtils = __webpack_require__(8); /* eslint-disable no-alert */ var PopStateEvent = 'popstate'; var _createLocation = function _createLocation(historyState) { var key = historyState && historyState.key; return (0, _LocationUtils.createLocation)({ pathname: window.location.pathname, search: window.location.search, hash: window.location.hash, state: key ? (0, _DOMStateStorage.readState)(key) : undefined }, undefined, key); }; var getCurrentLocation = exports.getCurrentLocation = function getCurrentLocation() { var historyState = void 0; try { historyState = window.history.state || {}; } catch (error) { // IE 11 sometimes throws when accessing window.history.state // See https://github.com/mjackson/history/pull/289 historyState = {}; } return _createLocation(historyState); }; var getUserConfirmation = exports.getUserConfirmation = function getUserConfirmation(message, callback) { return callback(window.confirm(message)); }; var startListener = exports.startListener = function startListener(listener) { var handlePopState = function handlePopState(event) { if (event.state !== undefined) // Ignore extraneous popstate events in WebKit listener(_createLocation(event.state)); }; (0, _DOMUtils.addEventListener)(window, PopStateEvent, handlePopState); return function () { return (0, _DOMUtils.removeEventListener)(window, PopStateEvent, handlePopState); }; }; var updateLocation = function updateLocation(location, updateState) { var state = location.state; var key = location.key; if (state !== undefined) (0, _DOMStateStorage.saveState)(key, state); updateState({ key: key }, (0, _PathUtils.createPath)(location)); }; var pushLocation = exports.pushLocation = function pushLocation(location) { return updateLocation(location, function (state, path) { return window.history.pushState(state, null, path); }); }; var replaceLocation = exports.replaceLocation = function replaceLocation(location) { return updateLocation(location, function (state, path) { return window.history.replaceState(state, null, path); }); }; var go = exports.go = function go(n) { if (n) window.history.go(n); }; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.locationsAreEqual = exports.statesAreEqual = exports.createLocation = exports.createQuery = undefined; 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; }; var _invariant = __webpack_require__(4); var _invariant2 = _interopRequireDefault(_invariant); var _PathUtils = __webpack_require__(8); var _Actions = __webpack_require__(10); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var createQuery = exports.createQuery = function createQuery(props) { return _extends(Object.create(null), props); }; var createLocation = exports.createLocation = function createLocation() { var input = arguments.length <= 0 || arguments[0] === undefined ? '/' : arguments[0]; var action = arguments.length <= 1 || arguments[1] === undefined ? _Actions.POP : arguments[1]; var key = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; var object = typeof input === 'string' ? (0, _PathUtils.parsePath)(input) : input; var pathname = object.pathname || '/'; var search = object.search || ''; var hash = object.hash || ''; var state = object.state; return { pathname: pathname, search: search, hash: hash, state: state, action: action, key: key }; }; var isDate = function isDate(object) { return Object.prototype.toString.call(object) === '[object Date]'; }; var statesAreEqual = exports.statesAreEqual = function statesAreEqual(a, b) { if (a === b) return true; var typeofA = typeof a === 'undefined' ? 'undefined' : _typeof(a); var typeofB = typeof b === 'undefined' ? 'undefined' : _typeof(b); if (typeofA !== typeofB) return false; !(typeofA !== 'function') ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'You must not store functions in location state') : (0, _invariant2.default)(false) : void 0; // Not the same object, but same type. if (typeofA === 'object') { !!(isDate(a) && isDate(b)) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'You must not store Date objects in location state') : (0, _invariant2.default)(false) : void 0; if (!Array.isArray(a)) return Object.keys(a).every(function (key) { return statesAreEqual(a[key], b[key]); }); return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return statesAreEqual(item, b[index]); }); } // All other serializable types (string, number, boolean) // should be strict equal. return false; }; var locationsAreEqual = exports.locationsAreEqual = function locationsAreEqual(a, b) { return a.key === b.key && // a.action === b.action && // Different action !== location change. a.pathname === b.pathname && a.search === b.search && a.hash === b.hash && statesAreEqual(a.state, b.state); }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.createPath = exports.parsePath = exports.getQueryStringValueFromPath = exports.stripQueryStringValueFromPath = exports.addQueryStringValueToPath = exports.isAbsolutePath = undefined; var _warning = __webpack_require__(9); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var isAbsolutePath = exports.isAbsolutePath = function isAbsolutePath(path) { return typeof path === 'string' && path.charAt(0) === '/'; }; var addQueryStringValueToPath = exports.addQueryStringValueToPath = function addQueryStringValueToPath(path, key, value) { var _parsePath = parsePath(path); var pathname = _parsePath.pathname; var search = _parsePath.search; var hash = _parsePath.hash; return createPath({ pathname: pathname, search: search + (search.indexOf('?') === -1 ? '?' : '&') + key + '=' + value, hash: hash }); }; var stripQueryStringValueFromPath = exports.stripQueryStringValueFromPath = function stripQueryStringValueFromPath(path, key) { var _parsePath2 = parsePath(path); var pathname = _parsePath2.pathname; var search = _parsePath2.search; var hash = _parsePath2.hash; return createPath({ pathname: pathname, search: search.replace(new RegExp('([?&])' + key + '=[a-zA-Z0-9]+(&?)'), function (match, prefix, suffix) { return prefix === '?' ? prefix : suffix; }), hash: hash }); }; var getQueryStringValueFromPath = exports.getQueryStringValueFromPath = function getQueryStringValueFromPath(path, key) { var _parsePath3 = parsePath(path); var search = _parsePath3.search; var match = search.match(new RegExp('[?&]' + key + '=([a-zA-Z0-9]+)')); return match && match[1]; }; var extractPath = function extractPath(string) { var match = string.match(/^(https?:)?\/\/[^\/]*/); return match == null ? string : string.substring(match[0].length); }; var parsePath = exports.parsePath = function parsePath(path) { var pathname = extractPath(path); var search = ''; var hash = ''; process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(path === pathname, 'A path must be pathname + search + hash only, not a full URL like "%s"', path) : void 0; var hashIndex = pathname.indexOf('#'); if (hashIndex !== -1) { hash = pathname.substring(hashIndex); pathname = pathname.substring(0, hashIndex); } var searchIndex = pathname.indexOf('?'); if (searchIndex !== -1) { search = pathname.substring(searchIndex); pathname = pathname.substring(0, searchIndex); } if (pathname === '') pathname = '/'; return { pathname: pathname, search: search, hash: hash }; }; var createPath = exports.createPath = function createPath(location) { if (location == null || typeof location === 'string') return location; var basename = location.basename; var pathname = location.pathname; var search = location.search; var hash = location.hash; var path = (basename || '') + pathname; if (search && search !== '?') path += search; if (hash) path += hash; return path; }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = function() {}; if (process.env.NODE_ENV !== 'production') { warning = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 10 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * Indicates that navigation was caused by a call to history.push. */ var PUSH = exports.PUSH = 'PUSH'; /** * Indicates that navigation was caused by a call to history.replace. */ var REPLACE = exports.REPLACE = 'REPLACE'; /** * Indicates that navigation was caused by some other action such * as using a browser's back/forward buttons and/or manually manipulating * the URL in a browser's location bar. This is the default. * * See https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate * for more information. */ var POP = exports.POP = 'POP'; /***/ }, /* 11 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var addEventListener = exports.addEventListener = function addEventListener(node, event, listener) { return node.addEventListener ? node.addEventListener(event, listener, false) : node.attachEvent('on' + event, listener); }; var removeEventListener = exports.removeEventListener = function removeEventListener(node, event, listener) { return node.removeEventListener ? node.removeEventListener(event, listener, false) : node.detachEvent('on' + event, listener); }; /** * Returns true if the HTML5 history API is supported. Taken from Modernizr. * * https://github.com/Modernizr/Modernizr/blob/master/LICENSE * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586 */ var supportsHistory = exports.supportsHistory = function supportsHistory() { var ua = window.navigator.userAgent; if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false; return window.history && 'pushState' in window.history; }; /** * Returns false if using go(n) with hash history causes a full page reload. */ var supportsGoWithoutReloadUsingHash = exports.supportsGoWithoutReloadUsingHash = function supportsGoWithoutReloadUsingHash() { return window.navigator.userAgent.indexOf('Firefox') === -1; }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.readState = exports.saveState = undefined; var _warning = __webpack_require__(9); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var QuotaExceededErrors = ['QuotaExceededError', 'QUOTA_EXCEEDED_ERR']; /* eslint-disable no-empty */ var SecurityError = 'SecurityError'; var KeyPrefix = '@@History/'; var createKey = function createKey(key) { return KeyPrefix + key; }; var saveState = exports.saveState = function saveState(key, state) { if (!window.sessionStorage) { // Session storage is not available or hidden. // sessionStorage is undefined in Internet Explorer when served via file protocol. process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(false, '[history] Unable to save state; sessionStorage is not available') : void 0; return; } try { if (state == null) { window.sessionStorage.removeItem(createKey(key)); } else { window.sessionStorage.setItem(createKey(key), JSON.stringify(state)); } } catch (error) { if (error.name === SecurityError) { // Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any // attempt to access window.sessionStorage. process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(false, '[history] Unable to save state; sessionStorage is not available due to security settings') : void 0; return; } if (QuotaExceededErrors.indexOf(error.name) >= 0 && window.sessionStorage.length === 0) { // Safari "private mode" throws QuotaExceededError. process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(false, '[history] Unable to save state; sessionStorage is not available in Safari private mode') : void 0; return; } throw error; } }; var readState = exports.readState = function readState(key) { var json = void 0; try { json = window.sessionStorage.getItem(createKey(key)); } catch (error) { if (error.name === SecurityError) { // Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any // attempt to access window.sessionStorage. process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(false, '[history] Unable to read state; sessionStorage is not available due to security settings') : void 0; return undefined; } } if (json) { try { return JSON.parse(json); } catch (error) { // Ignore invalid JSON. } } return undefined; }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.replaceLocation = exports.pushLocation = exports.getCurrentLocation = exports.go = exports.getUserConfirmation = undefined; var _BrowserProtocol = __webpack_require__(6); Object.defineProperty(exports, 'getUserConfirmation', { enumerable: true, get: function get() { return _BrowserProtocol.getUserConfirmation; } }); Object.defineProperty(exports, 'go', { enumerable: true, get: function get() { return _BrowserProtocol.go; } }); var _LocationUtils = __webpack_require__(7); var _PathUtils = __webpack_require__(8); var getCurrentLocation = exports.getCurrentLocation = function getCurrentLocation() { return (0, _LocationUtils.createLocation)(window.location); }; var pushLocation = exports.pushLocation = function pushLocation(location) { window.location.href = (0, _PathUtils.createPath)(location); return false; // Don't update location }; var replaceLocation = exports.replaceLocation = function replaceLocation(location) { window.location.replace((0, _PathUtils.createPath)(location)); return false; // Don't update location }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _AsyncUtils = __webpack_require__(15); var _PathUtils = __webpack_require__(8); var _runTransitionHook = __webpack_require__(16); var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook); var _Actions = __webpack_require__(10); var _LocationUtils = __webpack_require__(7); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var createHistory = function createHistory() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var getCurrentLocation = options.getCurrentLocation; var getUserConfirmation = options.getUserConfirmation; var pushLocation = options.pushLocation; var replaceLocation = options.replaceLocation; var go = options.go; var keyLength = options.keyLength; var currentLocation = void 0; var pendingLocation = void 0; var beforeListeners = []; var listeners = []; var allKeys = []; var getCurrentIndex = function getCurrentIndex() { if (pendingLocation && pendingLocation.action === _Actions.POP) return allKeys.indexOf(pendingLocation.key); if (currentLocation) return allKeys.indexOf(currentLocation.key); return -1; }; var updateLocation = function updateLocation(nextLocation) { currentLocation = nextLocation; var currentIndex = getCurrentIndex(); if (currentLocation.action === _Actions.PUSH) { allKeys = [].concat(_toConsumableArray(allKeys.slice(0, currentIndex + 1)), [currentLocation.key]); } else if (currentLocation.action === _Actions.REPLACE) { allKeys[currentIndex] = currentLocation.key; } listeners.forEach(function (listener) { return listener(currentLocation); }); }; var listenBefore = function listenBefore(listener) { beforeListeners.push(listener); return function () { return beforeListeners = beforeListeners.filter(function (item) { return item !== listener; }); }; }; var listen = function listen(listener) { listeners.push(listener); return function () { return listeners = listeners.filter(function (item) { return item !== listener; }); }; }; var confirmTransitionTo = function confirmTransitionTo(location, callback) { (0, _AsyncUtils.loopAsync)(beforeListeners.length, function (index, next, done) { (0, _runTransitionHook2.default)(beforeListeners[index], location, function (result) { return result != null ? done(result) : next(); }); }, function (message) { if (getUserConfirmation && typeof message === 'string') { getUserConfirmation(message, function (ok) { return callback(ok !== false); }); } else { callback(message !== false); } }); }; var transitionTo = function transitionTo(nextLocation) { if (currentLocation && (0, _LocationUtils.locationsAreEqual)(currentLocation, nextLocation) || pendingLocation && (0, _LocationUtils.locationsAreEqual)(pendingLocation, nextLocation)) return; // Nothing to do pendingLocation = nextLocation; confirmTransitionTo(nextLocation, function (ok) { if (pendingLocation !== nextLocation) return; // Transition was interrupted during confirmation pendingLocation = null; if (ok) { // Treat PUSH to same path like REPLACE to be consistent with browsers if (nextLocation.action === _Actions.PUSH) { var prevPath = (0, _PathUtils.createPath)(currentLocation); var nextPath = (0, _PathUtils.createPath)(nextLocation); if (nextPath === prevPath && (0, _LocationUtils.statesAreEqual)(currentLocation.state, nextLocation.state)) nextLocation.action = _Actions.REPLACE; } if (nextLocation.action === _Actions.POP) { updateLocation(nextLocation); } else if (nextLocation.action === _Actions.PUSH) { if (pushLocation(nextLocation) !== false) updateLocation(nextLocation); } else if (nextLocation.action === _Actions.REPLACE) { if (replaceLocation(nextLocation) !== false) updateLocation(nextLocation); } } else if (currentLocation && nextLocation.action === _Actions.POP) { var prevIndex = allKeys.indexOf(currentLocation.key); var nextIndex = allKeys.indexOf(nextLocation.key); if (prevIndex !== -1 && nextIndex !== -1) go(prevIndex - nextIndex); // Restore the URL } }); }; var push = function push(input) { return transitionTo(createLocation(input, _Actions.PUSH)); }; var replace = function replace(input) { return transitionTo(createLocation(input, _Actions.REPLACE)); }; var goBack = function goBack() { return go(-1); }; var goForward = function goForward() { return go(1); }; var createKey = function createKey() { return Math.random().toString(36).substr(2, keyLength || 6); }; var createHref = function createHref(location) { return (0, _PathUtils.createPath)(location); }; var createLocation = function createLocation(location, action) { var key = arguments.length <= 2 || arguments[2] === undefined ? createKey() : arguments[2]; return (0, _LocationUtils.createLocation)(location, action, key); }; return { getCurrentLocation: getCurrentLocation, listenBefore: listenBefore, listen: listen, transitionTo: transitionTo, push: push, replace: replace, go: go, goBack: goBack, goForward: goForward, createKey: createKey, createPath: _PathUtils.createPath, createHref: createHref, createLocation: createLocation }; }; exports.default = createHistory; /***/ }, /* 15 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var loopAsync = exports.loopAsync = function loopAsync(turns, work, callback) { var currentTurn = 0, isDone = false; var isSync = false, hasNext = false, doneArgs = void 0; var done = function done() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } isDone = true; if (isSync) { // Iterate instead of recursing if possible. doneArgs = args; return; } callback.apply(undefined, args); }; var next = function next() { if (isDone) return; hasNext = true; if (isSync) return; // Iterate instead of recursing if possible. isSync = true; while (!isDone && currentTurn < turns && hasNext) { hasNext = false; work(currentTurn++, next, done); } isSync = false; if (isDone) { // This means the loop finished synchronously. callback.apply(undefined, _toConsumableArray(doneArgs)); return; } if (currentTurn >= turns && hasNext) { isDone = true; callback(); } }; next(); }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _warning = __webpack_require__(9); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var runTransitionHook = function runTransitionHook(hook, location, callback) { var result = hook(location, callback); if (hook.length < 2) { // Assume the hook runs synchronously and automatically // call the callback with the return value. callback(result); } else { process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(result === undefined, 'You should not "return" in a transition hook with a callback argument; ' + 'call the callback instead') : void 0; } }; exports.default = runTransitionHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _warning = __webpack_require__(9); var _warning2 = _interopRequireDefault(_warning); var _invariant = __webpack_require__(4); var _invariant2 = _interopRequireDefault(_invariant); var _LocationUtils = __webpack_require__(7); var _PathUtils = __webpack_require__(8); var _createHistory = __webpack_require__(14); var _createHistory2 = _interopRequireDefault(_createHistory); var _Actions = __webpack_require__(10); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var createStateStorage = function createStateStorage(entries) { return entries.filter(function (entry) { return entry.state; }).reduce(function (memo, entry) { memo[entry.key] = entry.state; return memo; }, {}); }; var createMemoryHistory = function createMemoryHistory() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (Array.isArray(options)) { options = { entries: options }; } else if (typeof options === 'string') { options = { entries: [options] }; } var getCurrentLocation = function getCurrentLocation() { var entry = entries[current]; var path = (0, _PathUtils.createPath)(entry); var key = void 0, state = void 0; if (entry.key) { key = entry.key; state = readState(key); } var init = (0, _PathUtils.parsePath)(path); return (0, _LocationUtils.createLocation)(_extends({}, init, { state: state }), undefined, key); }; var canGo = function canGo(n) { var index = current + n; return index >= 0 && index < entries.length; }; var go = function go(n) { if (!n) return; if (!canGo(n)) { process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(false, 'Cannot go(%s) there is not enough history', n) : void 0; return; } current += n; var currentLocation = getCurrentLocation(); // Change action to POP history.transitionTo(_extends({}, currentLocation, { action: _Actions.POP })); }; var pushLocation = function pushLocation(location) { current += 1; if (current < entries.length) entries.splice(current); entries.push(location); saveState(location.key, location.state); }; var replaceLocation = function replaceLocation(location) { entries[current] = location; saveState(location.key, location.state); }; var history = (0, _createHistory2.default)(_extends({}, options, { getCurrentLocation: getCurrentLocation, pushLocation: pushLocation, replaceLocation: replaceLocation, go: go })); var _options = options; var entries = _options.entries; var current = _options.current; if (typeof entries === 'string') { entries = [entries]; } else if (!Array.isArray(entries)) { entries = ['/']; } entries = entries.map(function (entry) { return (0, _LocationUtils.createLocation)(entry); }); if (current == null) { current = entries.length - 1; } else { !(current >= 0 && current < entries.length) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'Current index must be >= 0 and < %s, was %s', entries.length, current) : (0, _invariant2.default)(false) : void 0; } var storage = createStateStorage(entries); var saveState = function saveState(key, state) { return storage[key] = state; }; var readState = function readState(key) { return storage[key]; }; return history; }; exports.default = createMemoryHistory; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _runTransitionHook = __webpack_require__(16); var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook); var _PathUtils = __webpack_require__(8); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var useBasename = function useBasename(createHistory) { return function () { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var history = createHistory(options); var basename = options.basename; var addBasename = function addBasename(location) { if (!location) return location; if (basename && location.basename == null) { if (location.pathname.indexOf(basename) === 0) { location.pathname = location.pathname.substring(basename.length); location.basename = basename; if (location.pathname === '') location.pathname = '/'; } else { location.basename = ''; } } return location; }; var prependBasename = function prependBasename(location) { if (!basename) return location; var object = typeof location === 'string' ? (0, _PathUtils.parsePath)(location) : location; var pname = object.pathname; var normalizedBasename = basename.slice(-1) === '/' ? basename : basename + '/'; var normalizedPathname = pname.charAt(0) === '/' ? pname.slice(1) : pname; var pathname = normalizedBasename + normalizedPathname; return _extends({}, location, { pathname: pathname }); }; // Override all read methods with basename-aware versions. var getCurrentLocation = function getCurrentLocation() { return addBasename(history.getCurrentLocation()); }; var listenBefore = function listenBefore(hook) { return history.listenBefore(function (location, callback) { return (0, _runTransitionHook2.default)(hook, addBasename(location), callback); }); }; var listen = function listen(listener) { return history.listen(function (location) { return listener(addBasename(location)); }); }; // Override all write methods with basename-aware versions. var push = function push(location) { return history.push(prependBasename(location)); }; var replace = function replace(location) { return history.replace(prependBasename(location)); }; var createPath = function createPath(location) { return history.createPath(prependBasename(location)); }; var createHref = function createHref(location) { return history.createHref(prependBasename(location)); }; var createLocation = function createLocation(location) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return addBasename(history.createLocation.apply(history, [prependBasename(location)].concat(args))); }; return _extends({}, history, { getCurrentLocation: getCurrentLocation, listenBefore: listenBefore, listen: listen, push: push, replace: replace, createPath: createPath, createHref: createHref, createLocation: createLocation }); }; }; exports.default = useBasename; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _queryString = __webpack_require__(20); var _runTransitionHook = __webpack_require__(16); var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook); var _LocationUtils = __webpack_require__(7); var _PathUtils = __webpack_require__(8); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultStringifyQuery = function defaultStringifyQuery(query) { return (0, _queryString.stringify)(query).replace(/%20/g, '+'); }; var defaultParseQueryString = _queryString.parse; /** * Returns a new createHistory function that may be used to create * history objects that know how to handle URL queries. */ var useQueries = function useQueries(createHistory) { return function () { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var history = createHistory(options); var stringifyQuery = options.stringifyQuery; var parseQueryString = options.parseQueryString; if (typeof stringifyQuery !== 'function') stringifyQuery = defaultStringifyQuery; if (typeof parseQueryString !== 'function') parseQueryString = defaultParseQueryString; var decodeQuery = function decodeQuery(location) { if (!location) return location; if (location.query == null) location.query = parseQueryString(location.search.substring(1)); return location; }; var encodeQuery = function encodeQuery(location, query) { if (query == null) return location; var object = typeof location === 'string' ? (0, _PathUtils.parsePath)(location) : location; var queryString = stringifyQuery(query); var search = queryString ? '?' + queryString : ''; return _extends({}, object, { search: search }); }; // Override all read methods with query-aware versions. var getCurrentLocation = function getCurrentLocation() { return decodeQuery(history.getCurrentLocation()); }; var listenBefore = function listenBefore(hook) { return history.listenBefore(function (location, callback) { return (0, _runTransitionHook2.default)(hook, decodeQuery(location), callback); }); }; var listen = function listen(listener) { return history.listen(function (location) { return listener(decodeQuery(location)); }); }; // Override all write methods with query-aware versions. var push = function push(location) { return history.push(encodeQuery(location, location.query)); }; var replace = function replace(location) { return history.replace(encodeQuery(location, location.query)); }; var createPath = function createPath(location) { return history.createPath(encodeQuery(location, location.query)); }; var createHref = function createHref(location) { return history.createHref(encodeQuery(location, location.query)); }; var createLocation = function createLocation(location) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var newLocation = history.createLocation.apply(history, [encodeQuery(location, location.query)].concat(args)); if (location.query) newLocation.query = (0, _LocationUtils.createQuery)(location.query); return decodeQuery(newLocation); }; return _extends({}, history, { getCurrentLocation: getCurrentLocation, listenBefore: listenBefore, listen: listen, push: push, replace: replace, createPath: createPath, createHref: createHref, createLocation: createLocation }); }; }; exports.default = useQueries; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strictUriEncode = __webpack_require__(21); var objectAssign = __webpack_require__(22); function encode(value, opts) { if (opts.encode) { return opts.strict ? strictUriEncode(value) : encodeURIComponent(value); } return value; } exports.extract = function (str) { return str.split('?')[1] || ''; }; exports.parse = function (str) { // Create an object with no prototype // https://github.com/sindresorhus/query-string/issues/47 var ret = Object.create(null); if (typeof str !== 'string') { return ret; } str = str.trim().replace(/^(\?|#|&)/, ''); if (!str) { return ret; } str.split('&').forEach(function (param) { var parts = param.replace(/\+/g, ' ').split('='); // Firefox (pre 40) decodes `%3D` to `=` // https://github.com/sindresorhus/query-string/pull/37 var key = parts.shift(); var val = parts.length > 0 ? parts.join('=') : undefined; key = decodeURIComponent(key); // missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters val = val === undefined ? null : decodeURIComponent(val); if (ret[key] === undefined) { ret[key] = val; } else if (Array.isArray(ret[key])) { ret[key].push(val); } else { ret[key] = [ret[key], val]; } }); return ret; }; exports.stringify = function (obj, opts) { var defaults = { encode: true, strict: true }; opts = objectAssign(defaults, opts); return obj ? Object.keys(obj).sort().map(function (key) { var val = obj[key]; if (val === undefined) { return ''; } if (val === null) { return encode(key, opts); } if (Array.isArray(val)) { var result = []; val.slice().forEach(function (val2) { if (val2 === undefined) { return; } if (val2 === null) { result.push(encode(key, opts)); } else { result.push(encode(key, opts) + '=' + encode(val2, opts)); } }); return result.join('&'); } return encode(key, opts) + '=' + encode(val, opts); }).filter(function (x) { return x.length > 0; }).join('&') : ''; }; /***/ }, /* 21 */ /***/ function(module, exports) { 'use strict'; module.exports = function (str) { return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); }); }; /***/ }, /* 22 */ /***/ function(module, exports) { 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }, /* 23 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var LOCATION_CHANGED = exports.LOCATION_CHANGED = 'ROUTER_LOCATION_CHANGED'; var PUSH = exports.PUSH = 'ROUTER_PUSH'; var REPLACE = exports.REPLACE = 'ROUTER_REPLACE'; var GO = exports.GO = 'ROUTER_GO'; var GO_BACK = exports.GO_BACK = 'ROUTER_GO_BACK'; var GO_FORWARD = exports.GO_FORWARD = 'ROUTER_GO_FORWARD'; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _urlPattern = __webpack_require__(25); var _urlPattern2 = _interopRequireDefault(_urlPattern); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (routes) { var routeList = Object.keys(routes).map(function (route) { return { route: route, pattern: new _urlPattern2.default(route), result: routes[route] }; }); return function (incomingUrl) { // Discard query strings var route = incomingUrl.split('?')[0]; // eslint-disable-line no-magic-numbers // Find the route that matches the URL for (var i = 0; i < routeList.length; i++) { var storedRoute = routeList[i]; var match = storedRoute.pattern.match(route); if (match) { // Return the matched params and user-defined result object return { route: storedRoute.route, params: match, result: storedRoute.result }; } } return null; }; }; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Generated by CoffeeScript 1.10.0 var slice = [].slice; (function(root, factory) { if (('function' === "function") && (__webpack_require__(26) != null)) { return !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports !== "undefined" && exports !== null) { return module.exports = factory(); } else { return root.UrlPattern = factory(); } })(this, function() { var P, UrlPattern, astNodeContainsSegmentsForProvidedParams, astNodeToNames, astNodeToRegexString, baseAstNodeToRegexString, concatMap, defaultOptions, escapeForRegex, getParam, keysAndValuesToObject, newParser, regexGroupCount, stringConcatMap, stringify; escapeForRegex = function(string) { return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }; concatMap = function(array, f) { var i, length, results; results = []; i = -1; length = array.length; while (++i < length) { results = results.concat(f(array[i])); } return results; }; stringConcatMap = function(array, f) { var i, length, result; result = ''; i = -1; length = array.length; while (++i < length) { result += f(array[i]); } return result; }; regexGroupCount = function(regex) { return (new RegExp(regex.toString() + '|')).exec('').length - 1; }; keysAndValuesToObject = function(keys, values) { var i, key, length, object, value; object = {}; i = -1; length = keys.length; while (++i < length) { key = keys[i]; value = values[i]; if (value == null) { continue; } if (object[key] != null) { if (!Array.isArray(object[key])) { object[key] = [object[key]]; } object[key].push(value); } else { object[key] = value; } } return object; }; P = {}; P.Result = function(value, rest) { this.value = value; this.rest = rest; }; P.Tagged = function(tag, value) { this.tag = tag; this.value = value; }; P.tag = function(tag, parser) { return function(input) { var result, tagged; result = parser(input); if (result == null) { return; } tagged = new P.Tagged(tag, result.value); return new P.Result(tagged, result.rest); }; }; P.regex = function(regex) { return function(input) { var matches, result; matches = regex.exec(input); if (matches == null) { return; } result = matches[0]; return new P.Result(result, input.slice(result.length)); }; }; P.sequence = function() { var parsers; parsers = 1 <= arguments.length ? slice.call(arguments, 0) : []; return function(input) { var i, length, parser, rest, result, values; i = -1; length = parsers.length; values = []; rest = input; while (++i < length) { parser = parsers[i]; result = parser(rest); if (result == null) { return; } values.push(result.value); rest = result.rest; } return new P.Result(values, rest); }; }; P.pick = function() { var indexes, parsers; indexes = arguments[0], parsers = 2 <= arguments.length ? slice.call(arguments, 1) : []; return function(input) { var array, result; result = P.sequence.apply(P, parsers)(input); if (result == null) { return; } array = result.value; result.value = array[indexes]; return result; }; }; P.string = function(string) { var length; length = string.length; return function(input) { if (input.slice(0, length) === string) { return new P.Result(string, input.slice(length)); } }; }; P.lazy = function(fn) { var cached; cached = null; return function(input) { if (cached == null) { cached = fn(); } return cached(input); }; }; P.baseMany = function(parser, end, stringResult, atLeastOneResultRequired, input) { var endResult, parserResult, rest, results; rest = input; results = stringResult ? '' : []; while (true) { if (end != null) { endResult = end(rest); if (endResult != null) { break; } } parserResult = parser(rest); if (parserResult == null) { break; } if (stringResult) { results += parserResult.value; } else { results.push(parserResult.value); } rest = parserResult.rest; } if (atLeastOneResultRequired && results.length === 0) { return; } return new P.Result(results, rest); }; P.many1 = function(parser) { return function(input) { return P.baseMany(parser, null, false, true, input); }; }; P.concatMany1Till = function(parser, end) { return function(input) { return P.baseMany(parser, end, true, true, input); }; }; P.firstChoice = function() { var parsers; parsers = 1 <= arguments.length ? slice.call(arguments, 0) : []; return function(input) { var i, length, parser, result; i = -1; length = parsers.length; while (++i < length) { parser = parsers[i]; result = parser(input); if (result != null) { return result; } } }; }; newParser = function(options) { var U; U = {}; U.wildcard = P.tag('wildcard', P.string(options.wildcardChar)); U.optional = P.tag('optional', P.pick(1, P.string(options.optionalSegmentStartChar), P.lazy(function() { return U.pattern; }), P.string(options.optionalSegmentEndChar))); U.name = P.regex(new RegExp("^[" + options.segmentNameCharset + "]+")); U.named = P.tag('named', P.pick(1, P.string(options.segmentNameStartChar), P.lazy(function() { return U.name; }))); U.escapedChar = P.pick(1, P.string(options.escapeChar), P.regex(/^./)); U["static"] = P.tag('static', P.concatMany1Till(P.firstChoice(P.lazy(function() { return U.escapedChar; }), P.regex(/^./)), P.firstChoice(P.string(options.segmentNameStartChar), P.string(options.optionalSegmentStartChar), P.string(options.optionalSegmentEndChar), U.wildcard))); U.token = P.lazy(function() { return P.firstChoice(U.wildcard, U.optional, U.named, U["static"]); }); U.pattern = P.many1(P.lazy(function() { return U.token; })); return U; }; defaultOptions = { escapeChar: '\\', segmentNameStartChar: ':', segmentValueCharset: 'a-zA-Z0-9-_~ %', segmentNameCharset: 'a-zA-Z0-9', optionalSegmentStartChar: '(', optionalSegmentEndChar: ')', wildcardChar: '*' }; baseAstNodeToRegexString = function(astNode, segmentValueCharset) { if (Array.isArray(astNode)) { return stringConcatMap(astNode, function(node) { return baseAstNodeToRegexString(node, segmentValueCharset); }); } switch (astNode.tag) { case 'wildcard': return '(.*?)'; case 'named': return "([" + segmentValueCharset + "]+)"; case 'static': return escapeForRegex(astNode.value); case 'optional': return '(?:' + baseAstNodeToRegexString(astNode.value, segmentValueCharset) + ')?'; } }; astNodeToRegexString = function(astNode, segmentValueCharset) { if (segmentValueCharset == null) { segmentValueCharset = defaultOptions.segmentValueCharset; } return '^' + baseAstNodeToRegexString(astNode, segmentValueCharset) + '$'; }; astNodeToNames = function(astNode) { if (Array.isArray(astNode)) { return concatMap(astNode, astNodeToNames); } switch (astNode.tag) { case 'wildcard': return ['_']; case 'named': return [astNode.value]; case 'static': return []; case 'optional': return astNodeToNames(astNode.value); } }; getParam = function(params, key, nextIndexes, sideEffects) { var index, maxIndex, result, value; if (sideEffects == null) { sideEffects = false; } value = params[key]; if (value == null) { if (sideEffects) { throw new Error("no values provided for key `" + key + "`"); } else { return; } } index = nextIndexes[key] || 0; maxIndex = Array.isArray(value) ? value.length - 1 : 0; if (index > maxIndex) { if (sideEffects) { throw new Error("too few values provided for key `" + key + "`"); } else { return; } } result = Array.isArray(value) ? value[index] : value; if (sideEffects) { nextIndexes[key] = index + 1; } return result; }; astNodeContainsSegmentsForProvidedParams = function(astNode, params, nextIndexes) { var i, length; if (Array.isArray(astNode)) { i = -1; length = astNode.length; while (++i < length) { if (astNodeContainsSegmentsForProvidedParams(astNode[i], params, nextIndexes)) { return true; } } return false; } switch (astNode.tag) { case 'wildcard': return getParam(params, '_', nextIndexes, false) != null; case 'named': return getParam(params, astNode.value, nextIndexes, false) != null; case 'static': return false; case 'optional': return astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes); } }; stringify = function(astNode, params, nextIndexes) { if (Array.isArray(astNode)) { return stringConcatMap(astNode, function(node) { return stringify(node, params, nextIndexes); }); } switch (astNode.tag) { case 'wildcard': return getParam(params, '_', nextIndexes, true); case 'named': return getParam(params, astNode.value, nextIndexes, true); case 'static': return astNode.value; case 'optional': if (astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes)) { return stringify(astNode.value, params, nextIndexes); } else { return ''; } } }; UrlPattern = function(arg1, arg2) { var groupCount, options, parsed, parser, withoutWhitespace; if (arg1 instanceof UrlPattern) { this.isRegex = arg1.isRegex; this.regex = arg1.regex; this.ast = arg1.ast; this.names = arg1.names; return; } this.isRegex = arg1 instanceof RegExp; if (!(('string' === typeof arg1) || this.isRegex)) { throw new TypeError('argument must be a regex or a string'); } if (this.isRegex) { this.regex = arg1; if (arg2 != null) { if (!Array.isArray(arg2)) { throw new Error('if first argument is a regex the second argument may be an array of group names but you provided something else'); } groupCount = regexGroupCount(this.regex); if (arg2.length !== groupCount) { throw new Error("regex contains " + groupCount + " groups but array of group names contains " + arg2.length); } this.names = arg2; } return; } if (arg1 === '') { throw new Error('argument must not be the empty string'); } withoutWhitespace = arg1.replace(/\s+/g, ''); if (withoutWhitespace !== arg1) { throw new Error('argument must not contain whitespace'); } options = { escapeChar: (arg2 != null ? arg2.escapeChar : void 0) || defaultOptions.escapeChar, segmentNameStartChar: (arg2 != null ? arg2.segmentNameStartChar : void 0) || defaultOptions.segmentNameStartChar, segmentNameCharset: (arg2 != null ? arg2.segmentNameCharset : void 0) || defaultOptions.segmentNameCharset, segmentValueCharset: (arg2 != null ? arg2.segmentValueCharset : void 0) || defaultOptions.segmentValueCharset, optionalSegmentStartChar: (arg2 != null ? arg2.optionalSegmentStartChar : void 0) || defaultOptions.optionalSegmentStartChar, optionalSegmentEndChar: (arg2 != null ? arg2.optionalSegmentEndChar : void 0) || defaultOptions.optionalSegmentEndChar, wildcardChar: (arg2 != null ? arg2.wildcardChar : void 0) || defaultOptions.wildcardChar }; parser = newParser(options); parsed = parser.pattern(arg1); if (parsed == null) { throw new Error("couldn't parse pattern"); } if (parsed.rest !== '') { throw new Error("could only partially parse pattern"); } this.ast = parsed.value; this.regex = new RegExp(astNodeToRegexString(this.ast, options.segmentValueCharset)); this.names = astNodeToNames(this.ast); }; UrlPattern.prototype.match = function(url) { var groups, match; match = this.regex.exec(url); if (match == null) { return null; } groups = match.slice(1); if (this.names) { return keysAndValuesToObject(this.names, groups); } else { return groups; } }; UrlPattern.prototype.stringify = function(params) { if (params == null) { params = {}; } if (this.isRegex) { throw new Error("can't stringify patterns generated from a regex"); } if (params !== Object(params)) { throw new Error("argument must be an object or undefined"); } return stringify(this.ast, params, {}); }; UrlPattern.escapeForRegex = escapeForRegex; UrlPattern.concatMap = concatMap; UrlPattern.stringConcatMap = stringConcatMap; UrlPattern.regexGroupCount = regexGroupCount; UrlPattern.keysAndValuesToObject = keysAndValuesToObject; UrlPattern.P = P; UrlPattern.newParser = newParser; UrlPattern.defaultOptions = defaultOptions; UrlPattern.astNodeToRegexString = astNodeToRegexString; UrlPattern.astNodeToNames = astNodeToNames; UrlPattern.getParam = getParam; UrlPattern.astNodeContainsSegmentsForProvidedParams = astNodeContainsSegmentsForProvidedParams; UrlPattern.stringify = stringify; return UrlPattern; }); /***/ }, /* 26 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _actionTypes = __webpack_require__(23); exports.default = function () { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (action.type === _actionTypes.LOCATION_CHANGED) { // No-op the initial route action if (state && state.pathname === action.payload.pathname) { return state; } return _extends({}, action.payload, { previous: state && state.current }); } return state; }; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createMatcher = __webpack_require__(24); var _createMatcher2 = _interopRequireDefault(_createMatcher); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (_ref) { var _ref$pathname = _ref.pathname; var pathname = _ref$pathname === undefined ? '/' : _ref$pathname; var _ref$query = _ref.query; var query = _ref$query === undefined ? {} : _ref$query; var routes = _ref.routes; var history = _ref.history; return _extends({}, history.createLocation({ pathname: pathname, query: query }), (0, _createMatcher2.default)(routes)(pathname)); }; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.RouterProvider = undefined; 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; }; }(); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } 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 RouterProvider = exports.RouterProvider = function (_Component) { _inherits(RouterProvider, _Component); function RouterProvider(props) { _classCallCheck(this, RouterProvider); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(RouterProvider).call(this, props)); _this.router = { store: props.store }; return _this; } _createClass(RouterProvider, [{ key: 'getChildContext', value: function getChildContext() { return { router: this.router }; } }, { key: 'render', value: function render() { return this.props.children; } }]); return RouterProvider; }(_react.Component); RouterProvider.childContextTypes = { router: _react.PropTypes.object }; exports.default = function (_ref) { var store = _ref.store; return function (ComposedComponent) { return function (props) { return _react2.default.createElement( RouterProvider, { store: store }, _react2.default.createElement(ComposedComponent, props) ); }; }; }; /***/ }, /* 30 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_30__; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.PersistentQueryLink = exports.Link = undefined; 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; }; }(); 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; }; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _actionTypes = __webpack_require__(23); 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } 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; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var LEFT_MOUSE_BUTTON = 0; var normalizeHref = function normalizeHref(location) { return '' + (location.basename || '') + location.pathname; }; var normalizeLocation = function normalizeLocation(href) { if (typeof href === 'string') { var pathnameAndQuery = href.split('?'); var pathname = pathnameAndQuery[0]; // eslint-disable-line no-magic-numbers var query = pathnameAndQuery[1]; // eslint-disable-line no-magic-numbers return query ? { pathname: pathname, search: '?' + query } : { pathname: pathname }; } return href; }; var resolveQueryForLocation = function resolveQueryForLocation(_ref) { var linkLocation = _ref.linkLocation; var persistQuery = _ref.persistQuery; var currentLocation = _ref.currentLocation; var currentQuery = currentLocation && currentLocation.query; // Only use the query from state if it exists // and the href doesn't provide its own query if (persistQuery && currentQuery && !linkLocation.search && !linkLocation.query) { return { pathname: linkLocation.pathname, query: currentQuery }; } return linkLocation; }; var isNotLeftClick = function isNotLeftClick(e) { return e.button && e.button !== LEFT_MOUSE_BUTTON; }; var hasModifier = function hasModifier(e) { return Boolean(e.shiftKey || e.altKey || e.metaKey || e.ctrlKey); }; var _onClick = function _onClick(_ref2) { var e = _ref2.e; var target = _ref2.target; var location = _ref2.location; var replaceState = _ref2.replaceState; var router = _ref2.router; if (hasModifier(e) || isNotLeftClick(e) || target) { return; } e.preventDefault(); if (router) { router.store.dispatch({ type: replaceState ? _actionTypes.REPLACE : _actionTypes.PUSH, payload: location }); } }; var Link = function Link(props, context) { var href = props.href; var target = props.target; var persistQuery = props.persistQuery; var replaceState = props.replaceState; var children = props.children; var rest = _objectWithoutProperties(props, ['href', 'target', 'persistQuery', 'replaceState', 'children']); var router = context.router; var locationDescriptor = resolveQueryForLocation({ linkLocation: normalizeLocation(href), currentLocation: router.store.getState().router, persistQuery: persistQuery }); var location = router.store.history.createLocation(locationDescriptor); return _react2.default.createElement( 'a', _extends({ href: normalizeHref(location), onClick: function onClick(e) { return _onClick({ e: e, target: target, location: location, replaceState: replaceState, router: router }); } }, rest), children ); }; Link.contextTypes = { router: _react.PropTypes.object }; var PersistentQueryLink = function (_Component) { _inherits(PersistentQueryLink, _Component); function PersistentQueryLink() { _classCallCheck(this, PersistentQueryLink); return _possibleConstructorReturn(this, Object.getPrototypeOf(PersistentQueryLink).apply(this, arguments)); } _createClass(PersistentQueryLink, [{ key: 'render', value: function render() { var _props = this.props; var children = _props.children; var rest = _objectWithoutProperties(_props, ['children']); return _react2.default.createElement( Link, _extends({}, rest, { persistQuery: true }), children ); } }]); return PersistentQueryLink; }(_react.Component); PersistentQueryLink.propTypes = { children: _react.PropTypes.node }; PersistentQueryLink.contextTypes = { router: _react.PropTypes.object }; exports.Link = Link; exports.PersistentQueryLink = PersistentQueryLink; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Fragment = function Fragment(props, context) { var forRoute = props.forRoute; var forRoutes = props.forRoutes; var withConditions = props.withConditions; var children = props.children; var matchRoute = context.router.store.matchRoute; var _context$router$store = context.router.store.getState(); var location = _context$router$store.router; var matchResult = matchRoute(location.pathname); if (!matchResult) { return null; } if (forRoute && matchResult.route !== forRoute) { return null; } if (forRoutes) { var anyMatch = forRoutes.some(function (route) { return matchResult.route === route; }); if (!anyMatch) { return null; } } if (withConditions && !withConditions(location)) { return null; } return _react2.default.createElement( 'div', null, children ); }; Fragment.contextTypes = { router: _react.PropTypes.object }; exports.default = Fragment; /***/ } /******/ ]) }); ; //# sourceMappingURL=redux-little-router.js.map
src/app/components/Apply/ApplicationTemplate.js
kresimircoko/empathy
import React, { Component } from 'react'; class ApplicationTemplate extends Component { render () { return ( <form id="application-template"> <h3>Application For Benevolence</h3> <label htmlFor="charName">Character Name</label> <input name="charName" placeholder="Arthas" type="text"/> <label htmlFor="charArmory">Character Armory</label> <input name="charArmory" placeholder="armory.com/sekenah" type="text"/> <label htmlFor="charTime">How long has this character been your main?</label> <textarea name="charTime" placeholder="5 years in hell"/> <label htmlFor="uiScreenshot">Screenshot of Your UI</label> <input name="uiScreenshot" placeholder="imgur.com/ui" type="text"/> <label htmlFor="charLogs">Link to WarcraftLogs</label> <input name="charLogs" placeholder="warcraftlogs.com/me" type="text"/> </form> ) } } export default ApplicationTemplate;
src/components/flows/thirdPillar/ConfirmThirdPillarMandate/ThirdPillarTermsAgreement/ThirdPillarTermsAgreement.js
TulevaEE/onboarding-client
import React from 'react'; import Types from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { FormattedMessage, useIntl } from 'react-intl'; import { actions as thirdPillarActions } from '../../../../thirdPillar'; const RECOMMENDATION_AGE = 55; export const ThirdPillarTermsAgreement = ({ age, agreed, onAgreementChange }) => { const { formatMessage } = useIntl(); const showAgeDependentRecommendation = age && age >= RECOMMENDATION_AGE; return ( <div className="mt-5"> <div className="custom-control custom-checkbox"> <input checked={agreed} onChange={() => onAgreementChange(!agreed)} type="checkbox" className="custom-control-input" id="third-pillar-terms-checkbox" /> <label className="custom-control-label" htmlFor="third-pillar-terms-checkbox"> <FormattedMessage id="thirdPillarAgreement.termsConfirmation" values={{ a: (chunks) => ( <a href={formatMessage({ id: 'thirdPillarAgreement.termsConfirmation.link' })}> {chunks} </a> ), }} />{' '} {showAgeDependentRecommendation && ( <> <FormattedMessage id="thirdPillarAgreement.ageDependentRecommendationConfirmation" />{' '} </> )} <FormattedMessage id="thirdPillarAgreement.signingExplanation" /> {showAgeDependentRecommendation && ( <div className="mt-2"> <small className="text-muted"> <FormattedMessage id="thirdPillarAgreement.ageDependentRecommendation" /> </small> </div> )} </label> </div> </div> ); }; ThirdPillarTermsAgreement.propTypes = { age: Types.number, agreed: Types.bool, onAgreementChange: Types.func, }; ThirdPillarTermsAgreement.defaultProps = { age: null, agreed: false, onAgreementChange: () => {}, }; const mapStateToProps = (state) => ({ agreed: state.thirdPillar.agreedToTerms, age: state.login.user ? state.login.user.age : null, }); const mapDispatchToProps = (dispatch) => bindActionCreators( { onAgreementChange: thirdPillarActions.changeAgreementToTerms, }, dispatch, ); export default connect(mapStateToProps, mapDispatchToProps)(ThirdPillarTermsAgreement);
frontend/app/js/components/service/details/externalurl.js
serverboards/serverboards
import React from 'react' function ExternalUrl({url}){ return ( <iframe src={url} className="ui full height"></iframe> ) } export default ExternalUrl
files/react.slick/0.4.1/react-slick.js
markcarver/jsdelivr
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["Slider"] = factory(require("react")); else root["Slider"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__) { 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"; module.exports = __webpack_require__(40); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTransferer */ 'use strict'; var assign = __webpack_require__(68); var emptyFunction = __webpack_require__(67); var joinClasses = __webpack_require__(69); /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); } }; module.exports = ReactPropTransferer; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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; }; var React = __webpack_require__(2); var cloneWithProps = __webpack_require__(30); var classnames = __webpack_require__(14); var EventHandlersMixin = __webpack_require__(11); var HelpersMixin = __webpack_require__(10); var initialState = __webpack_require__(12); var defaultProps = __webpack_require__(13); var _assign = __webpack_require__(7); var Slider = React.createClass({ displayName: "Slider", mixins: [EventHandlersMixin, HelpersMixin], getInitialState: function getInitialState() { return initialState; }, getDefaultProps: function getDefaultProps() { return defaultProps; }, componentDidMount: function componentDidMount() { this.initialize(this.props); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.initialize(nextProps); }, renderDots: function renderDots() { var dotOptions; var dots = []; if (this.props.dots === true && this.state.slideCount > this.props.slidesToShow) { for (var i = 0; i <= this.getDotCount(); i += 1) { var className = classnames({ "slick-active": this.state.currentSlide === i * this.props.slidesToScroll }); dotOptions = { message: "index", index: i }; dots.push(React.createElement( "li", { key: i, className: className }, React.createElement( "button", { onClick: this.changeSlide.bind(this, dotOptions) }, i ) )); } return React.createElement( "ul", { className: this.props.dotsClass, style: { display: "block" } }, dots ); } else { return null; } }, renderSlides: function renderSlides() { var key; var slides = []; var preCloneSlides = []; var postCloneSlides = []; var count = React.Children.count(this.props.children); React.Children.forEach(this.props.children, (function (child, index) { var infiniteCount; slides.push(cloneWithProps(child, { key: index, "data-index": index, className: this.getSlideClasses(index), style: _assign({}, this.getSlideStyle(), child.props.style) })); if (this.props.infinite === true) { if (this.props.centerMode === true) { infiniteCount = this.props.slidesToShow + 1; } else { infiniteCount = this.props.slidesToShow; } if (index >= count - infiniteCount) { key = -(count - index); preCloneSlides.push(cloneWithProps(child, { key: key, "data-index": key, className: this.getSlideClasses(key), style: _assign({}, this.getSlideStyle(), child.props.style) })); } if (index < infiniteCount) { key = count + index; postCloneSlides.push(cloneWithProps(child, { key: key, "data-index": key, className: this.getSlideClasses(key), style: _assign({}, this.getSlideStyle(), child.props.style) })); } } }).bind(this)); return preCloneSlides.concat(slides, postCloneSlides); }, renderTrack: function renderTrack() { return React.createElement( "div", { ref: "track", className: "slick-track", style: this.state.trackStyle }, this.renderSlides() ); }, renderArrows: function renderArrows() { if (this.props.arrows === true) { var prevClasses = { "slick-prev": true }; var nextClasses = { "slick-next": true }; var prevHandler = this.changeSlide.bind(this, { message: "previous" }); var nextHandler = this.changeSlide.bind(this, { message: "next" }); if (this.props.infinite === false) { if (this.state.currentSlide === 0) { prevClasses["slick-disabled"] = true; prevHandler = null; } if (this.props.centerMode && !this.props.infinite) { if (this.state.currentSlide >= this.state.slideCount - 1) { nextClasses["slick-disabled"] = true; nextHandler = null; } } else { if (this.state.currentSlide >= this.state.slideCount - this.props.slidesToShow) { nextClasses["slick-disabled"] = true; nextHandler = null; } } } var prevArrowProps = { key: "0", ref: "previous", "data-role": "none", className: classnames(prevClasses), style: { display: "block" }, onClick: prevHandler }; if (this.props.prevArrow) { var prevArrow = React.createElement(this.props.prevArrow, prevArrowProps); } else { var prevArrow = React.createElement( "button", _extends({ type: "button" }, prevArrowProps), " Previous" ); } var nextArrowProps = { key: "1", ref: "next", "data-role": "none", className: classnames(nextClasses), style: { display: "block" }, onClick: nextHandler }; if (this.props.nextArrow) { var nextArrow = React.createElement(this.props.nextArrow, nextArrowProps); } else { var nextArrow = React.createElement( "button", _extends({ type: "button" }, nextArrowProps), " Next" ); } return [prevArrow, nextArrow]; } else { return null; } }, render: function render() { var className = classnames("slick-initialized", "slick-slider", this.props.className); return React.createElement( "div", { className: className }, React.createElement( "div", { ref: "list", className: "slick-list", style: this.getListStyle(), onMouseDown: this.swipeStart, onMouseMove: this.state.dragging ? this.swipeMove : null, onMouseUp: this.swipeEnd, onMouseLeave: this.state.dragging ? this.swipeEnd : null, onTouchStart: this.swipeStart, onTouchMove: this.state.dragging ? this.swipeMove : null, onTouchEnd: this.swipeEnd, onTouchCancel: this.state.dragging ? this.swipeEnd : null }, this.renderTrack() ), this.renderArrows(), this.renderDots() ); } }); module.exports = Slider; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var arrayFilter = __webpack_require__(16), baseCallback = __webpack_require__(21), baseFilter = __webpack_require__(15), isArray = __webpack_require__(17), keys = __webpack_require__(18); /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is bound to `thisArg` and * invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias select * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the new filtered array. * @example * * _.filter([4, 5, 6], function(n) { * return n % 2 == 0; * }); * // => [4, 6] * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); * // => ['barney'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.filter(users, 'active', false), 'user'); * // => ['fred'] * * // using the `_.property` callback shorthand * _.pluck(_.filter(users, 'active'), 'user'); * // => ['barney'] */ function filter(collection, predicate, thisArg) { var func = isArray(collection) ? arrayFilter : baseFilter; predicate = baseCallback(predicate, thisArg, 3); return func(collection, predicate); } module.exports = filter; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseCallback = __webpack_require__(20), baseCompareAscending = __webpack_require__(19), baseEach = __webpack_require__(23), baseSortBy = __webpack_require__(22), isIterateeCall = __webpack_require__(25), isArray = __webpack_require__(26), keys = __webpack_require__(24); /** * Used by `_.sortBy` to compare transformed elements of a collection and stable * sort them in ascending order. * * @private * @param {Object} object The object to compare to `other`. * @param {Object} other The object to compare to `object`. * @returns {number} Returns the sort order indicator for `object`. */ function compareAscending(object, other) { return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index); } /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.map` without support for callback shorthands * and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection through `iteratee`. This method performs * a stable sort, that is, it preserves the original sort order of equal elements. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new sorted array. * @example * * _.sortBy([1, 2, 3], function(n) { * return Math.sin(n); * }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(n) { * return this.sin(n); * }, Math); * // => [3, 1, 2] * * var users = [ * { 'user': 'fred' }, * { 'user': 'pebbles' }, * { 'user': 'barney' } * ]; * * // using the `_.property` callback shorthand * _.pluck(_.sortBy(users, 'user'), 'user'); * // => ['barney', 'fred', 'pebbles'] */ function sortBy(collection, iteratee, thisArg) { if (collection == null) { return []; } if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { iteratee = null; } var index = -1; iteratee = baseCallback(iteratee, thisArg, 3); var result = baseMap(collection, function(value, key, collection) { return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value }; }); return baseSortBy(result, compareAscending); } module.exports = sortBy; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseGet = __webpack_require__(33), toPath = __webpack_require__(34), isArray = __webpack_require__(31), map = __webpack_require__(32); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * 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 : object[key]; }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } /** * 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) { return isObject(value) ? value : Object(value); } /** * Gets the property value of `path` from all elements in `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Array|string} path The path of the property to pluck. * @returns {Array} Returns the property values. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * _.pluck(users, 'user'); * // => ['barney', 'fred'] * * var userIndex = _.indexBy(users, 'user'); * _.pluck(userIndex, 'age'); * // => [36, 40] (iteration order is not guaranteed) */ function pluck(collection, path) { return map(collection, property(path)); } /** * 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'); } /** * Creates a function which returns the property value at `path` on a * given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } module.exports = pluck; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.2.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseAssign = __webpack_require__(27), createAssigner = __webpack_require__(28), keys = __webpack_require__(29); /** * A specialized version of `_.assign` for customizing assigned values 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 assigned values. * @returns {Object} Returns `object`. */ function assignWith(object, source, customizer) { var index = -1, props = keys(source), length = props.length; while (++index < length) { var key = props[index], value = object[key], result = customizer(value, source[key], key, object, source); if ((result === result ? (result !== value) : (value === value)) || (value === undefined && !(key in object))) { object[key] = result; } } return object; } /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources overwrite property assignments of previous sources. * If `customizer` is provided it is invoked to produce the assigned values. * The `customizer` is bound to `thisArg` and invoked with five arguments: * (objectValue, sourceValue, key, object, source). * * **Note:** This method mutates `object` and is based on * [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign). * * @static * @memberOf _ * @alias extend * @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 * * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); * // => { 'user': 'fred', 'age': 40 } * * // using a customizer callback * var defaults = _.partialRight(_.assign, function(value, other) { * return _.isUndefined(value) ? other : value; * }); * * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var assign = createAssigner(function(object, source, customizer) { return customizer ? assignWith(object, source, customizer) : baseAssign(object, source); }); module.exports = assign; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var canUseDOM = __webpack_require__(35); var enquire = canUseDOM && __webpack_require__(37); var json2mq = __webpack_require__(9); var ResponsiveMixin = { media: function (query, handler) { query = json2mq(query); if (typeof handler === 'function') { handler = { match: handler }; } enquire.register(query, handler); // Queue the handlers to unregister them at unmount if (! this._responsiveMediaHandlers) { this._responsiveMediaHandlers = []; } this._responsiveMediaHandlers.push({query: query, handler: handler}); }, componentWillUnmount: function () { this._responsiveMediaHandlers.forEach(function(obj) { enquire.unregister(obj.query, obj.handler); }); } }; module.exports = ResponsiveMixin; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var camel2hyphen = __webpack_require__(39); var isDimension = function (feature) { var re = /[height|width]$/; return re.test(feature); }; var obj2mq = function (obj) { var mq = ''; var features = Object.keys(obj); features.forEach(function (feature, index) { var value = obj[feature]; feature = camel2hyphen(feature); // Add px to dimension features if (isDimension(feature) && typeof value === 'number') { value = value + 'px'; } if (value === true) { mq += feature; } else if (value === false) { mq += 'not ' + feature; } else { mq += '(' + feature + ': ' + value + ')'; } if (index < features.length-1) { mq += ' and ' } }); return mq; }; var json2mq = function (query) { var mq = ''; if (typeof query === 'string') { return query; } // Handling array of media queries if (query instanceof Array) { query.forEach(function (q, index) { mq += obj2mq(q); if (index < query.length-1) { mq += ', ' } }); return mq; } // Handling single media query return obj2mq(query); }; module.exports = json2mq; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var assign = __webpack_require__(38); var React = __webpack_require__(2); var classnames = __webpack_require__(14); var ReactTransitionEvents = __webpack_require__(36); var helpers = { initialize: function (props) { var slideCount = React.Children.count(props.children); var listWidth = this.refs.list.getDOMNode().getBoundingClientRect().width; var trackWidth = this.refs.track.getDOMNode().getBoundingClientRect().width; var slideWidth = this.getDOMNode().getBoundingClientRect().width/props.slidesToShow; this.setState({ slideCount: slideCount, slideWidth: slideWidth, listWidth: listWidth, trackWidth: trackWidth, currentSlide: props.initialSlide }, function () { // getCSS function needs previously set state var trackStyle = this.getCSS(this.getLeft(this.state.currentSlide)); this.setState({trackStyle: trackStyle}); this.autoPlay(); // once we're set up, trigger the initial autoplay. }); }, getDotCount: function () { var pagerQty; pagerQty = Math.ceil(this.state.slideCount /this.props.slidesToScroll); return pagerQty - 1; }, getLeft: function (slideIndex) { var slideOffset = 0; var targetLeft; var targetSlide; if (this.props.infinite === true) { if (this.state.slideCount > this.props.slidesToShow) { slideOffset = (this.state.slideWidth * this.props.slidesToShow) * -1; } if (this.state.slideCount % this.props.slidesToScroll !== 0) { if (slideIndex + this.props.slidesToScroll > this.state.slideCount && this.state.slideCount > this.props.slidesToShow) { if(slideIndex > this.state.slideCount) { slideOffset = ((this.props.slidesToShow - (slideIndex - this.state.slideCount)) * this.state.slideWidth) * -1; } else { slideOffset = ((this.state.slideCount % this.props.slidesToScroll) * this.state.slideWidth) * -1; } } } } else { } if (this.props.centerMode === true && this.props.infinite === true) { slideOffset += this.state.slideWidth * Math.floor(this.props.slidesToShow / 2) - this.state.slideWidth; } else if (this.props.centerMode === true) { slideOffset = this.state.slideWidth * Math.floor(this.props.slidesToShow / 2); } targetLeft = ((slideIndex * this.state.slideWidth) * -1) + slideOffset; if (this.props.variableWidth === true) { var targetSlideIndex; if(this.state.slideCount <= this.props.slidesToShow || this.props.infinite === false) { targetSlide = this.refs.track.getDOMNode().childNodes[slideIndex]; } else { targetSlideIndex = (slideIndex + this.props.slidesToShow); targetSlide = this.refs.track.getDOMNode().childNodes[targetSlideIndex]; } targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0; if (this.props.centerMode === true) { if(this.props.infinite === false) { targetSlide = this.refs.track.getDOMNode().childNodes[slideIndex]; } else { targetSlide = this.refs.track.getDOMNode().childNodes[(slideIndex + this.props.slidesToShow + 1)]; } targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0; targetLeft += (this.state.listWidth - targetSlide.offsetWidth) / 2; } } return targetLeft; }, getAnimateCSS: function (targetLeft) { var style = this.getCSS(targetLeft); style.WebkitTransition = '-webkit-transform ' + this.props.speed + 'ms ' + this.props.cssEase; style.transition = 'transform ' + this.props.speed + 'ms ' + this.props.cssEase; return style; }, getCSS: function (targetLeft) { // implemented this instead of setCSS var trackWidth; if (this.props.variableWidth) { trackWidth = (this.state.slideCount + 2*this.props.slidesToShow)*this.state.slideWidth; } else if (this.props.centerMode) { trackWidth = (this.state.slideCount + 2*(this.props.slidesToShow + 1)) *this.state.slideWidth; } else { trackWidth = (this.state.slideCount + 2*this.props.slidesToShow )*this.state.slideWidth; } var style = { opacity: 1, width: trackWidth, WebkitTransform: 'translate3d(' + targetLeft + 'px, 0px, 0px)', transform: 'translate3d(' + targetLeft + 'px, 0px, 0px)', transition: '', WebkitTransition: '' }; return style; }, getSlideStyle: function () { return { width: this.state.slideWidth }; }, getSlideClasses: function (index) { var slickActive, slickCenter, slickCloned; var centerOffset, indexOffset; var allSlides; var centerIndex; var realRange = false; slickCloned = (index < 0) || (index >= this.state.slideCount); if (this.props.centerMode) { if (this.refs.track) { allSlides = this.refs.track.getDOMNode().childNodes.length; } centerOffset = Math.floor(this.props.slidesToShow / 2); indexOffset = this.state.currentSlide + this.props.slidesToShow; centerIndex = this.state.currentSlide + centerOffset; slickCenter = (centerIndex-1 === index); if (this.state.currentSlide >= centerOffset && this.state.currentSlide <= (this.props.slideCount - 1) - centerOffset) { realRange = true; } if (realRange && (index > this.state.currentSlide - centerOffset) && (index <= this.state.currentSlide + centerOffset + 1 )) { slickActive = true; } else { } } else { slickActive = (this.state.currentSlide === index); } return classnames({ 'slick-slide': true, 'slick-active': slickActive, 'slick-center': slickCenter, 'slick-cloned': slickCloned }); }, getListStyle: function () { var style = {}; if (this.props.adaptiveHeight) { var selector = '[data-index="' + this.state.currentSlide +'"]'; if (this.refs.list) { style.height = this.refs.list.getDOMNode().querySelector(selector).offsetHeight; } } return style; }, slideHandler: function (index, sync, dontAnimate) { // Functionality of animateSlide and postSlide is merged into this function // console.log('slideHandler', index); var targetSlide, currentSlide; var targetLeft, currentLeft; if (this.state.animating === true) { return; } // To prevent the slider from sticking in animating state, If we click on already active dot if (this.props.fade === true && this.state.currentSlide === index) { return; } if (this.state.slideCount <= this.props.slidesToShow) { return; } targetSlide = index; if (targetSlide < 0) { if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = this.state.slideCount - (this.state.slideCount % this.props.slidesToScroll); } else { currentSlide = this.state.slideCount + targetSlide; } } else if (targetSlide >= this.state.slideCount) { if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = 0; } else { currentSlide = targetSlide - this.state.slideCount; } } else { currentSlide = targetSlide; } targetLeft = this.getLeft(targetSlide, this.state); currentLeft = this.getLeft(currentSlide, this.state); if (this.props.infinite === false) { targetLeft = currentLeft; } if(this.props.afterChange!==null){ this.props.afterChange(currentSlide); } var callback = function() { this.setState({ animating: false, trackStyle: this.getCSS(currentLeft), swipeLeft: null }); }.bind(this) this.setState({ animating: true, currentSlide: currentSlide, currentLeft: currentLeft, trackStyle: this.getAnimateCSS(targetLeft) }, function () { ReactTransitionEvents.addEndEventListener(this.refs.track.getDOMNode(), callback); setTimeout(callback, this.props.speed); }); this.autoPlay(); }, swipeDirection: function (touchObject) { var xDist, yDist, r, swipeAngle; xDist = touchObject.startX - touchObject.curX; yDist = touchObject.startY - touchObject.curY; r = Math.atan2(yDist, xDist); swipeAngle = Math.round(r * 180 / Math.PI); if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } if ((swipeAngle <= 45) && (swipeAngle >= 0)) { return (this.props.rtl === false ? 'left' : 'right'); } if ((swipeAngle <= 360) && (swipeAngle >= 315)) { return (this.props.rtl === false ? 'left' : 'right'); } if ((swipeAngle >= 135) && (swipeAngle <= 225)) { return (this.props.rtl === false ? 'right' : 'left'); } return 'vertical'; }, autoPlay: function () { var play = function () { if (this.isMounted()) this.slideHandler(this.state.currentSlide + this.props.slidesToScroll); }.bind(this); if (this.props.autoplay) { window.clearTimeout(this.state.autoPlayTimer); this.setState({ autoPlayTimer: window.setTimeout(play, this.props.autoplaySpeed) }); } }, }; module.exports = helpers; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var EventHandlers = { // Event handler for previous and next changeSlide: function (options, e) { // console.log('changeSlide'); var indexOffset, slideOffset, unevenOffset; unevenOffset = (this.state.slideCount % this.props.slidesToScroll !== 0); indexOffset = unevenOffset ? 0 : (this.state.slideCount - this.state.currentSlide) % this.props.slidesToScroll; if (options.message === 'previous') { slideOffset = (indexOffset === 0) ? this.props.slidesToScroll : this.props.slidesToShow - indexOffset; if (this.state.slideCount > this.props.slidesToShow) { this.slideHandler(this.state.currentSlide - slideOffset, false); } } else if (options.message === 'next') { slideOffset = (indexOffset === 0) ? this.props.slidesToScroll : indexOffset; if (this.state.slideCount > this.props.slidesToShow) { this.slideHandler(this.state.currentSlide + slideOffset, false); } } else if (options.message === 'index') { // Click on dots var targetSlide = options.index*this.props.slidesToScroll; if (targetSlide !== this.state.currentSlide) { this.slideHandler(targetSlide); } } }, // Accessiblity handler for previous and next keyHandler: function (e) { }, // Focus on selecting a slide (click handler on track) selectHandler: function (e) { }, swipeStart: function (e) { var touches, posX, posY; if ((this.props.swipe === false) || ('ontouchend' in document && this.props.swipe === false)) { return; } else if (this.props.draggable === false && e.type.indexOf('mouse') !== -1) { return; } posX = (e.touches !== undefined) ? e.touches[0].pageX : e.clientX; posY = (e.touches !== undefined) ? e.touches[0].pageY : e.clientY; this.setState({ dragging: true, touchObject: { startX: posX, startY: posY, curX: posX, curY: posY } }); e.preventDefault(); }, swipeMove: function (e) { if (!this.state.dragging) { return; } if (this.state.animating) { return; } var swipeLeft; var curLeft, positionOffset; var touchObject = this.state.touchObject; curLeft = this.getLeft(this.state.currentSlide); touchObject.curX = (e.touches )? e.touches[0].pageX : e.clientX; touchObject.curY = (e.touches )? e.touches[0].pageY : e.clientY; touchObject.swipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curX - touchObject.startX, 2))); positionOffset = (this.props.rtl === false ? 1 : -1) * (touchObject.curX > touchObject.startX ? 1 : -1); swipeLeft = curLeft + touchObject.swipeLength * positionOffset; this.setState({ touchObject: touchObject, swipeLeft: swipeLeft, trackStyle: this.getCSS(swipeLeft), }); e.preventDefault(); }, swipeEnd: function (e) { e.preventDefault(); if (!this.state.dragging) { return; } var touchObject = this.state.touchObject; var minSwipe = this.state.listWidth/this.props.touchThreshold; var swipeDirection = this.swipeDirection(touchObject); this.setState({ dragging: false, swipeLeft: null, touchObject: {} }); // Fix for #13 if (!touchObject.swipeLength) { return; } if (touchObject.swipeLength > minSwipe) { if (swipeDirection === 'left') { this.slideHandler(this.state.currentSlide + this.props.slidesToScroll); } else if (swipeDirection === 'right') { this.slideHandler(this.state.currentSlide - this.props.slidesToScroll); } else { this.slideHandler(this.state.currentSlide, null, true); } } else { this.slideHandler(this.state.currentSlide, null, true); } }, }; module.exports = EventHandlers; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var initialState = { animating: false, dragging: false, autoPlayTimer: null, currentDirection: 0, currentLeft: null, currentSlide: 0, direction: 1, // listWidth: null, // listHeight: null, // loadIndex: 0, slideCount: null, slideWidth: null, // sliding: false, // slideOffset: 0, swipeLeft: null, touchObject: { startX: 0, startY: 0, curX: 0, curY: 0 }, // added for react initialized: false, trackStyle: {}, trackWidth: 0, // Removed // transformsEnabled: false, // $nextArrow: null, // $prevArrow: null, // $dots: null, // $list: null, // $slideTrack: null, // $slides: null, }; module.exports = initialState; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var defaultProps = { className: '', // accessibility: true, adaptiveHeight: false, arrows: true, autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, // lazyLoad: 'ondemand', responsive: null, rtl: false, slide: 'div', slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, // useCSS: true, variableWidth: false, vertical: false, // waitForAnimate: true, afterChange: null, nextArrow: null, prevArrow: null }; module.exports = defaultProps; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseEach = __webpack_require__(45); /** * The base implementation of `_.filter` without support for callback * shorthands or `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } module.exports = baseFilter; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * A specialized version of `_.filter` for arrays without support for callback * shorthands or `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[++resIndex] = value; } } return result; } module.exports = arrayFilter; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var arrayTag = '[object Array]', funcTag = '[object Function]'; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * 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'; } /** 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 resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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; }; /** * 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 (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = isArray; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var getNative = __webpack_require__(48), isArguments = __webpack_require__(46), isArray = __webpack_require__(17); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * 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' ? value : parseFloat(value); length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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)); 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; } /** * 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'); } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#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 ? null : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; /** * 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)) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keys; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * The base implementation of `compareAscending` which compares values and * sorts them in ascending order without guaranteeing a stable sort. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function baseCompareAscending(value, other) { if (value !== other) { var valIsNull = value === null, valIsUndef = value === undefined, valIsReflexive = value === value; var othIsNull = other === null, othIsUndef = other === undefined, othIsReflexive = other === other; if ((value > other && !othIsNull) || !valIsReflexive || (valIsNull && !othIsUndef && othIsReflexive) || (valIsUndef && othIsReflexive)) { return 1; } if ((value < other && !valIsNull) || !othIsReflexive || (othIsNull && !valIsUndef && valIsReflexive) || (othIsUndef && valIsReflexive)) { return -1; } } return 0; } module.exports = baseCompareAscending; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.3.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseIsEqual = __webpack_require__(51), bindCallback = __webpack_require__(47), isArray = __webpack_require__(26), pairs = __webpack_require__(49); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * The base implementation of `_.callback` which supports specifying the * number of arguments to provide to `func`. * * @private * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } if (func == null) { return identity; } if (type == 'object') { return baseMatches(func); } return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg); } /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ function baseGet(object, path, pathKey) { if (object == null) { return; } if (pathKey !== undefined && pathKey in toObject(object)) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = object[path[index++]]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `_.isMatch` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to inspect. * @param {Array} matchData The propery names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparing objects. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = toObject(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var result = customizer ? customizer(objValue, srcValue, key) : undefined; if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { return false; } } } return true; } /** * The base implementation of `_.matches` which does not clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { var key = matchData[0][0], value = matchData[0][1]; return function(object) { if (object == null) { return false; } return object[key] === value && (value !== undefined || (key in toObject(object))); }; } return function(object) { return baseIsMatch(object, matchData); }; } /** * The base implementation of `_.matchesProperty` which does not which does * not clone `value`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to compare. * @returns {Function} Returns the new function. */ function baseMatchesProperty(path, srcValue) { var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(srcValue), pathKey = (path + ''); path = toPath(path); return function(object) { if (object == null) { return false; } var key = pathKey; object = toObject(object); if ((isArr || !isCommon) && !(key in object)) { object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } key = last(path); object = toObject(object); } return object[key] === srcValue ? (srcValue !== undefined || (key in object)) : baseIsEqual(srcValue, object[key], undefined, true); }; } /** * 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 : object[key]; }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * Gets the propery names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = pairs(object), length = result.length; while (length--) { result[length][2] = isStrictComparable(result[length][1]); } return result; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * 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) { return isObject(value) ? value : Object(value); } /** * Converts `value` to property path array if it's not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * 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'); } /** * 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; } /** * Creates a function which returns the property value at `path` on a * given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } module.exports = baseCallback; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.3.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseIsEqual = __webpack_require__(53), bindCallback = __webpack_require__(52), isArray = __webpack_require__(17), pairs = __webpack_require__(50); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * The base implementation of `_.callback` which supports specifying the * number of arguments to provide to `func`. * * @private * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } if (func == null) { return identity; } if (type == 'object') { return baseMatches(func); } return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg); } /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ function baseGet(object, path, pathKey) { if (object == null) { return; } if (pathKey !== undefined && pathKey in toObject(object)) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = object[path[index++]]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `_.isMatch` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to inspect. * @param {Array} matchData The propery names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparing objects. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = toObject(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var result = customizer ? customizer(objValue, srcValue, key) : undefined; if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { return false; } } } return true; } /** * The base implementation of `_.matches` which does not clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { var key = matchData[0][0], value = matchData[0][1]; return function(object) { if (object == null) { return false; } return object[key] === value && (value !== undefined || (key in toObject(object))); }; } return function(object) { return baseIsMatch(object, matchData); }; } /** * The base implementation of `_.matchesProperty` which does not which does * not clone `value`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to compare. * @returns {Function} Returns the new function. */ function baseMatchesProperty(path, srcValue) { var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(srcValue), pathKey = (path + ''); path = toPath(path); return function(object) { if (object == null) { return false; } var key = pathKey; object = toObject(object); if ((isArr || !isCommon) && !(key in object)) { object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } key = last(path); object = toObject(object); } return object[key] === srcValue ? (srcValue !== undefined || (key in object)) : baseIsEqual(srcValue, object[key], undefined, true); }; } /** * 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 : object[key]; }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * Gets the propery names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = pairs(object), length = result.length; while (length--) { result[length][2] = isStrictComparable(result[length][1]); } return result; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * 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) { return isObject(value) ? value : Object(value); } /** * Converts `value` to property path array if it's not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * 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'); } /** * 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; } /** * Creates a function which returns the property value at `path` on a * given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } module.exports = baseCallback; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * The base implementation of `_.sortBy` and `_.sortByAll` which uses `comparer` * to define the sort order of `array` and replaces criteria objects with their * corresponding values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } module.exports = baseSortBy; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = __webpack_require__(24); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.forEach` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * 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(); /** * The base implementation of `_.forOwn` 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 baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } /** * 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 : object[key]; }; } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * 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; }; } /** * 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'); /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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) { return isObject(value) ? value : Object(value); } /** * 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 = baseEach; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var getNative = __webpack_require__(54), isArguments = __webpack_require__(55), isArray = __webpack_require__(26); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * 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' ? value : parseFloat(value); length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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)); 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; } /** * 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'); } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#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 ? null : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; /** * 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)) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keys; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.8 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * 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' ? value : parseFloat(value); length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * 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; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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 = isIterateeCall; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var arrayTag = '[object Array]', funcTag = '[object Function]'; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * 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'; } /** 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 resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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; }; /** * 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 (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = isArray; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.2.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseCopy = __webpack_require__(66), keys = __webpack_require__(29); /** * The base implementation of `_.assign` without support for argument juggling, * multiple sources, and `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return source == null ? object : baseCopy(source, keys(source), object); } module.exports = baseAssign; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var bindCallback = __webpack_require__(56), isIterateeCall = __webpack_require__(59), restParam = __webpack_require__(57); /** * Creates a function that assigns properties of source object(s) to a given * destination object. * * **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`. * * @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; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var getNative = __webpack_require__(58), isArguments = __webpack_require__(60), isArray = __webpack_require__(61); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * 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' ? value : parseFloat(value); length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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)); 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; } /** * 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'); } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#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 ? null : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; /** * 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)) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keys; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, 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. * * @typechecks static-only * @providesModule cloneWithProps */ 'use strict'; var ReactElement = __webpack_require__(42); var ReactPropTransferer = __webpack_require__(1); var keyOf = __webpack_require__(41); var warning = __webpack_require__(43); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {ReactElement} child child element you'd like to clone * @param {object} props props you'd like to modify. className and style will be * merged automatically. * @return {ReactElement} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== (undefined)) { ("production" !== (undefined) ? warning( !child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var arrayTag = '[object Array]', funcTag = '[object Function]'; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * 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'; } /** 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 resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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; }; /** * 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 (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = isArray; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var arrayMap = __webpack_require__(62), baseCallback = __webpack_require__(63), baseEach = __webpack_require__(64), isArray = __webpack_require__(31), keys = __webpack_require__(65); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.map` without support for callback shorthands * and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * Creates an array of values by running each element in `collection` through * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, * `sum`, `uniq`, and `words` * * @static * @memberOf _ * @alias collect * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new mapped array. * @example * * function timesThree(n) { * return n * 3; * } * * _.map([1, 2], timesThree); * // => [3, 6] * * _.map({ 'a': 1, 'b': 2 }, timesThree); * // => [3, 6] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // using the `_.property` callback shorthand * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee, thisArg) { var func = isArray(collection) ? arrayMap : baseMap; iteratee = baseCallback(iteratee, thisArg, 3); return func(collection, iteratee); } module.exports = map; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.7.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ function baseGet(object, path, pathKey) { if (object == null) { return; } if (pathKey !== undefined && pathKey in toObject(object)) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = object[path[index++]]; } return (index && index == length) ? object : undefined; } /** * 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) { return isObject(value) ? value : Object(value); } /** * 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 = baseGet; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.8.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var isArray = __webpack_require__(31); /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `value` to a string if it is not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * Converts `value` to property path array if it is not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } module.exports = toPath; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); module.exports = canUseDOM; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ 'use strict'; var ExecutionEnvironment = __webpack_require__(44); /** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ var EVENT_NAME_MAP = { transitionend: { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'mozTransitionEnd', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd' }, animationend: { 'animation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'mozAnimationEnd', 'OAnimation': 'oAnimationEnd', 'msAnimation': 'MSAnimationEnd' } }; var endEvents = []; function detectEvents() { var testEl = document.createElement('div'); var style = testEl.style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition; } for (var baseEventName in EVENT_NAME_MAP) { var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]); break; } } } } if (ExecutionEnvironment.canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function(endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function(endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; module.exports = ReactTransitionEvents; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! * enquire.js v2.1.1 - Awesome Media Queries in JavaScript * Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/enquire.js * License: MIT (http://www.opensource.org/licenses/mit-license.php) */ ;(function (name, context, factory) { var matchMedia = window.matchMedia; if (typeof module !== 'undefined' && module.exports) { module.exports = factory(matchMedia); } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return (context[name] = factory(matchMedia)); }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { context[name] = factory(matchMedia); } }('enquire', this, function (matchMedia) { 'use strict'; /*jshint unused:false */ /** * Helper function for iterating over a collection * * @param collection * @param fn */ function each(collection, fn) { var i = 0, length = collection.length, cont; for(i; i < length; i++) { cont = fn(collection[i], i); if(cont === false) { break; //allow early exit } } } /** * Helper function for determining whether target object is an array * * @param target the object under test * @return {Boolean} true if array, false otherwise */ function isArray(target) { return Object.prototype.toString.apply(target) === '[object Array]'; } /** * Helper function for determining whether target object is a function * * @param target the object under test * @return {Boolean} true if function, false otherwise */ function isFunction(target) { return typeof target === 'function'; } /** * Delegate to handle a media query being matched and unmatched. * * @param {object} options * @param {function} options.match callback for when the media query is matched * @param {function} [options.unmatch] callback for when the media query is unmatched * @param {function} [options.setup] one-time callback triggered the first time a query is matched * @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched? * @constructor */ function QueryHandler(options) { this.options = options; !options.deferSetup && this.setup(); } QueryHandler.prototype = { /** * coordinates setup of the handler * * @function */ setup : function() { if(this.options.setup) { this.options.setup(); } this.initialised = true; }, /** * coordinates setup and triggering of the handler * * @function */ on : function() { !this.initialised && this.setup(); this.options.match && this.options.match(); }, /** * coordinates the unmatch event for the handler * * @function */ off : function() { this.options.unmatch && this.options.unmatch(); }, /** * called when a handler is to be destroyed. * delegates to the destroy or unmatch callbacks, depending on availability. * * @function */ destroy : function() { this.options.destroy ? this.options.destroy() : this.off(); }, /** * determines equality by reference. * if object is supplied compare options, if function, compare match callback * * @function * @param {object || function} [target] the target for comparison */ equals : function(target) { return this.options === target || this.options.match === target; } }; /** * Represents a single media query, manages it's state and registered handlers for this query * * @constructor * @param {string} query the media query string * @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design */ function MediaQuery(query, isUnconditional) { this.query = query; this.isUnconditional = isUnconditional; this.handlers = []; this.mql = matchMedia(query); var self = this; this.listener = function(mql) { self.mql = mql; self.assess(); }; this.mql.addListener(this.listener); } MediaQuery.prototype = { /** * add a handler for this query, triggering if already active * * @param {object} handler * @param {function} handler.match callback for when query is activated * @param {function} [handler.unmatch] callback for when query is deactivated * @param {function} [handler.setup] callback for immediate execution when a query handler is registered * @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched? */ addHandler : function(handler) { var qh = new QueryHandler(handler); this.handlers.push(qh); this.matches() && qh.on(); }, /** * removes the given handler from the collection, and calls it's destroy methods * * @param {object || function} handler the handler to remove */ removeHandler : function(handler) { var handlers = this.handlers; each(handlers, function(h, i) { if(h.equals(handler)) { h.destroy(); return !handlers.splice(i,1); //remove from array and exit each early } }); }, /** * Determine whether the media query should be considered a match * * @return {Boolean} true if media query can be considered a match, false otherwise */ matches : function() { return this.mql.matches || this.isUnconditional; }, /** * Clears all handlers and unbinds events */ clear : function() { each(this.handlers, function(handler) { handler.destroy(); }); this.mql.removeListener(this.listener); this.handlers.length = 0; //clear array }, /* * Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match */ assess : function() { var action = this.matches() ? 'on' : 'off'; each(this.handlers, function(handler) { handler[action](); }); } }; /** * Allows for registration of query handlers. * Manages the query handler's state and is responsible for wiring up browser events * * @constructor */ function MediaQueryDispatch () { if(!matchMedia) { throw new Error('matchMedia not present, legacy browsers require a polyfill'); } this.queries = {}; this.browserIsIncapable = !matchMedia('only all').matches; } MediaQueryDispatch.prototype = { /** * Registers a handler for the given media query * * @param {string} q the media query * @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers * @param {function} options.match fired when query matched * @param {function} [options.unmatch] fired when a query is no longer matched * @param {function} [options.setup] fired when handler first triggered * @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched * @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers */ register : function(q, options, shouldDegrade) { var queries = this.queries, isUnconditional = shouldDegrade && this.browserIsIncapable; if(!queries[q]) { queries[q] = new MediaQuery(q, isUnconditional); } //normalise to object in an array if(isFunction(options)) { options = { match : options }; } if(!isArray(options)) { options = [options]; } each(options, function(handler) { queries[q].addHandler(handler); }); return this; }, /** * unregisters a query and all it's handlers, or a specific handler for a query * * @param {string} q the media query to target * @param {object || function} [handler] specific handler to unregister */ unregister : function(q, handler) { var query = this.queries[q]; if(query) { if(handler) { query.removeHandler(handler); } else { query.clear(); delete this.queries[q]; } } return this; } }; return new MediaQueryDispatch(); })); /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var camel2hyphen = function (str) { return str .replace(/[A-Z]/g, function (match) { return '-' + match.toLowerCase(); }) .toLowerCase(); }; module.exports = camel2hyphen; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var React = __webpack_require__(2); var InnerSlider = __webpack_require__(3); var _sortBy = __webpack_require__(5); var _pluck = __webpack_require__(6); var _filter = __webpack_require__(4); var _assign = __webpack_require__(7); var json2mq = __webpack_require__(9); var ResponsiveMixin = __webpack_require__(8); var Slider = React.createClass({ displayName: "Slider", mixins: [ResponsiveMixin], getInitialState: function getInitialState() { return { breakpoint: null }; }, componentDidMount: function componentDidMount() { var breakpoints = _sortBy(_pluck(this.props.responsive, "breakpoint")); breakpoints.forEach((function (breakpoint, index) { var query; if (index === 0) { query = json2mq({ minWidth: 0, maxWidth: breakpoint }); } else { query = json2mq({ minWidth: breakpoints[index - 1], maxWidth: breakpoint }); } this.media(query, (function () { this.setState({ breakpoint: breakpoint }); }).bind(this)); }).bind(this)); // Register media query for full screen. Need to support resize from small to large var query = json2mq({ minWidth: breakpoints.slice(-1)[0] }); this.media(query, (function () { this.setState({ breakpoint: null }); }).bind(this)); }, render: function render() { var settings; var newProps; if (this.state.breakpoint) { newProps = _filter(this.props.responsive, { breakpoint: this.state.breakpoint }); settings = _assign({}, this.props, newProps[0].settings); } else { settings = this.props; } return React.createElement(InnerSlider, settings); } }); module.exports = Slider; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var ReactContext = __webpack_require__(70); var ReactCurrentOwner = __webpack_require__(71); var assign = __webpack_require__(68); var warning = __webpack_require__(43); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== (undefined) ? warning( false, 'Don\'t set the %s property of the React element. Instead, ' + 'specify the correct value when initially creating the element.', key ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== (undefined)) { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = {props: props, originalProps: assign({}, props)}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== (undefined)) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== (undefined)) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function(element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return new ReactElement( element.type, key, ref, owner, element._context, props ); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ "use strict"; var emptyFunction = __webpack_require__(67); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== (undefined)) { warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || /^[s\W]*$/.test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}); console.warn(message); try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ "use strict"; var canUseDOM = !!( (typeof window !== 'undefined' && window.document && window.document.createElement) ); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = __webpack_require__(18); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.forEach` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * 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(); /** * The base implementation of `_.forOwn` 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 baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } /** * 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 : object[key]; }; } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * 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; }; } /** * 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'); /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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) { return isObject(value) ? value : Object(value); } /** * 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 = baseEach; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * 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'; } /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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) && objToString.call(value) == argsTag; } module.exports = isArguments; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * 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); }; } /** * 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 = bindCallback; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.9.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * 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'; } /** 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 resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * 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; } /** * 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 (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = getNative; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = __webpack_require__(24); /** * 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) { return isObject(value) ? value : Object(value); } /** * 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'); } /** * Creates a two dimensional array of the key-value pairs for `object`, * e.g. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) */ function pairs(object) { object = toObject(object); var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } module.exports = pairs; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = __webpack_require__(18); /** * 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) { return isObject(value) ? value : Object(value); } /** * 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'); } /** * Creates a two dimensional array of the key-value pairs for `object`, * e.g. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) */ function pairs(object) { object = toObject(object); var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } module.exports = pairs; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.6 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var isArray = __webpack_require__(26), isTypedArray = __webpack_require__(72), keys = __webpack_require__(24); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** 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`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * A specialized version of `_.some` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.isEqual` without support for `this` binding * `customizer` functions. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObject(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing objects. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `value` objects. * @param {Array} [stackB=[]] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag == argsTag) { objTag = objectTag; } else if (objTag != objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag == argsTag) { othTag = objectTag; } else if (othTag != objectTag) { othIsArr = isTypedArray(other); } } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == object) { return stackB[length] == other; } } // Add `object` and `other` to the stack of traversed objects. stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing arrays. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isLoose && othLength > arrLength)) { return false; } // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index], result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; if (result !== undefined) { if (result) { continue; } return false; } // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { if (!arraySome(other, function(othValue) { return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); })) { return false; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { return false; } } return true; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} value The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: // 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 +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other : object == +other; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings primitives and string // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. return object == (other + ''); } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isLoose) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { return false; } } var skipCtor = isLoose; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key], result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; // Recursively compare objects (susceptible to call stack limits). if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { return false; } skipCtor || (skipCtor = key == 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } /** * 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 = baseIsEqual; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * 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); }; } /** * 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 = bindCallback; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.6 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var isArray = __webpack_require__(17), isTypedArray = __webpack_require__(73), keys = __webpack_require__(18); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** 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`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * A specialized version of `_.some` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.isEqual` without support for `this` binding * `customizer` functions. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObject(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing objects. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `value` objects. * @param {Array} [stackB=[]] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag == argsTag) { objTag = objectTag; } else if (objTag != objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag == argsTag) { othTag = objectTag; } else if (othTag != objectTag) { othIsArr = isTypedArray(other); } } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == object) { return stackB[length] == other; } } // Add `object` and `other` to the stack of traversed objects. stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing arrays. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isLoose && othLength > arrLength)) { return false; } // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index], result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; if (result !== undefined) { if (result) { continue; } return false; } // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { if (!arraySome(other, function(othValue) { return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); })) { return false; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { return false; } } return true; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} value The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: // 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 +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other : object == +other; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings primitives and string // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. return object == (other + ''); } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isLoose) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { return false; } } var skipCtor = isLoose; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key], result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; // Recursively compare objects (susceptible to call stack limits). if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { return false; } skipCtor || (skipCtor = key == 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } /** * 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 = baseIsEqual; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.9.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * 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'; } /** 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 resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * 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; } /** * 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 (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = getNative; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * 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'; } /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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) && objToString.call(value) == argsTag; } module.exports = isArguments; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * 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); }; } /** * 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 = bindCallback; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.6.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** 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/en-US/docs/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; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.9.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * 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'; } /** 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 resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * 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; } /** * 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 (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = getNative; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.8 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * 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' ? value : parseFloat(value); length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * 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; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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 = isIterateeCall; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * 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'; } /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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) && objToString.call(value) == argsTag; } module.exports = isArguments; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var arrayTag = '[object Array]', funcTag = '[object Function]'; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * 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'; } /** 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 resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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; }; /** * 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 (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = isArray; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * A specialized version of `_.map` for arrays without support for callback * shorthands or `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.3.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseIsEqual = __webpack_require__(74), bindCallback = __webpack_require__(75), isArray = __webpack_require__(31), pairs = __webpack_require__(76); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * The base implementation of `_.callback` which supports specifying the * number of arguments to provide to `func`. * * @private * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } if (func == null) { return identity; } if (type == 'object') { return baseMatches(func); } return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg); } /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ function baseGet(object, path, pathKey) { if (object == null) { return; } if (pathKey !== undefined && pathKey in toObject(object)) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = object[path[index++]]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `_.isMatch` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to inspect. * @param {Array} matchData The propery names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparing objects. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = toObject(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var result = customizer ? customizer(objValue, srcValue, key) : undefined; if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { return false; } } } return true; } /** * The base implementation of `_.matches` which does not clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { var key = matchData[0][0], value = matchData[0][1]; return function(object) { if (object == null) { return false; } return object[key] === value && (value !== undefined || (key in toObject(object))); }; } return function(object) { return baseIsMatch(object, matchData); }; } /** * The base implementation of `_.matchesProperty` which does not which does * not clone `value`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to compare. * @returns {Function} Returns the new function. */ function baseMatchesProperty(path, srcValue) { var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(srcValue), pathKey = (path + ''); path = toPath(path); return function(object) { if (object == null) { return false; } var key = pathKey; object = toObject(object); if ((isArr || !isCommon) && !(key in object)) { object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } key = last(path); object = toObject(object); } return object[key] === srcValue ? (srcValue !== undefined || (key in object)) : baseIsEqual(srcValue, object[key], undefined, true); }; } /** * 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 : object[key]; }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * Gets the propery names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = pairs(object), length = result.length; while (length--) { result[length][2] = isStrictComparable(result[length][1]); } return result; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * 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) { return isObject(value) ? value : Object(value); } /** * Converts `value` to property path array if it's not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * 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'); } /** * 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; } /** * Creates a function which returns the property value at `path` on a * given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } module.exports = baseCallback; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = __webpack_require__(65); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.forEach` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * 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(); /** * The base implementation of `_.forOwn` 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 baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } /** * 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 : object[key]; }; } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * 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; }; } /** * 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'); /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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) { return isObject(value) ? value : Object(value); } /** * 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 = baseEach; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.1.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var getNative = __webpack_require__(79), isArguments = __webpack_require__(78), isArray = __webpack_require__(31); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * 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' ? value : parseFloat(value); length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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)); 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; } /** * 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'); } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#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 ? null : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; /** * 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)) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keys; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * 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; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function() { return this; }; emptyFunction.thatReturnsArgument = function(arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ 'use strict'; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactContext */ 'use strict'; var assign = __webpack_require__(68); var emptyObject = __webpack_require__(77); var warning = __webpack_require__(43); var didWarn = false; /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: emptyObject, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { if ("production" !== (undefined)) { ("production" !== (undefined) ? warning( didWarn, 'withContext is deprecated and will be removed in a future version. ' + 'Use a wrapper component with getChildContext instead.' ) : null); didWarn = true; } var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `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; /** * 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'; } /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#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`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `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; /** * 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'; } /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#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`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.6 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var isArray = __webpack_require__(31), isTypedArray = __webpack_require__(80), keys = __webpack_require__(65); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** 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`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * A specialized version of `_.some` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.isEqual` without support for `this` binding * `customizer` functions. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObject(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing objects. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `value` objects. * @param {Array} [stackB=[]] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag == argsTag) { objTag = objectTag; } else if (objTag != objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag == argsTag) { othTag = objectTag; } else if (othTag != objectTag) { othIsArr = isTypedArray(other); } } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == object) { return stackB[length] == other; } } // Add `object` and `other` to the stack of traversed objects. stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing arrays. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isLoose && othLength > arrLength)) { return false; } // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index], result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; if (result !== undefined) { if (result) { continue; } return false; } // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { if (!arraySome(other, function(othValue) { return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); })) { return false; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { return false; } } return true; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} value The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: // 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 +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other : object == +other; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings primitives and string // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. return object == (other + ''); } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isLoose) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { return false; } } var skipCtor = isLoose; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key], result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; // Recursively compare objects (susceptible to call stack limits). if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { return false; } skipCtor || (skipCtor = key == 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } /** * 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 = baseIsEqual; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * 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); }; } /** * 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 = bindCallback; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = __webpack_require__(65); /** * 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) { return isObject(value) ? value : Object(value); } /** * 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'); } /** * Creates a two dimensional array of the key-value pairs for `object`, * e.g. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) */ function pairs(object) { object = toObject(object); var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } module.exports = pairs; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ "use strict"; var emptyObject = {}; if ("production" !== (undefined)) { Object.freeze(emptyObject); } module.exports = emptyObject; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * 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'; } /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * 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 : object[key]; }; } /** * 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'); /** * 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)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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) && objToString.call(value) == argsTag; } module.exports = isArguments; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.9.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * 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'; } /** 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 resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * 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; } /** * 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 (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = getNative; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `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; /** * 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'; } /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#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`](https://people.mozilla.org/~jorendorff/es6-draft.html#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; } /** * 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; /***/ } /******/ ]) }); ;
ajax/libs/6to5/3.3.4/browser.js
andyinabox/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.to5=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(require,module,exports){(function(global){"use strict";var transform=module.exports=require("./transformation");transform.version=require("../../package").version;transform.transform=transform;transform.run=function(code,opts){opts=opts||{};opts.sourceMap="inline";return new Function(transform(code,opts).code)()};transform.load=function(url,callback,opts,hold){opts=opts||{};opts.filename=opts.filename||url;var xhr=global.ActiveXObject?new global.ActiveXObject("Microsoft.XMLHTTP"):new global.XMLHttpRequest;xhr.open("GET",url,true);if("overrideMimeType"in xhr)xhr.overrideMimeType("text/plain");xhr.onreadystatechange=function(){if(xhr.readyState!==4)return;var status=xhr.status;if(status===0||status===200){var param=[xhr.responseText,opts];if(!hold)transform.run.apply(transform,param);if(callback)callback(param)}else{throw new Error("Could not load "+url)}};xhr.send(null)};var runScripts=function(){var scripts=[];var types=["text/ecmascript-6","text/6to5","module"];var index=0;var exec=function(){var param=scripts[index];if(param instanceof Array){transform.run.apply(transform,param);index++;exec()}};var run=function(script,i){var opts={};if(script.src){transform.load(script.src,function(param){scripts[i]=param;exec()},opts,true)}else{opts.filename="embedded";scripts[i]=[script.innerHTML,opts]}};var _scripts=global.document.getElementsByTagName("script");for(var i=0;i<_scripts.length;++i){var _script=_scripts[i];if(types.indexOf(_script.type)>=0)scripts.push(_script)}for(i in scripts){run(scripts[i],i)}exec()};if(global.addEventListener){global.addEventListener("DOMContentLoaded",runScripts,false)}else if(global.attachEvent){global.attachEvent("onload",runScripts)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../package":296,"./transformation":38}],2:[function(require,module,exports){"use strict";module.exports=File;var SHEBANG_REGEX=/^\#\!.*/;var transform=require("./transformation");var generate=require("./generation");var clone=require("./helpers/clone");var Scope=require("./traverse/scope");var util=require("./util");var t=require("./types");var contains=require("lodash/collection/contains");var each=require("lodash/collection/each");var defaults=require("lodash/object/defaults");var isFunction=require("lodash/lang/isFunction");function File(opts){this.dynamicImportIds={};this.dynamicImported=[];this.dynamicImports=[];this.dynamicData={};this.data={};this.lastStatements=[];this.opts=this.normaliseOptions(opts);this.ast={};this.buildTransformers()}File.helpers=["inherits","defaults","prototype-properties","apply-constructor","tagged-template-literal","tagged-template-literal-loose","interop-require","to-array","sliced-to-array","object-without-properties","has-own","slice","bind","define-property","async-to-generator","interop-require-wildcard","typeof","extends","get","set"];File.validOptions=["filename","filenameRelative","blacklist","whitelist","loose","optional","modules","sourceMap","sourceMapName","sourceFileName","sourceRoot","moduleRoot","moduleIds","comments","reactCompat","keepModuleIdExtensions","code","ast","format","playground","experimental","resolveModuleSource","runtime","ignore","only","extensions","accept"];File.prototype.normaliseOptions=function(opts){opts=clone(opts);for(var key in opts){if(key[0]!=="_"&&File.validOptions.indexOf(key)<0){throw new ReferenceError("Unknown option: "+key)}}defaults(opts,{keepModuleIdExtensions:false,resolveModuleSource:null,experimental:false,reactCompat:false,playground:false,whitespace:true,moduleIds:false,blacklist:[],whitelist:[],sourceMap:false,optional:[],comments:true,filename:"unknown",modules:"common",runtime:false,loose:[],code:true,ast:true});opts.filename=opts.filename.replace(/\\/g,"/");opts.blacklist=util.arrayify(opts.blacklist);opts.whitelist=util.arrayify(opts.whitelist);opts.optional=util.arrayify(opts.optional);opts.loose=util.arrayify(opts.loose);if(contains(opts.loose,"all")){opts.loose=Object.keys(transform.transformers)}defaults(opts,{moduleRoot:opts.sourceRoot});defaults(opts,{sourceRoot:opts.moduleRoot});defaults(opts,{filenameRelative:opts.filename});defaults(opts,{sourceFileName:opts.filenameRelative,sourceMapName:opts.filenameRelative});if(opts.playground){opts.experimental=true}if(opts.runtime){this.set("runtimeIdentifier",t.identifier("to5Runtime"))}opts.blacklist=transform._ensureTransformerNames("blacklist",opts.blacklist);opts.whitelist=transform._ensureTransformerNames("whitelist",opts.whitelist);opts.optional=transform._ensureTransformerNames("optional",opts.optional);opts.loose=transform._ensureTransformerNames("loose",opts.loose);return opts};File.prototype.isLoose=function(key){return contains(this.opts.loose,key)};File.prototype.buildTransformers=function(){var file=this;var transformers={};var secondaryStack=[];var stack=[];each(transform.transformers,function(transformer,key){var pass=transformers[key]=transformer.buildPass(file);if(pass.canRun(file)){stack.push(pass);if(transformer.secondPass){secondaryStack.push(pass)}if(transformer.manipulateOptions){transformer.manipulateOptions(file.opts,file)}}});this.transformerStack=stack.concat(secondaryStack);this.transformers=transformers};File.prototype.toArray=function(node,i){if(t.isArrayExpression(node)){return node}else if(t.isIdentifier(node)&&node.name==="arguments"){return t.callExpression(t.memberExpression(this.addHelper("slice"),t.identifier("call")),[node])}else{var declarationName="to-array";var args=[node];if(i){args.push(t.literal(i));declarationName="sliced-to-array"}return t.callExpression(this.addHelper(declarationName),args)}};File.prototype.getModuleFormatter=function(type){var ModuleFormatter=isFunction(type)?type:transform.moduleFormatters[type];if(!ModuleFormatter){var loc=util.resolve(type);if(loc)ModuleFormatter=require(loc)}if(!ModuleFormatter){throw new ReferenceError("Unknown module formatter type "+JSON.stringify(type))}return new ModuleFormatter(this)};File.prototype.parseShebang=function(code){var shebangMatch=code.match(SHEBANG_REGEX);if(shebangMatch){this.shebang=shebangMatch[0];code=code.replace(SHEBANG_REGEX,"")}return code};File.prototype.set=function(key,val){return this.data[key]=val};File.prototype.setDynamic=function(key,fn){this.dynamicData[key]=fn};File.prototype.get=function(key){var data=this.data[key];if(data){return data}else{var dynamic=this.dynamicData[key];if(dynamic){return this.set(key,dynamic())}}};File.prototype.addImport=function(source,name){name=name||source;var id=this.dynamicImportIds[name];if(!id){id=this.dynamicImportIds[name]=this.generateUidIdentifier(name);var specifiers=[t.importSpecifier(t.identifier("default"),id)];var declar=t.importDeclaration(specifiers,t.literal(source));declar._blockHoist=3;this.dynamicImported.push(declar);this.moduleFormatter.importSpecifier(specifiers[0],declar,this.dynamicImports)}return id};File.prototype.isConsequenceExpressionStatement=function(node){return t.isExpressionStatement(node)&&this.lastStatements.indexOf(node)>=0};File.prototype.addHelper=function(name){if(!contains(File.helpers,name)){throw new ReferenceError("unknown declaration "+name)}var program=this.ast.program;var declar=program._declarations&&program._declarations[name];if(declar)return declar.id;var runtime=this.get("runtimeIdentifier");if(runtime){name=t.identifier(t.toIdentifier(name));return t.memberExpression(runtime,name)}else{var ref=util.template(name);ref._compact=true;var uid=this.generateUidIdentifier(name);this.scope.push({key:name,id:uid,init:ref});return uid}};File.prototype.errorWithNode=function(node,msg,Error){Error=Error||SyntaxError;var loc=node.loc.start;var err=new Error("Line "+loc.line+": "+msg);err.loc=loc;return err};File.prototype.addCode=function(code){code=(code||"")+"";this.code=code;return this.parseShebang(code)};File.prototype.parse=function(code){var self=this;code=this.addCode(code);var opts=this.opts;opts.allowImportExportEverywhere=this.isLoose("es6.modules");return util.parse(opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){var self=this;util.debug(this.opts.filename);this.ast=ast;this.lastStatements=t.getLastStatements(ast.program);this.scope=new Scope(ast.program,ast,null,this);var modFormatter=this.moduleFormatter=this.getModuleFormatter(this.opts.modules);if(modFormatter.init&&this.transformers["es6.modules"].canRun()){modFormatter.init()}var astRun=function(key){each(self.transformerStack,function(pass){pass.astRun(key)})};astRun("enter");each(this.transformerStack,function(pass){pass.transform()});astRun("exit")};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;var result={code:"",map:null,ast:null};if(opts.ast)result.ast=ast;if(!opts.code)return result;var _result=generate(ast,opts,this.code);result.code=_result.code;result.map=_result.map;if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}return result};File.prototype.generateUid=function(name,scope){name=t.toIdentifier(name).replace(/^_+/,"");scope=scope||this.scope;var uid;var i=0;do{uid=this._generateUid(name,i);i++}while(scope.has(uid));return uid};File.prototype.generateUidIdentifier=function(name,scope){scope=scope||this.scope;var id=t.identifier(this.generateUid(name,scope));scope.add(id);return id};File.prototype._generateUid=function(name,i){var id=name;if(i>1)id+=i;return"_"+id}},{"./generation":16,"./helpers/clone":23,"./transformation":38,"./traverse/scope":99,"./types":102,"./util":105,"lodash/collection/contains":176,"lodash/collection/each":177,"lodash/lang/isFunction":247,"lodash/object/defaults":257}],3:[function(require,module,exports){"use strict";module.exports=Buffer;var util=require("../util");var isNumber=require("lodash/lang/isNumber");var isBoolean=require("lodash/lang/isBoolean");var contains=require("lodash/collection/contains");function Buffer(position,format){this.position=position;this._indent=format.indent.base;this.format=format;this.buf=""}Buffer.prototype.get=function(){return util.trimRight(this.buf)};Buffer.prototype.getIndent=function(){if(this.format.compact){return""}else{return util.repeat(this._indent,this.format.indent.style)}};Buffer.prototype.indentSize=function(){return this.getIndent().length};Buffer.prototype.indent=function(){this._indent++};Buffer.prototype.dedent=function(){this._indent--};Buffer.prototype.semicolon=function(){this.push(";")};Buffer.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};Buffer.prototype.rightBrace=function(){this.newline(true);this.push("}")};Buffer.prototype.keyword=function(name){this.push(name);this.push(" ")};Buffer.prototype.space=function(){if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};Buffer.prototype.removeLast=function(cha){if(!this.isLast(cha))return;this.buf=this.buf.substr(0,this.buf.length-1);this.position.unshift(cha)};Buffer.prototype.newline=function(i,removeLast){if(this.format.compact){this.space();return}removeLast=removeLast||false;if(isNumber(i)){if(this.endsWith("{\n"))i--;if(this.endsWith(util.repeat(i,"\n")))return;while(i--){this._newline(removeLast)}return}if(isBoolean(i)){removeLast=i}this._newline(removeLast)};Buffer.prototype._newline=function(removeLast){if(removeLast&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this._removeSpacesAfterLastNewline();this._push("\n")};Buffer.prototype._removeSpacesAfterLastNewline=function(){var lastNewlineIndex=this.buf.lastIndexOf("\n");if(lastNewlineIndex===-1)return;var index=this.buf.length-1;while(index>lastNewlineIndex){if(this.buf[index]!==" "){break}index--}if(index===lastNewlineIndex){this.buf=this.buf.substring(0,index+1)}};Buffer.prototype.push=function(str,noIndent){if(this._indent&&!noIndent&&str!=="\n"){var indent=this.getIndent();str=str.replace(/\n/g,"\n"+indent);if(this.isLast("\n"))str=indent+str}this._push(str)};Buffer.prototype._push=function(str){this.position.push(str);this.buf+=str};Buffer.prototype.endsWith=function(str){var d=this.buf.length-str.length;return d>=0&&this.buf.lastIndexOf(str)===d};Buffer.prototype.isLast=function(cha,trimRight){var buf=this.buf;if(trimRight)buf=util.trimRight(buf);var last=buf[buf.length-1];if(Array.isArray(cha)){return contains(cha,last)}else{return cha===last}}},{"../util":105,"lodash/collection/contains":176,"lodash/lang/isBoolean":245,"lodash/lang/isNumber":249}],4:[function(require,module,exports){"use strict";exports.File=function(node,print){print(node.program)};exports.Program=function(node,print){print.sequence(node.body)};exports.BlockStatement=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();print.sequence(node.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],5:[function(require,module,exports){"use strict";exports.ClassExpression=exports.ClassDeclaration=function(node,print){this.push("class");if(node.id){this.space();print(node.id)}if(node.superClass){this.push(" extends ");print(node.superClass)}this.space();print(node.body)};exports.ClassBody=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();print.sequence(node.body);this.dedent();this.rightBrace()}};exports.MethodDefinition=function(node,print){if(node.static){this.push("static ")}this._method(node,print)}},{}],6:[function(require,module,exports){"use strict";exports.ComprehensionBlock=function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" of ");print(node.right);this.push(")")};exports.ComprehensionExpression=function(node,print){this.push(node.generator?"(":"[");print.join(node.blocks,{separator:" "});this.space();if(node.filter){this.keyword("if");this.push("(");print(node.filter);this.push(")");this.space()}print(node.body);this.push(node.generator?")":"]")}},{}],7:[function(require,module,exports){"use strict";var util=require("../../util");var t=require("../../types");var isNumber=require("lodash/lang/isNumber");exports.UnaryExpression=function(node,print){var hasSpace=/[a-z]$/.test(node.operator);var arg=node.argument;if(t.isUpdateExpression(arg)||t.isUnaryExpression(arg)){hasSpace=true}if(t.isUnaryExpression(arg)&&arg.operator==="!"){hasSpace=false}this.push(node.operator);if(hasSpace)this.space();print(node.argument)};exports.UpdateExpression=function(node,print){if(node.prefix){this.push(node.operator);print(node.argument)}else{print(node.argument);this.push(node.operator)}};exports.ConditionalExpression=function(node,print){print(node.test);this.push(" ? ");print(node.consequent);this.push(" : ");print(node.alternate)};exports.NewExpression=function(node,print){this.push("new ");print(node.callee);if(node.arguments.length||this.format.parentheses){this.push("(");print.join(node.arguments,{separator:", "});this.push(")")}};exports.SequenceExpression=function(node,print){print.join(node.expressions,{separator:", "})};exports.ThisExpression=function(){this.push("this")};exports.CallExpression=function(node,print){print(node.callee);this.push("(");var separator=",";if(node._prettyCall){separator+="\n";this.newline();this.indent()}else{separator+=" "}print.join(node.arguments,{separator:separator});if(node._prettyCall){this.newline();this.dedent()}this.push(")")};var buildYieldAwait=function(keyword){return function(node,print){this.push(keyword);if(node.delegate||node.all){this.push("*")}if(node.argument){this.space();print(node.argument)}}};exports.YieldExpression=buildYieldAwait("yield");exports.AwaitExpression=buildYieldAwait("await");exports.EmptyStatement=function(){this.semicolon()};exports.ExpressionStatement=function(node,print){print(node.expression);this.semicolon()};exports.BinaryExpression=exports.LogicalExpression=exports.AssignmentPattern=exports.AssignmentExpression=function(node,print){print(node.left);this.space();this.push(node.operator);this.space();print(node.right)};var SCIENTIFIC_NOTATION=/e/i;exports.MemberExpression=function(node,print){var obj=node.object;print(obj);if(!node.computed&&t.isMemberExpression(node.property)){throw new TypeError("Got a MemberExpression for MemberExpression property")}var computed=node.computed;if(t.isLiteral(node.property)&&isNumber(node.property.value)){computed=true}if(computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(obj)&&util.isInteger(obj.value)&&!SCIENTIFIC_NOTATION.test(obj.value.toString())){this.push(".")}this.push(".");print(node.property)}}},{"../../types":102,"../../util":105,"lodash/lang/isNumber":249}],8:[function(require,module,exports){"use strict";exports.AnyTypeAnnotation=exports.ArrayTypeAnnotation=exports.BooleanTypeAnnotation=exports.ClassProperty=exports.DeclareClass=exports.DeclareFunction=exports.DeclareModule=exports.DeclareVariable=exports.FunctionTypeAnnotation=exports.FunctionTypeParam=exports.GenericTypeAnnotation=exports.InterfaceExtends=exports.InterfaceDeclaration=exports.IntersectionTypeAnnotation=exports.NullableTypeAnnotation=exports.NumberTypeAnnotation=exports.StringLiteralTypeAnnotation=exports.StringTypeAnnotation=exports.TupleTypeAnnotation=exports.TypeofTypeAnnotation=exports.TypeAlias=exports.TypeAnnotation=exports.TypeParameterDeclaration=exports.TypeParameterInstantiation=exports.ObjectTypeAnnotation=exports.ObjectTypeCallProperty=exports.ObjectTypeIndexer=exports.ObjectTypeProperty=exports.QualifiedTypeIdentifier=exports.UnionTypeAnnotation=exports.VoidTypeAnnotation=function(){}},{}],9:[function(require,module,exports){"use strict";var t=require("../../types");var each=require("lodash/collection/each");exports.JSXAttribute=function(node,print){print(node.name);if(node.value){this.push("=");print(node.value)}};exports.JSXIdentifier=function(node){this.push(node.name)};exports.JSXNamespacedName=function(node,print){print(node.namespace);this.push(":");print(node.name)};exports.JSXMemberExpression=function(node,print){print(node.object);this.push(".");print(node.property)};exports.JSXSpreadAttribute=function(node,print){this.push("{...");print(node.argument);this.push("}")};exports.JSXExpressionContainer=function(node,print){this.push("{");print(node.expression);this.push("}")};exports.JSXElement=function(node,print){var self=this;var open=node.openingElement;print(open);if(open.selfClosing)return;this.indent();each(node.children,function(child){if(t.isLiteral(child)){self.push(child.value)}else{print(child)}});this.dedent();print(node.closingElement)};exports.JSXOpeningElement=function(node,print){this.push("<");print(node.name);if(node.attributes.length>0){this.push(" ");print.join(node.attributes,{separator:" "})}this.push(node.selfClosing?" />":">")};exports.JSXClosingElement=function(node,print){this.push("</");print(node.name);this.push(">")};exports.JSXEmptyExpression=function(){}},{"../../types":102,"lodash/collection/each":177}],10:[function(require,module,exports){"use strict";var t=require("../../types");exports._params=function(node,print){this.push("(");print.join(node.params,{separator:", "});this.push(")")};exports._method=function(node,print){var value=node.value;var kind=node.kind;var key=node.key;if(!kind||kind==="init"){if(value.generator){this.push("*")}}else{this.push(kind+" ")}if(value.async)this.push("async ");if(node.computed){this.push("[");print(key);this.push("]")}else{print(key)}this._params(value,print);this.push(" ");print(value.body)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,print){if(node.async)this.push("async ");this.push("function");if(node.generator)this.push("*");this.push(" ");if(node.id){this.space();print(node.id)}this._params(node,print);this.space();print(node.body)};exports.ArrowFunctionExpression=function(node,print){if(node.async)this.push("async ");if(node.params.length===1&&t.isIdentifier(node.params[0])){print(node.params[0])}else{this._params(node,print)}this.push(" => ");print(node.body)}},{"../../types":102}],11:[function(require,module,exports){"use strict";var t=require("../../types");var each=require("lodash/collection/each");exports.ImportSpecifier=function(node,print){if(t.isSpecifierDefault(node)){print(t.getSpecifierName(node))}else{return exports.ExportSpecifier.apply(this,arguments)}};exports.ExportSpecifier=function(node,print){print(node.id);if(node.name){this.push(" as ");print(node.name)}};exports.ExportBatchSpecifier=function(){this.push("*")};exports.ExportDeclaration=function(node,print){this.push("export ");var specifiers=node.specifiers;if(node.default){this.push("default ")}if(node.declaration){print(node.declaration);if(t.isStatement(node.declaration))return}else{if(specifiers.length===1&&t.isExportBatchSpecifier(specifiers[0])){print(specifiers[0])}else{this.push("{");if(specifiers.length){this.space();print.join(specifiers,{separator:", "});this.space()}this.push("}")}if(node.source){this.push(" from ");print(node.source)}}this.ensureSemicolon()};exports.ImportDeclaration=function(node,print){var self=this;this.push("import ");var specfiers=node.specifiers;if(specfiers&&specfiers.length){var foundImportSpecifier=false;each(node.specifiers,function(spec,i){if(+i>0){self.push(", ")}var isDefault=t.isSpecifierDefault(spec);if(!isDefault&&spec.type!=="ImportBatchSpecifier"&&!foundImportSpecifier){foundImportSpecifier=true;self.push("{ ")}print(spec)});if(foundImportSpecifier){this.push(" }")}this.push(" from ")}print(node.source);this.semicolon()};exports.ImportBatchSpecifier=function(node,print){this.push("* as ");print(node.name)}},{"../../types":102,"lodash/collection/each":177}],12:[function(require,module,exports){"use strict";var each=require("lodash/collection/each");each(["BindMemberExpression","BindFunctionExpression"],function(type){exports[type]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(type))}})},{"lodash/collection/each":177}],13:[function(require,module,exports){"use strict";var util=require("../../util");var t=require("../../types");exports.WithStatement=function(node,print){this.keyword("with");this.push("(");print(node.object);this.push(")");print.block(node.body)};exports.IfStatement=function(node,print){this.keyword("if");this.push("(");print(node.test);this.push(")");this.space();print.indentOnComments(node.consequent);if(node.alternate){if(this.isLast("}"))this.push(" ");this.keyword("else");print.indentOnComments(node.alternate)}};exports.ForStatement=function(node,print){this.keyword("for");this.push("(");print(node.init);this.push(";");if(node.test){this.push(" ");print(node.test)}this.push(";");if(node.update){this.push(" ");print(node.update)}this.push(")");print.block(node.body)};exports.WhileStatement=function(node,print){this.keyword("while");this.push("(");print(node.test);this.push(")");print.block(node.body)};var buildForXStatement=function(op){return function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" "+op+" ");print(node.right);this.push(")");print.block(node.body)}};exports.ForInStatement=buildForXStatement("in");exports.ForOfStatement=buildForXStatement("of");exports.DoWhileStatement=function(node,print){this.keyword("do");print(node.body);this.space();this.keyword("while");this.push("(");print(node.test);this.push(");")};var buildLabelStatement=function(prefix,key){return function(node,print){this.push(prefix);var label=node[key||"label"];if(label){this.push(" ");print(label)}this.semicolon()}};exports.ContinueStatement=buildLabelStatement("continue");exports.ReturnStatement=buildLabelStatement("return","argument");exports.BreakStatement=buildLabelStatement("break");exports.LabeledStatement=function(node,print){print(node.label);this.push(": ");print(node.body)};exports.TryStatement=function(node,print){this.keyword("try");print(node.block);this.space();if(node.handlers){print(node.handlers[0])}else{print(node.handler)}if(node.finalizer){this.space();this.push("finally ");print(node.finalizer)}};exports.CatchClause=function(node,print){this.keyword("catch");this.push("(");print(node.param);this.push(") ");print(node.body)};exports.ThrowStatement=function(node,print){this.push("throw ");print(node.argument);this.semicolon()};exports.SwitchStatement=function(node,print){this.keyword("switch");this.push("(");print(node.discriminant);this.push(")");this.space();this.push("{");print.sequence(node.cases,{indent:true});this.push("}")};exports.SwitchCase=function(node,print){if(node.test){this.push("case ");print(node.test);this.push(":")}else{this.push("default:")}this.newline();print.sequence(node.consequent,{indent:true})};exports.DebuggerStatement=function(){this.push("debugger;")};exports.VariableDeclaration=function(node,print,parent){this.push(node.kind+" ");var hasInits=false;if(!t.isFor(parent)){for(var i=0;i<node.declarations.length;i++){if(node.declarations[i].init){hasInits=true}}}var sep=",";if(hasInits){sep+="\n"+util.repeat(node.kind.length+1)}else{sep+=" "}print.join(node.declarations,{separator:sep});if(!t.isFor(parent)){this.semicolon()}};exports.PrivateDeclaration=function(node,print){this.push("private ");print.join(node.declarations,{separator:", "});this.semicolon()};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.space();this.push("=");this.space();print(node.init)}else{print(node.id)}}},{"../../types":102,"../../util":105}],14:[function(require,module,exports){"use strict";var each=require("lodash/collection/each");exports.TaggedTemplateExpression=function(node,print){print(node.tag);print(node.quasi)};exports.TemplateElement=function(node){this._push(node.value.raw)};exports.TemplateLiteral=function(node,print){this.push("`");var quasis=node.quasis;var self=this;var len=quasis.length;each(quasis,function(quasi,i){print(quasi);if(i+1<len){self.push("${ ");print(node.expressions[i]);self.push(" }")}});this._push("`")}},{"lodash/collection/each":177}],15:[function(require,module,exports){"use strict";var each=require("lodash/collection/each");exports.Identifier=function(node){this.push(node.name)};exports.RestElement=exports.SpreadElement=exports.SpreadProperty=function(node,print){this.push("...");print(node.argument)};exports.VirtualPropertyExpression=function(node,print){print(node.object);this.push("::");print(node.property)};exports.ObjectExpression=exports.ObjectPattern=function(node,print){var props=node.properties;if(props.length){this.push("{");this.space();print.join(props,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};exports.Property=function(node,print){if(node.method||node.kind==="get"||node.kind==="set"){this._method(node,print)}else{if(node.computed){this.push("[");print(node.key);this.push("]")}else{print(node.key);if(node.shorthand)return}this.push(": ");print(node.value)}};exports.ArrayExpression=exports.ArrayPattern=function(node,print){var elems=node.elements;var self=this;var len=elems.length;this.push("[");each(elems,function(elem,i){if(!elem){self.push(",")}else{if(i>0)self.push(" ");print(elem);if(i<len-1)self.push(",")}});this.push("]")};exports.Literal=function(node){var val=node.value;var type=typeof val;if(type==="string"){val=JSON.stringify(val);val=val.replace(/[\u000A\u000D\u2028\u2029]/g,function(c){return"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)});this.push(val)}else if(type==="boolean"||type==="number"){this.push(JSON.stringify(val))}else if(node.regex){this.push("/"+node.regex.pattern+"/"+node.regex.flags)}else if(val===null){this.push("null")}}},{"lodash/collection/each":177}],16:[function(require,module,exports){"use strict";module.exports=function(ast,opts,code){var gen=new CodeGenerator(ast,opts,code);return gen.generate()};module.exports.CodeGenerator=CodeGenerator;var detectIndent=require("detect-indent");var Whitespace=require("./whitespace");var SourceMap=require("./source-map");var Position=require("./position");var Buffer=require("./buffer");var util=require("../util");var n=require("./node");var t=require("../types");var each=require("lodash/collection/each");var extend=require("lodash/object/extend");var merge=require("lodash/object/merge");function CodeGenerator(ast,opts,code){opts=opts||{};this.comments=ast.comments||[];this.tokens=ast.tokens||[];this.format=CodeGenerator.normaliseOptions(code,opts);this.ast=ast;this.whitespace=new Whitespace(this.tokens,this.comments);this.position=new Position;this.map=new SourceMap(this.position,opts,code);this.buffer=new Buffer(this.position,this.format)}each(Buffer.prototype,function(fn,key){CodeGenerator.prototype[key]=function(){return fn.apply(this.buffer,arguments)}});CodeGenerator.normaliseOptions=function(code,opts){var style=" ";if(code){var indent=detectIndent(code).indent;if(indent&&indent!==" ")style=indent}return merge({parentheses:true,comments:opts.comments==null||opts.comments,compact:false,indent:{adjustMultilineComment:true,style:style,base:0}},opts.format||{})};CodeGenerator.generators={templateLiterals:require("./generators/template-literals"),comprehensions:require("./generators/comprehensions"),expressions:require("./generators/expressions"),statements:require("./generators/statements"),playground:require("./generators/playground"),classes:require("./generators/classes"),methods:require("./generators/methods"),modules:require("./generators/modules"),types:require("./generators/types"),flow:require("./generators/flow"),base:require("./generators/base"),jsx:require("./generators/jsx")};each(CodeGenerator.generators,function(generator){extend(CodeGenerator.prototype,generator)});CodeGenerator.prototype.generate=function(){var ast=this.ast;this.print(ast);var comments=[];each(ast.comments,function(comment){if(!comment._displayed)comments.push(comment)});this._printComments(comments);return{map:this.map.get(),code:this.buffer.get()}};CodeGenerator.prototype.buildPrint=function(parent){var self=this;var print=function(node,opts){return self.print(node,parent,opts)};print.sequence=function(nodes,opts){opts=opts||{};opts.statement=true;return self.printJoin(print,nodes,opts)};print.join=function(nodes,opts){return self.printJoin(print,nodes,opts)};print.block=function(node){return self.printBlock(print,node)};print.indentOnComments=function(node){return self.printAndIndentOnComments(print,node)};return print};CodeGenerator.prototype.print=function(node,parent,opts){if(!node)return"";if(parent&&parent._compact){node._compact=true}var oldCompact=this.format.compact;if(node._compact){this.format.compact=true}var self=this;opts=opts||{};var newline=function(leading){if(!opts.statement&&!n.isUserWhitespacable(node,parent)){return}var lines=0;if(node.start!=null&&!node._ignoreUserWhitespace){if(leading){lines=self.whitespace.getNewlinesBefore(node)}else{lines=self.whitespace.getNewlinesAfter(node)}}else{if(!leading)lines++;var needs=n.needsWhitespaceAfter;if(leading)needs=n.needsWhitespaceBefore;lines+=needs(node,parent);if(!self.buffer.get())lines=0}self.newline(lines)};if(this[node.type]){var needsNoLineTermParens=n.needsParensNoLineTerminator(node,parent);var needsParens=needsNoLineTermParens||n.needsParens(node,parent);if(needsParens)this.push("(");if(needsNoLineTermParens)this.indent(); this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node);this[node.type](node,this.buildPrint(node),parent);if(needsNoLineTermParens){this.newline();this.dedent()}if(needsParens)this.push(")");if(opts.after)opts.after();newline(false);this.printTrailingComments(node,parent)}else{throw new ReferenceError("unknown node of type "+JSON.stringify(node.type)+" with constructor "+JSON.stringify(node&&node.constructor.name))}this.format.compact=oldCompact};CodeGenerator.prototype.printJoin=function(print,nodes,opts){if(!nodes||!nodes.length)return;opts=opts||{};var self=this;var len=nodes.length;if(opts.indent)self.indent();each(nodes,function(node,i){print(node,{statement:opts.statement,after:function(){if(opts.iterator){opts.iterator(node,i)}if(opts.separator&&i<len-1){self.push(opts.separator)}}})});if(opts.indent)self.dedent()};CodeGenerator.prototype.printAndIndentOnComments=function(print,node){var indent=!!node.leadingComments;if(indent)this.indent();print(node);if(indent)this.dedent()};CodeGenerator.prototype.printBlock=function(print,node){if(t.isEmptyStatement(node)){this.semicolon()}else{this.push(" ");print(node)}};CodeGenerator.prototype.generateComment=function(comment){var val=comment.value;if(comment.type==="Line"){val="//"+val}else{val="/*"+val+"*/"}return val};CodeGenerator.prototype.printTrailingComments=function(node,parent){this._printComments(this.getComments("trailingComments",node,parent))};CodeGenerator.prototype.printLeadingComments=function(node,parent){this._printComments(this.getComments("leadingComments",node,parent))};CodeGenerator.prototype.getComments=function(key,node,parent){if(t.isExpressionStatement(parent)){return[]}var comments=[];var nodes=[node];var self=this;if(t.isExpressionStatement(node)){nodes.push(node.argument)}each(nodes,function(node){comments=comments.concat(self._getComments(key,node))});return comments};CodeGenerator.prototype._getComments=function(key,node){return node&&node[key]||[]};CodeGenerator.prototype._printComments=function(comments){if(this.format.compact)return;if(!this.format.comments)return;if(!comments||!comments.length)return;var self=this;each(comments,function(comment){var skip=false;each(self.ast.comments,function(origComment){if(origComment.start===comment.start){if(origComment._displayed)skip=true;origComment._displayed=true;return false}});if(skip)return;self.newline(self.whitespace.getNewlinesBefore(comment));var column=self.position.column;var val=self.generateComment(comment);if(column&&!self.isLast(["\n"," ","[","{"])){self._push(" ");column++}if(comment.type==="Block"&&self.format.indent.adjustMultilineComment){var offset=comment.loc.start.column;if(offset){var newlineRegex=new RegExp("\\n\\s{1,"+offset+"}","g");val=val.replace(newlineRegex,"\n")}var indent=Math.max(self.indentSize(),column);val=val.replace(/\n/g,"\n"+util.repeat(indent))}if(column===0){val=self.getIndent()+val}self._push(val);self.newline(self.whitespace.getNewlinesAfter(comment))})}},{"../types":102,"../util":105,"./buffer":3,"./generators/base":4,"./generators/classes":5,"./generators/comprehensions":6,"./generators/expressions":7,"./generators/flow":8,"./generators/jsx":9,"./generators/methods":10,"./generators/modules":11,"./generators/playground":12,"./generators/statements":13,"./generators/template-literals":14,"./generators/types":15,"./node":17,"./position":20,"./source-map":21,"./whitespace":22,"detect-indent":160,"lodash/collection/each":177,"lodash/object/extend":258,"lodash/object/merge":262}],17:[function(require,module,exports){"use strict";module.exports=Node;var whitespace=require("./whitespace");var parens=require("./parentheses");var t=require("../../types");var each=require("lodash/collection/each");var some=require("lodash/collection/some");var find=function(obj,node,parent){if(!obj)return;var result;var types=Object.keys(obj);for(var i=0;i<types.length;i++){var type=types[i];if(t.is(type,node)){var fn=obj[type];result=fn(node,parent);if(result!=null)break}}return result};function Node(node,parent){this.parent=parent;this.node=node}Node.isUserWhitespacable=function(node){return t.isUserWhitespacable(node)};Node.needsWhitespace=function(node,parent,type){if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var lines=find(whitespace[type].nodes,node,parent);if(lines)return lines;each(find(whitespace[type].list,node,parent),function(expr){lines=Node.needsWhitespace(expr,node,type);if(lines)return false});return lines||0};Node.needsWhitespaceBefore=function(node,parent){return Node.needsWhitespace(node,parent,"before")};Node.needsWhitespaceAfter=function(node,parent){return Node.needsWhitespace(node,parent,"after")};Node.needsParens=function(node,parent){if(!parent)return false;if(t.isNewExpression(parent)&&parent.callee===node){if(t.isCallExpression(node))return true;var hasCall=some(node,function(val){return t.isCallExpression(val)});if(hasCall)return true}return find(parens,node,parent)};Node.needsParensNoLineTerminator=function(node,parent){if(!parent)return false;if(!node.leadingComments||!node.leadingComments.length){return false}if(t.isYieldExpression(parent)||t.isAwaitExpression(parent)){return true}if(t.isContinueStatement(parent)||t.isBreakStatement(parent)||t.isReturnStatement(parent)||t.isThrowStatement(parent)){return true}return false};each(Node,function(fn,key){Node.prototype[key]=function(){var args=new Array(arguments.length+2);args[0]=this.node;args[1]=this.parent;for(var i=0;i<args.length;i++){args[i+2]=arguments[i]}return Node[key].apply(null,args)}})},{"../../types":102,"./parentheses":18,"./whitespace":19,"lodash/collection/each":177,"lodash/collection/some":182}],18:[function(require,module,exports){"use strict";var t=require("../../types");var each=require("lodash/collection/each");var PRECEDENCE={};each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],function(tier,i){each(tier,function(op){PRECEDENCE[op]=i})});exports.UpdateExpression=function(node,parent){if(t.isMemberExpression(parent)&&parent.object===node){return true}};exports.ObjectExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false};exports.Binary=function(node,parent){if((t.isCallExpression(parent)||t.isNewExpression(parent))&&parent.callee===node){return true}if(t.isUnaryLike(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isBinary(parent)){var parentOp=parent.operator;var parentPos=PRECEDENCE[parentOp];var nodeOp=node.operator;var nodePos=PRECEDENCE[nodeOp];if(parentPos>nodePos){return true}if(parentPos===nodePos&&parent.right===node){return true}}};exports.BinaryExpression=function(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}};exports.SequenceExpression=function(node,parent){if(t.isForStatement(parent)){return false}if(t.isExpressionStatement(parent)&&parent.expression===node){return false}return true};exports.YieldExpression=function(node,parent){return t.isBinary(parent)||t.isUnaryLike(parent)||t.isCallExpression(parent)||t.isMemberExpression(parent)||t.isNewExpression(parent)||t.isConditionalExpression(parent)||t.isYieldExpression(parent)};exports.ClassExpression=function(node,parent){return t.isExpressionStatement(parent)};exports.UnaryLike=function(node,parent){return t.isMemberExpression(parent)&&parent.object===node};exports.FunctionExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}};exports.AssignmentExpression=exports.ConditionalExpression=function(node,parent){if(t.isUnaryLike(parent)){return true}if(t.isBinary(parent)){return true}if(t.isCallExpression(parent)||t.isNewExpression(parent)){if(parent.callee===node){return true}}if(t.isConditionalExpression(parent)&&parent.test===node){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false}},{"../../types":102,"lodash/collection/each":177}],19:[function(require,module,exports){"use strict";var t=require("../../types");var each=require("lodash/collection/each");var map=require("lodash/collection/map");var isNumber=require("lodash/lang/isNumber");exports.before={nodes:{Property:function(node,parent){if(parent.properties[0]===node){return 1}},SpreadProperty:function(node,parent){return exports.before.nodes.Property(node,parent)},SwitchCase:function(node,parent){if(parent.cases[0]===node){return 1}},CallExpression:function(node){if(t.isFunction(node.callee)){return 1}}}};exports.after={nodes:{LogicalExpression:function(node){return t.isFunction(node.left)||t.isFunction(node.right)},AssignmentExpression:function(node){if(t.isFunction(node.right)){return 1}}},list:{VariableDeclaration:function(node){return map(node.declarations,"init")},ArrayExpression:function(node){return node.elements},ObjectExpression:function(node){return node.properties}}};each({Function:1,Class:1,For:1,ArrayExpression:{after:1},ObjectExpression:{after:1},SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(amounts,type){if(isNumber(amounts)){amounts={after:amounts,before:amounts}}each([type].concat(t.FLIPPED_ALIAS_KEYS[type]||[]),function(type){each(amounts,function(amount,key){exports[key].nodes[type]=function(){return amount}})})})},{"../../types":102,"lodash/collection/each":177,"lodash/collection/map":181,"lodash/lang/isNumber":249}],20:[function(require,module,exports){"use strict";module.exports=Position;function Position(){this.line=1;this.column=0}Position.prototype.push=function(str){for(var i=0;i<str.length;i++){if(str[i]==="\n"){this.line++;this.column=0}else{this.column++}}};Position.prototype.unshift=function(str){for(var i=0;i<str.length;i++){if(str[i]==="\n"){this.line--}else{this.column--}}}},{}],21:[function(require,module,exports){"use strict";module.exports=SourceMap;var sourceMap=require("source-map");var t=require("../types");function SourceMap(position,opts,code){this.position=position;this.opts=opts;if(opts.sourceMap){this.map=new sourceMap.SourceMapGenerator({file:opts.sourceMapName,sourceRoot:opts.sourceRoot});this.map.setSourceContent(opts.sourceFileName,code)}else{this.map=null}}SourceMap.prototype.get=function(){var map=this.map;if(map){return map.toJSON()}else{return map}};SourceMap.prototype.mark=function(node){var loc=node.loc;if(!loc)return;var map=this.map;if(!map)return;if(t.isProgram(node)||t.isFile(node))return;var position=this.position;var generated={line:position.line,column:position.column};var original=loc.start;map.addMapping({source:this.opts.sourceFileName,generated:generated,original:original})}},{"../types":102,"source-map":284}],22:[function(require,module,exports){"use strict";module.exports=Whitespace;var sortBy=require("lodash/collection/sortBy");function getLookupIndex(i,base,max){i+=base;if(i>=max)i-=max;return i}function Whitespace(tokens,comments){this.tokens=sortBy(tokens.concat(comments),"start");this.used={};this._lastFoundIndex=0}Whitespace.prototype.getNewlinesBefore=function(node){var startToken;var endToken;var tokens=this.tokens;var token;for(var j=0;j<tokens.length;j++){var i=getLookupIndex(j,this._lastFoundIndex,this.tokens.length);token=tokens[i];if(node.start===token.start){startToken=tokens[i-1];endToken=token;this._lastFoundIndex=i;break}}return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesAfter=function(node){var startToken;var endToken;var tokens=this.tokens;var token;for(var j=0;j<tokens.length;j++){var i=getLookupIndex(j,this._lastFoundIndex,this.tokens.length);token=tokens[i];if(node.end===token.end){startToken=token;endToken=tokens[i+1];this._lastFoundIndex=i;break}}if(endToken.type.type==="eof"){return 1}else{var lines=this.getNewlinesBetween(startToken,endToken);if(node.type==="Line"&&!lines){return 1}else{return lines}}};Whitespace.prototype.getNewlinesBetween=function(startToken,endToken){var start=startToken?startToken.loc.end.line:1;var end=endToken.loc.start.line;var lines=0;for(var line=start;line<end;line++){if(typeof this.used[line]==="undefined"){this.used[line]=true;lines++}}return lines}},{"lodash/collection/sortBy":183}],23:[function(require,module,exports){"use strict";module.exports=function cloneDeep(obj){var obj2={};if(!obj)return obj2;for(var key in obj){obj2[key]=obj[key]}return obj2}},{}],24:[function(require,module,exports){var supportsColor=require("supports-color");var tokenize=require("js-tokenizer");var chalk=require("chalk");var util=require("../util");var defs={string1:"red",string2:"red",punct:["white","bold"],curly:"green",parens:["blue","bold"],square:["yellow"],name:"white",keyword:["cyan"],number:"magenta",regexp:"magenta",comment1:"grey",comment2:"grey"};var highlight=function(text){var colorize=function(str,col){if(!col)return str;if(Array.isArray(col)){col.forEach(function(col){str=chalk[col](str)})}else{str=chalk[col](str)}return str};return tokenize(text,true).map(function(str){var type=tokenize.type(str);return colorize(str,defs[type])}).join("")};module.exports=function(lines,lineNumber,colNumber){colNumber=Math.max(colNumber,0);if(supportsColor){lines=highlight(lines)}lines=lines.split(/\r\n|[\n\r\u2028\u2029]/);var start=Math.max(lineNumber-3,0);var end=Math.min(lines.length,lineNumber+3);var width=(end+"").length;if(!lineNumber&&!colNumber){start=0;end=lines.length}return"\n"+lines.slice(start,end).map(function(line,i){var curr=i+start+1;var gutter=curr===lineNumber?"> ":" ";var sep=curr+util.repeat(width+1);gutter+=sep+"| ";var str=gutter+line;if(colNumber&&curr===lineNumber){str+="\n";str+=util.repeat(gutter.length-2);str+="|"+util.repeat(colNumber)+"^"}return str}).join("\n")}},{"../util":105,chalk:148,"js-tokenizer":170,"supports-color":295}],25:[function(require,module,exports){module.exports=function(a,b){if(a.length===0)return b.length;if(b.length===0)return a.length;var matrix=[];var i;for(i=0;i<=b.length;i++){matrix[i]=[i]}var j;for(j=0;j<=a.length;j++){matrix[0][j]=j}for(i=1;i<=b.length;i++){for(j=1;j<=a.length;j++){if(b.charAt(i-1)==a.charAt(j-1)){matrix[i][j]=matrix[i-1][j-1]}else{matrix[i][j]=Math.min(matrix[i-1][j-1]+1,Math.min(matrix[i][j-1]+1,matrix[i-1][j]+1))}}}return matrix[b.length][a.length]}},{}],26:[function(require,module,exports){"use strict";module.exports=function(){return Object.create(null)}},{}],27:[function(require,module,exports){"use strict";module.exports=function toFastProperties(obj){function f(){}f.prototype=obj;return f;eval(obj)}},{}],28:[function(require,module,exports){"use strict";var t=require("./types");var extend=require("lodash/object/extend");require("./types/node");var estraverse=require("estraverse");extend(estraverse.VisitorKeys,t.VISITOR_KEYS);var types=require("ast-types");var def=types.Type.def;var or=types.Type.or;def("File").bases("Node").build("program").field("program",def("Program"));def("AssignmentPattern").bases("Pattern").build("left","right").field("left",def("Pattern")).field("right",def("Expression"));def("ImportBatchSpecifier").bases("Specifier").build("name").field("name",def("Identifier"));def("RestElement").bases("Pattern").build("argument").field("argument",def("expression"));def("VirtualPropertyExpression").bases("Expression").build("object","property").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression")));def("PrivateDeclaration").bases("Declaration").build("declarations").field("declarations",[def("Identifier")]);def("BindMemberExpression").bases("Expression").build("object","property","arguments").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("arguments",[def("Expression")]);def("BindFunctionExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);types.finalize()},{"./types":102,"./types/node":103,"ast-types":120,estraverse:163,"lodash/object/extend":258}],29:[function(require,module,exports){"use strict";var explode=require("./explode-assignable-expression");var t=require("../../types");module.exports=function(exports,opts){var isAssignment=function(node){return node.operator===opts.operator+"="};var buildAssignment=function(left,right){return t.assignmentExpression("=",left,right)};exports.ExpressionStatement=function(node,parent,scope,context,file){if(file.isConsequenceExpressionStatement(node))return;var expr=node.expression;if(!isAssignment(expr))return;var nodes=[];var exploded=explode(expr.left,nodes,file,scope,true);nodes.push(t.expressionStatement(buildAssignment(exploded.ref,opts.build(exploded.uid,expr.right))));return nodes};exports.AssignmentExpression=function(node,parent,scope,context,file){if(!isAssignment(node))return;var nodes=[];var exploded=explode(node.left,nodes,file,scope);nodes.push(buildAssignment(exploded.ref,opts.build(exploded.uid,node.right)));return t.toSequenceExpression(nodes,scope)};exports.BinaryExpression=function(node){if(node.operator!==opts.operator)return;return opts.build(node.left,node.right)}}},{"../../types":102,"./explode-assignable-expression":32}],30:[function(require,module,exports){"use strict";var t=require("../../types");module.exports=function build(node,buildBody){var self=node.blocks.shift();if(!self)return;var child=build(node,buildBody);if(!child){child=buildBody();if(node.filter){child=t.ifStatement(node.filter,t.blockStatement([child]))}}return t.forOfStatement(t.variableDeclaration("let",[t.variableDeclarator(self.left)]),self.right,t.blockStatement([child]))}},{"../../types":102}],31:[function(require,module,exports){"use strict";var explode=require("./explode-assignable-expression");var t=require("../../types");module.exports=function(exports,opts){var buildAssignment=function(left,right){return t.assignmentExpression("=",left,right)};exports.ExpressionStatement=function(node,parent,scope,context,file){if(file.isConsequenceExpressionStatement(node))return;var expr=node.expression;if(!opts.is(expr,file))return;var nodes=[];var exploded=explode(expr.left,nodes,file,scope);nodes.push(t.ifStatement(opts.build(exploded.uid,file),t.expressionStatement(buildAssignment(exploded.ref,expr.right))));return nodes};exports.AssignmentExpression=function(node,parent,scope,context,file){if(!opts.is(node,file))return;var nodes=[];var exploded=explode(node.left,nodes,file,scope);nodes.push(t.logicalExpression("&&",opts.build(exploded.uid,file),buildAssignment(exploded.ref,node.right)));nodes.push(exploded.ref);return t.toSequenceExpression(nodes,scope)}}},{"../../types":102,"./explode-assignable-expression":32}],32:[function(require,module,exports){"use strict";var t=require("../../types");var getObjRef=function(node,nodes,file,scope){var ref;if(t.isIdentifier(node)){if(scope.has(node.name,true)){return node}else{ref=node}}else if(t.isMemberExpression(node)){ref=node.object;if(t.isIdentifier(ref)&&scope.has(ref.name)){return ref}}else{throw new Error("We can't explode this node type "+node.type)}var temp=scope.generateUidBasedOnNode(ref);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,ref)]));return temp};var getPropRef=function(node,nodes,file,scope){var prop=node.property;var key=t.toComputedKey(node,prop);if(t.isLiteral(key))return key;var temp=scope.generateUidBasedOnNode(prop);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,prop)]));return temp};module.exports=function(node,nodes,file,scope,allowedSingleIdent){var obj;if(t.isIdentifier(node)&&allowedSingleIdent){obj=node}else{obj=getObjRef(node,nodes,file,scope)}var ref,uid;if(t.isIdentifier(node)){ref=node;uid=obj}else{var prop=getPropRef(node,nodes,file,scope);var computed=node.computed||t.isLiteral(prop);uid=ref=t.memberExpression(obj,prop,computed)}return{uid:uid,ref:ref}}},{"../../types":102}],33:[function(require,module,exports){"use strict";var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var visitor={enter:function(node,parent,scope,context,state){if(!t.isIdentifier(node,{name:state.id}))return;if(!t.isReferenced(node,parent))return;var localDeclar=scope.get(state.id,true);if(localDeclar!==state.outerDeclar)return;state.selfReference=true;context.stop()}};exports.property=function(node,file,scope){var key=t.toComputedKey(node,node.key);if(!t.isLiteral(key))return node;var id=t.toIdentifier(key.value);key=t.identifier(id);var state={id:id,selfReference:false,outerDeclar:scope.get(id,true)};traverse(node,visitor,scope,state);if(state.selfReference){node.value=util.template("property-method-assignment-wrapper",{FUNCTION:node.value,FUNCTION_ID:key,FUNCTION_KEY:scope.generateUidIdentifier(id),WRAPPER_KEY:scope.generateUidIdentifier(id+"Wrapper")})}else{node.value.id=key}}},{"../../traverse":98,"../../types":102,"../../util":105}],34:[function(require,module,exports){var t=require("../../types");var isCreateClassCallExpression=t.buildMatchMemberExpression("React.createClass");exports.isCreateClass=function(node){if(!node||!t.isCallExpression(node))return false;if(!isCreateClassCallExpression(node.callee))return false;var args=node.arguments;if(args.length!==1)return false;var first=args[0];if(!t.isObjectExpression(first))return false;return true};exports.isReactComponent=t.buildMatchMemberExpression("React.Component")},{"../../types":102}],35:[function(require,module,exports){"use strict";var traverse=require("../../traverse");var t=require("../../types");var visitor={enter:function(node,parent,scope,context){if(t.isFunction(node))context.skip();if(t.isAwaitExpression(node)){node.type="YieldExpression";if(node.all){node.all=false;node.argument=t.callExpression(t.memberExpression(t.identifier("Promise"),t.identifier("all")),[node.argument])}}}};module.exports=function(node,callId,scope){node.async=false;node.generator=true;traverse(node,visitor,scope);var call=t.callExpression(callId,[node]);var id=node.id;delete node.id;if(t.isFunctionDeclaration(node)){var declar=t.variableDeclaration("let",[t.variableDeclarator(id,call)]);declar._blockHoist=true;return declar}else{return call}}},{"../../traverse":98,"../../types":102}],36:[function(require,module,exports){"use strict";module.exports=ReplaceSupers;var traverse=require("../../traverse");var t=require("../../types");function ReplaceSupers(opts){this.topLevelThisReference=null;this.methodNode=opts.methodNode;this.className=opts.className;this.superName=opts.superName;this.isLoose=opts.isLoose;this.scope=opts.scope;this.file=opts.file}ReplaceSupers.prototype.setSuperProperty=function(property,value,isStatic,isComputed,thisExpression){return t.callExpression(this.file.addHelper("set"),[t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getPrototypeOf")),[isStatic?this.className:t.memberExpression(this.className,t.identifier("prototype"))]),isComputed?property:t.literal(property.name),value,thisExpression])};ReplaceSupers.prototype.superProperty=function(property,isStatic,isComputed,thisExpression){return t.callExpression(this.file.addHelper("get"),[t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getPrototypeOf")),[isStatic?this.className:t.memberExpression(this.className,t.identifier("prototype"))]),isComputed?property:t.literal(property.name),thisExpression])};ReplaceSupers.prototype.looseSuperProperty=function(methodNode,id,parent){var methodName=methodNode.key;var superName=this.superName||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){parent.arguments.unshift(t.thisExpression());if(methodName.name==="constructor"){return t.memberExpression(superName,t.identifier("call"))}else{id=superName;if(!methodNode.static){id=t.memberExpression(id,t.identifier("prototype"))}id=t.memberExpression(id,methodName,methodNode.computed);return t.memberExpression(id,t.identifier("call"))}}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superName,t.identifier("prototype"))}else{return superName}};ReplaceSupers.prototype.replace=function(){this.traverseLevel(this.methodNode.value,true)};var visitor={enter:function(node,parent,scope,context,state){var topLevel=state.topLevel;var self=state.self;if(t.isFunction(node)&&!t.isArrowFunctionExpression(node)){self.traverseLevel(node,false);return context.skip()}if(t.isProperty(node,{method:true})||t.isMethodDefinition(node)){return context.skip()}var getThisReference=topLevel?t.thisExpression:self.getThisReference;var callback=self.specHandle;if(self.isLoose)callback=self.looseHandle;return callback.call(self,getThisReference,node,parent)}};ReplaceSupers.prototype.traverseLevel=function(node,topLevel){var state={self:this,topLevel:topLevel};traverse(node,visitor,this.scope,state)};ReplaceSupers.prototype.getThisReference=function(){if(this.topLevelThisReference){return this.topLevelThisReference}else{var ref=this.topLevelThisReference=this.file.generateUidIdentifier("this");this.methodNode.value.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(this.topLevelThisReference,t.thisExpression())]));return ref}};ReplaceSupers.prototype.looseHandle=function(getThisReference,node,parent){if(t.isIdentifier(node,{name:"super"})){return this.looseSuperProperty(this.methodNode,node,parent)}else if(t.isCallExpression(node)){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;t.appendToMemberExpression(callee,t.identifier("call"));node.arguments.unshift(getThisReference())}};ReplaceSupers.prototype.specHandle=function(getThisReference,node,parent){var methodNode=this.methodNode;var property;var computed;var args;var thisReference;if(t.isIdentifier(node,{name:"super"})){if(!(t.isMemberExpression(parent)&&!parent.computed&&parent.property===node)){throw this.file.errorWithNode(node,"illegal use of bare super")}}else if(t.isCallExpression(node)){var callee=node.callee;if(t.isIdentifier(callee,{name:"super"})){property=methodNode.key;computed=methodNode.computed;args=node.arguments;if(methodNode.key.name!=="constructor"){var methodName=methodNode.key.name||"METHOD_NAME";throw this.file.errorWithNode(node,"Direct super call is illegal in non-constructor, use super."+methodName+"() instead")}}else{if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;property=callee.property;computed=callee.computed;args=node.arguments}}else if(t.isMemberExpression(node)){if(!t.isIdentifier(node.object,{name:"super"}))return;property=node.property;computed=node.computed}else if(t.isAssignmentExpression(node)){if(!t.isIdentifier(node.left.object,{name:"super"}))return;if(methodNode.kind!=="set")return;thisReference=getThisReference();return this.setSuperProperty(node.left.property,node.right,methodNode.static,node.left.computed,thisReference)}if(!property)return;thisReference=getThisReference();var superProperty=this.superProperty(property,methodNode.static,computed,thisReference);if(args){if(args.length===1&&t.isSpreadElement(args[0])){return t.callExpression(t.memberExpression(superProperty,t.identifier("apply")),[thisReference,args[0].argument])}else{return t.callExpression(t.memberExpression(superProperty,t.identifier("call")),[thisReference].concat(args))}}else{return superProperty}}},{"../../traverse":98,"../../types":102}],37:[function(require,module,exports){"use strict";var t=require("../../types");exports.has=function(node){var first=node.body[0];return t.isExpressionStatement(first)&&t.isLiteral(first.expression,{value:"use strict"})};exports.wrap=function(node,callback){var useStrictNode;if(exports.has(node)){useStrictNode=node.body.shift()}callback();if(useStrictNode){node.body.unshift(useStrictNode)}}},{"../../types":102}],38:[function(require,module,exports){"use strict";module.exports=transform;var Transformer=require("./transformer");var object=require("../helpers/object");var File=require("../file");var util=require("../util");var each=require("lodash/collection/each");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform.fromAst=function(ast,code,opts){ast=util.normaliseAst(ast);var file=new File(opts);file.addCode(code);file.transform(ast);return file.generate()};transform._ensureTransformerNames=function(type,rawKeys){var keys=[];for(var i=0;i<rawKeys.length;i++){var key=rawKeys[i];var deprecatedKey=transform.deprecatedTransformerMap[key];if(deprecatedKey){console.error("The transformer "+key+" has been renamed to "+deprecatedKey+" in v3.0.0 - backwards compatibilty will be removed 4.0.0");rawKeys.push(deprecatedKey)}else if(transform.transformers[key]){keys.push(key)}else if(transform.namespaces[key]){keys=keys.concat(transform.namespaces[key])}else{throw new ReferenceError("Unknown transformer "+key+" specified in "+type+" - "+"transformer key names have been changed in 3.0.0 see "+"the changelog for more info "+"https://github.com/6to5/6to5/blob/master/CHANGELOG.md#300")}}return keys};transform.transformers=object();transform.namespaces=object();transform.deprecatedTransformerMap=require("./transformers/deprecated");transform.moduleFormatters=require("./modules");var rawTransformers=require("./transformers");each(rawTransformers,function(transformer,key){var namespace=key.split(".")[0];transform.namespaces[namespace]=transform.namespaces[namespace]||[];transform.namespaces[namespace].push(key);transform.transformers[key]=new Transformer(key,transformer)})},{"../file":2,"../helpers/object":26,"../util":105,"./modules":46,"./transformer":51,"./transformers":73,"./transformers/deprecated":52,"lodash/collection/each":177}],39:[function(require,module,exports){"use strict";module.exports=DefaultFormatter;var traverse=require("../../traverse");var object=require("../../helpers/object");var util=require("../../util");var t=require("../../types");var extend=require("lodash/object/extend");function DefaultFormatter(file){this.file=file;this.ids=object();this.hasNonDefaultExports=false;this.hasLocalExports=false;this.hasLocalImports=false;this.localImportOccurences=object();this.localExports=object();this.localImports=object();this.getLocalExports();this.getLocalImports();this.remapAssignments()}DefaultFormatter.prototype.doDefaultExportInterop=function(node){return node.default&&!this.noInteropRequire&&!this.hasNonDefaultExports};DefaultFormatter.prototype.bumpImportOccurences=function(node){var source=node.source.value;var occurs=this.localImportOccurences;occurs[source]=occurs[source]||0;occurs[source]+=node.specifiers.length};var exportsVisitor={enter:function(node,parent,scope,context,formatter){var declar=node&&node.declaration;if(t.isExportDeclaration(node)){formatter.hasLocalImports=true;if(declar&&t.isStatement(declar)){extend(formatter.localExports,t.getDeclarations(declar))}if(!node.default){formatter.hasNonDefaultExports=true}if(node.source){formatter.bumpImportOccurences(node)}}}};DefaultFormatter.prototype.getLocalExports=function(){traverse(this.file.ast,exportsVisitor,this.file.scope,this)};var importsVisitor={enter:function(node,parent,scope,context,formatter){if(t.isImportDeclaration(node)){formatter.hasLocalImports=true;extend(formatter.localImports,t.getDeclarations(node));formatter.bumpImportOccurences(node)}}};DefaultFormatter.prototype.getLocalImports=function(){traverse(this.file.ast,importsVisitor,this.file.scope,this)};var remapVisitor={enter:function(node,parent,scope,context,formatter){if(t.isUpdateExpression(node)&&formatter.isLocalReference(node.argument,scope)){context.skip();var assign=t.assignmentExpression(node.operator[0]+"=",node.argument,t.literal(1));var remapped=formatter.remapExportAssignment(assign);if(t.isExpressionStatement(parent)||node.prefix){return remapped}var nodes=[];nodes.push(remapped); var operator;if(node.operator==="--"){operator="+"}else{operator="-"}nodes.push(t.binaryExpression(operator,node.argument,t.literal(1)));return t.sequenceExpression(nodes)}if(t.isAssignmentExpression(node)&&formatter.isLocalReference(node.left,scope)){context.skip();return formatter.remapExportAssignment(node)}}};DefaultFormatter.prototype.remapAssignments=function(){if(this.hasLocalImports){traverse(this.file.ast,remapVisitor,this.file.scope,this)}};DefaultFormatter.prototype.isLocalReference=function(node){var localImports=this.localImports;return t.isIdentifier(node)&&localImports[node.name]&&localImports[node.name]!==node};DefaultFormatter.prototype.checkLocalReference=function(node){var file=this.file;if(this.isLocalReference(node)){throw file.errorWithNode(node,"Illegal assignment of module import")}};DefaultFormatter.prototype.remapExportAssignment=function(node){return t.assignmentExpression("=",node.left,t.assignmentExpression(node.operator,t.memberExpression(t.identifier("exports"),node.left),node.right))};DefaultFormatter.prototype.isLocalReference=function(node,scope){var localExports=this.localExports;var name=node.name;return t.isIdentifier(node)&&localExports[name]&&localExports[name]===scope.get(name,true)};DefaultFormatter.prototype.getModuleName=function(){var opts=this.file.opts;var filenameRelative=opts.filenameRelative;var moduleName="";if(opts.moduleRoot){moduleName=opts.moduleRoot+"/"}if(!opts.filenameRelative){return moduleName+opts.filename.replace(/^\//,"")}if(opts.sourceRoot){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}if(!opts.keepModuleIdExtensions){filenameRelative=filenameRelative.replace(/\.(.*?)$/,"")}moduleName+=filenameRelative;moduleName=moduleName.replace(/\\/g,"/");return moduleName};DefaultFormatter.prototype._pushStatement=function(ref,nodes){if(t.isClass(ref)||t.isFunction(ref)){if(ref.id){nodes.push(t.toStatement(ref));ref=ref.id}}return ref};DefaultFormatter.prototype._hoistExport=function(declar,assign,priority){if(t.isFunctionDeclaration(declar)){assign._blockHoist=priority||2}return assign};DefaultFormatter.prototype.getExternalReference=function(node,nodes){var ids=this.ids;var id=node.source.value;if(ids[id]){return ids[id]}else{return this.ids[id]=this._getExternalReference(node,nodes)}};DefaultFormatter.prototype.exportSpecifier=function(specifier,node,nodes){var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){var ref=this.getExternalReference(node,nodes);if(t.isExportBatchSpecifier(specifier)){nodes.push(this.buildExportsWildcard(ref,node))}else{if(t.isSpecifierDefault(specifier)&&!this.noInteropRequire){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}else{ref=t.memberExpression(ref,t.getSpecifierId(specifier))}nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier),ref,node))}}else{nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier),specifier.id,node))}};DefaultFormatter.prototype.buildExportsWildcard=function(objectIdentifier){return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"),[t.identifier("exports"),t.callExpression(this.file.addHelper("interop-require-wildcard"),[objectIdentifier])]))};DefaultFormatter.prototype.buildExportsAssignment=function(id,init){return util.template("exports-assign",{VALUE:init,KEY:id},true)};DefaultFormatter.prototype.exportDeclaration=function(node,nodes){var declar=node.declaration;var id=declar.id;if(node.default){id=t.identifier("default")}var assign;if(t.isVariableDeclaration(declar)){for(var i=0;i<declar.declarations.length;i++){var decl=declar.declarations[i];decl.init=this.buildExportsAssignment(decl.id,decl.init,node).expression;var newDeclar=t.variableDeclaration(declar.kind,[decl]);if(i===0)t.inherits(newDeclar,declar);nodes.push(newDeclar)}}else{var ref=declar;if(t.isFunctionDeclaration(declar)||t.isClassDeclaration(declar)){ref=declar.id;nodes.push(declar)}assign=this.buildExportsAssignment(id,ref,node);nodes.push(assign);this._hoistExport(declar,assign)}}},{"../../helpers/object":26,"../../traverse":98,"../../types":102,"../../util":105,"lodash/object/extend":258}],40:[function(require,module,exports){"use strict";var util=require("../../util");module.exports=function(Parent){var Constructor=function(){this.noInteropRequire=true;Parent.apply(this,arguments)};util.inherits(Constructor,Parent);return Constructor}},{"../../util":105}],41:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./amd"))},{"./_strict":40,"./amd":42}],42:[function(require,module,exports){"use strict";module.exports=AMDFormatter;var DefaultFormatter=require("./_default");var CommonFormatter=require("./common");var util=require("../../util");var t=require("../../types");var contains=require("lodash/collection/contains");var values=require("lodash/object/values");function AMDFormatter(){CommonFormatter.apply(this,arguments)}util.inherits(AMDFormatter,DefaultFormatter);AMDFormatter.prototype.init=CommonFormatter.prototype.init;AMDFormatter.prototype.buildDependencyLiterals=function(){var names=[];for(var name in this.ids){names.push(t.literal(name))}return names};AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")];if(this.passModuleArg)names.push(t.literal("module"));names=names.concat(this.buildDependencyLiterals());names=t.arrayExpression(names);var params=values(this.ids);if(this.passModuleArg)params.unshift(t.identifier("module"));params.unshift(t.identifier("exports"));var container=t.functionExpression(null,params,t.blockStatement(body));var defineArgs=[names,container];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var call=t.callExpression(t.identifier("define"),defineArgs);program.body=[t.expressionStatement(call)]};AMDFormatter.prototype.getModuleName=function(){if(this.file.opts.moduleIds){return DefaultFormatter.prototype.getModuleName.apply(this,arguments)}else{return null}};AMDFormatter.prototype._getExternalReference=function(node){return this.file.generateUidIdentifier(node.source.value)};AMDFormatter.prototype.importDeclaration=function(node){this.getExternalReference(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var ref=this.getExternalReference(node);if(contains(this.file.dynamicImported,node)){this.ids[node.source.value]=ref}else if(t.isImportBatchSpecifier(specifier)){}else if(t.isSpecifierDefault(specifier)&&!this.noInteropRequire){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}else{ref=t.memberExpression(ref,t.getSpecifierId(specifier),false)}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,ref)]))};AMDFormatter.prototype.exportDeclaration=function(node){if(this.doDefaultExportInterop(node)){this.passModuleArg=true}CommonFormatter.prototype.exportDeclaration.apply(this,arguments)}},{"../../types":102,"../../util":105,"./_default":39,"./common":44,"lodash/collection/contains":176,"lodash/object/values":263}],43:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./common"))},{"./_strict":40,"./common":44}],44:[function(require,module,exports){"use strict";module.exports=CommonJSFormatter;var DefaultFormatter=require("./_default");var contains=require("lodash/collection/contains");var util=require("../../util");var t=require("../../types");function CommonJSFormatter(){DefaultFormatter.apply(this,arguments)}util.inherits(CommonJSFormatter,DefaultFormatter);CommonJSFormatter.prototype.init=function(){if(this.hasNonDefaultExports){this.file.ast.program.body.push(util.template("exports-module-declaration",true))}};CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);var ref=this.getExternalReference(node,nodes);if(t.isSpecifierDefault(specifier)){if(!contains(this.file.dynamicImported,node)){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,ref)]))}else{if(specifier.type==="ImportBatchSpecifier"){nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.callExpression(this.file.addHelper("interop-require-wildcard"),[ref]))]))}else{nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.memberExpression(ref,t.getSpecifierId(specifier)))]))}}};CommonJSFormatter.prototype.importDeclaration=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source},true))};CommonJSFormatter.prototype.exportDeclaration=function(node,nodes){if(this.doDefaultExportInterop(node)){var declar=node.declaration;var assign=util.template("exports-default-assign",{VALUE:this._pushStatement(declar,nodes)},true);if(t.isFunctionDeclaration(declar)){assign._blockHoist=3}nodes.push(assign);return}DefaultFormatter.prototype.exportDeclaration.apply(this,arguments)};CommonJSFormatter.prototype._getExternalReference=function(node,nodes){var source=node.source.value;var call=t.callExpression(t.identifier("require"),[node.source]);if(this.localImportOccurences[source]>1){var uid=this.file.generateUidIdentifier(source);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(uid,call)]));return uid}else{return call}}},{"../../types":102,"../../util":105,"./_default":39,"lodash/collection/contains":176}],45:[function(require,module,exports){"use strict";module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.exportDeclaration=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.importDeclaration=IgnoreFormatter.prototype.importSpecifier=IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":102}],46:[function(require,module,exports){module.exports={commonStrict:require("./common-strict"),amdStrict:require("./amd-strict"),umdStrict:require("./umd-strict"),common:require("./common"),system:require("./system"),ignore:require("./ignore"),amd:require("./amd"),umd:require("./umd")}},{"./amd":42,"./amd-strict":41,"./common":44,"./common-strict":43,"./ignore":45,"./system":47,"./umd":49,"./umd-strict":48}],47:[function(require,module,exports){"use strict";module.exports=SystemFormatter;var DefaultFormatter=require("./_default");var AMDFormatter=require("./amd");var useStrict=require("../helpers/use-strict");var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var last=require("lodash/array/last");var each=require("lodash/collection/each");var map=require("lodash/collection/map");function SystemFormatter(file){this.exportIdentifier=file.generateUidIdentifier("export");this.noInteropRequire=true;DefaultFormatter.apply(this,arguments)}util.inherits(SystemFormatter,AMDFormatter);SystemFormatter.prototype.init=function(){};SystemFormatter.prototype._addImportSource=function(node,exportNode){node._importSource=exportNode.source&&exportNode.source.value;return node};SystemFormatter.prototype.buildExportsWildcard=function(objectIdentifier,node){var leftIdentifier=this.file.generateUidIdentifier("key");var valIdentifier=t.memberExpression(objectIdentifier,leftIdentifier,true);var left=t.variableDeclaration("var",[t.variableDeclarator(leftIdentifier)]);var right=objectIdentifier;var block=t.blockStatement([t.expressionStatement(this.buildExportCall(leftIdentifier,valIdentifier))]);return this._addImportSource(t.forInStatement(left,right,block),node)};SystemFormatter.prototype.buildExportsAssignment=function(id,init,node){var call=this.buildExportCall(t.literal(id.name),init,true);return this._addImportSource(call,node)};SystemFormatter.prototype.remapExportAssignment=function(node){return this.buildExportCall(t.literal(node.left.name),node)};SystemFormatter.prototype.buildExportCall=function(id,init,isStatement){var call=t.callExpression(this.exportIdentifier,[id,init]);if(isStatement){return t.expressionStatement(call)}else{return call}};SystemFormatter.prototype.importSpecifier=function(specifier,node,nodes){AMDFormatter.prototype.importSpecifier.apply(this,arguments);this._addImportSource(last(nodes),node)};var runnerSettersVisitor={enter:function(node,parent,scope,context,state){if(node._importSource===state.source){if(t.isVariableDeclaration(node)){each(node.declarations,function(declar){state.hoistDeclarators.push(t.variableDeclarator(declar.id));state.nodes.push(t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init)))})}else{state.nodes.push(node)}context.remove()}}};SystemFormatter.prototype.buildRunnerSetters=function(block,hoistDeclarators){var scope=this.file.scope;return t.arrayExpression(map(this.ids,function(uid,source){var state={source:source,nodes:[],hoistDeclarators:hoistDeclarators};traverse(block,runnerSettersVisitor,scope,state);return t.functionExpression(null,[uid],t.blockStatement(state.nodes))}))};var hoistVariablesVisitor={enter:function(node,parent,scope,context,hoistDeclarators){if(t.isFunction(node)){return context.skip()}if(t.isVariableDeclaration(node)){if(node.kind!=="var"&&!t.isProgram(parent)){return}if(node._blockHoist)return;var nodes=[];for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];hoistDeclarators.push(t.variableDeclarator(declar.id));if(declar.init){var assign=t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init));nodes.push(assign)}}if(t.isFor(parent)){if(parent.left===node){return node.declarations[0].id}if(parent.init===node){return t.toSequenceExpression(nodes,scope)}}return nodes}}};var hoistFunctionsVisitor={enter:function(node,parent,scope,context,handlerBody){if(t.isFunction(node))context.skip();if(t.isFunctionDeclaration(node)||node._blockHoist){handlerBody.push(node);context.remove()}}};SystemFormatter.prototype.transform=function(ast){var program=ast.program;var hoistDeclarators=[];var moduleName=this.getModuleName();var moduleNameLiteral=t.literal(moduleName);var block=t.blockStatement(program.body);var runner=util.template("system",{MODULE_NAME:moduleNameLiteral,MODULE_DEPENDENCIES:t.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(block,hoistDeclarators),EXECUTE:t.functionExpression(null,[],block)},true);var handlerBody=runner.expression.arguments[2].body.body;if(!moduleName)runner.expression.arguments.shift();var returnStatement=handlerBody.pop();traverse(block,hoistVariablesVisitor,this.file.scope,hoistDeclarators);if(hoistDeclarators.length){var hoistDeclar=t.variableDeclaration("var",hoistDeclarators);hoistDeclar._blockHoist=true;handlerBody.unshift(hoistDeclar)}traverse(block,hoistFunctionsVisitor,this.file.scope,handlerBody);handlerBody.push(returnStatement);if(useStrict.has(block)){handlerBody.unshift(block.body.shift())}program.body=[runner]}},{"../../traverse":98,"../../types":102,"../../util":105,"../helpers/use-strict":37,"./_default":39,"./amd":42,"lodash/array/last":173,"lodash/collection/each":177,"lodash/collection/map":181}],48:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./umd"))},{"./_strict":40,"./umd":49}],49:[function(require,module,exports){"use strict";module.exports=UMDFormatter;var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var values=require("lodash/object/values");function UMDFormatter(){AMDFormatter.apply(this,arguments)}util.inherits(UMDFormatter,AMDFormatter);UMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[];for(var name in this.ids){names.push(t.literal(name))}var ids=values(this.ids);var args=[t.identifier("exports")];if(this.passModuleArg)args.push(t.identifier("module"));args=args.concat(ids);var factory=t.functionExpression(null,args,t.blockStatement(body));var defineArgs=[t.literal("exports")];if(this.passModuleArg)defineArgs.push(t.literal("module"));defineArgs=defineArgs.concat(names);defineArgs=[t.arrayExpression(defineArgs)];var testExports=util.template("test-exports");var testModule=util.template("test-module");var commonTests=this.passModuleArg?t.logicalExpression("&&",testExports,testModule):testExports;var commonArgs=[t.identifier("exports")];if(this.passModuleArg)commonArgs.push(t.identifier("module"));commonArgs=commonArgs.concat(names.map(function(name){return t.callExpression(t.identifier("require"),[name])}));var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var runner=util.template("umd-runner-body",{AMD_ARGUMENTS:defineArgs,COMMON_TEST:commonTests,COMMON_ARGUMENTS:commonArgs});var call=t.callExpression(runner,[factory]);program.body=[t.expressionStatement(call)]}},{"../../types":102,"../../util":105,"./amd":42,"lodash/object/values":263}],50:[function(require,module,exports){module.exports=TransformerPass;var traverse=require("../traverse");var util=require("../util");var contains=require("lodash/collection/contains");function TransformerPass(file,transformer){this.transformer=transformer;this.handlers=transformer.handlers;this.file=file}TransformerPass.prototype.astRun=function(key){var handlers=this.handlers;var file=this.file;if(handlers.ast&&handlers.ast[key]){handlers.ast[key](file.ast,file)}};TransformerPass.prototype.canRun=function(){var transformer=this.transformer;var opts=this.file.opts;var key=transformer.key;if(key[0]==="_")return true;var blacklist=opts.blacklist;if(blacklist.length&&contains(blacklist,key))return false;var whitelist=opts.whitelist;if(whitelist.length&&!contains(whitelist,key))return false;if(transformer.optional&&!contains(opts.optional,key))return false;if(transformer.experimental&&!opts.experimental)return false;if(transformer.playground&&!opts.playground)return false;return true};var transformVisitor={enter:function(node,parent,scope,context,state){var fns=state.handlers[node.type];if(!fns)return;return fns.enter(node,parent,scope,context,state.file,state.pass)},exit:function(node,parent,scope,context,state){var fns=state.handlers[node.type];if(!fns)return;return fns.exit(node,parent,scope,context,state.file,state.pass)}};TransformerPass.prototype.transform=function(){var file=this.file;util.debug(file.opts.filename+": Running transformer "+this.transformer.key);this.astRun("before");var state={file:file,handlers:this.handlers,pass:this};traverse(file.ast,transformVisitor,file.scope,state);this.astRun("after")}},{"../traverse":98,"../util":105,"lodash/collection/contains":176}],51:[function(require,module,exports){"use strict";module.exports=Transformer;var TransformerPass=require("./transformer-pass");var isFunction=require("lodash/lang/isFunction");var traverse=require("../traverse");var isObject=require("lodash/lang/isObject");var each=require("lodash/collection/each");function Transformer(key,transformer,opts){this.manipulateOptions=transformer.manipulateOptions;this.experimental=!!transformer.experimental;this.playground=!!transformer.playground;this.secondPass=!!transformer.secondPass;this.optional=!!transformer.optional;this.handlers=this.normalise(transformer);this.opts=opts||{};this.key=key}Transformer.prototype.normalise=function(transformer){var self=this;if(isFunction(transformer)){transformer={ast:transformer}}traverse.explode(transformer);each(transformer,function(fns,type){if(type[0]==="_"){self[type]=fns;return}if(isFunction(fns))fns={enter:fns};if(!isObject(fns))return;if(!fns.enter)fns.enter=function(){};if(!fns.exit)fns.exit=function(){};transformer[type]=fns});return transformer};Transformer.prototype.buildPass=function(file){return new TransformerPass(file,this)}},{"../traverse":98,"./transformer-pass":50,"lodash/collection/each":177,"lodash/lang/isFunction":247,"lodash/lang/isObject":250}],52:[function(require,module,exports){module.exports={specNoForInOfAssignment:"validation.noForInOfAssignment",specSetters:"validation.setters",specBlockScopedFunctions:"spec.blockScopedFunctions",malletOperator:"playground.malletOperator",methodBinding:"playground.methodBinding",memoizationOperator:"playground.memoizationOperator",objectGetterMemoization:"playground.objectGetterMemoization",modules:"es6.modules",propertyNameShorthand:"es6.properties.shorthand",arrayComprehension:"es7.comprehensions",generatorComprehension:"es7.comprehensions",arrowFunctions:"es6.arrowFunctions",classes:"es6.classes",objectSpread:"es7.objectSpread",exponentiationOperator:"es7.exponentiationOperator",spread:"es6.spread",templateLiterals:"es6.templateLiterals",propertyMethodAssignment:"es6.properties.shorthand",computedPropertyNames:"es6.properties.computed",defaultParameters:"es6.parameters.default",restParameters:"es6.parameters.rest",destructuring:"es6.destructuring",forOf:"es6.forOf",unicodeRegex:"es6.unicodeRegex",abstractReferences:"es7.abstractReferences",constants:"es6.constants",letScoping:"es6.letScoping",blockScopingTDZ:"es6.blockScopingTDZ",generators:"regenerator",protoToAssign:"spec.protoToAssign",typeofSymbol:"spec.typeofSymbol",coreAliasing:"selfContained",undefinedToVoid:"spec.undefinedToVoid",undeclaredVariableCheck:"validation.undeclaredVariableCheck",specPropertyLiterals:"minification.propertyLiterals",specMemberExpressionLiterals:"minification.memberExpressionLiterals"}},{}],53:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.ObjectExpression=function(node){var mutatorMap={};var hasAny=false;node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){hasAny=true;util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.computed,prop.value);return false}else{return true}});if(!hasAny)return;return t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("defineProperties")),[node,util.buildDefineProperties(mutatorMap)])}},{"../../../types":102,"../../../util":105}],54:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction="arrow";node.expression=false;node.type="FunctionExpression";return node}},{"../../../types":102}],55:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var visitor={enter:function(node,parent,scope,context,state){if(!t.isReferencedIdentifier(node,parent))return;var declared=state.letRefs[node.name];if(!declared)return;if(scope.get(node.name,true)!==declared)return;var declaredLoc=declared.loc;var referenceLoc=node.loc;if(!declaredLoc||!referenceLoc)return;var before=referenceLoc.start.line<declaredLoc.start.line;if(referenceLoc.start.line===declaredLoc.start.line){before=referenceLoc.start.col<declaredLoc.start.col}if(before){throw state.file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}}};exports.optional=true;exports.Loop=exports.Program=exports.BlockStatement=function(node,parent,scope,context,file){var letRefs=node._letReferences;if(!letRefs)return;var state={letRefs:letRefs,file:file};traverse(node,visitor,scope,state)}},{"../../../traverse":98,"../../../types":102}],56:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var object=require("../../../helpers/object");var util=require("../../../util");var t=require("../../../types");var values=require("lodash/object/values");var extend=require("lodash/object/extend");var isLet=function(node,parent){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;if(!t.isFor(parent)||t.isFor(parent)&&parent.left!==node){for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];declar.init=declar.init||t.identifier("undefined")}}node._let=true;node.kind="var";return true};var isVar=function(node,parent){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node,parent)};var standardiseLets=function(declars){for(var i=0;i<declars.length;i++){delete declars[i]._let}};exports.VariableDeclaration=function(node,parent){isLet(node,parent)};exports.Loop=function(node,parent,scope,context,file){var init=node.left||node.init;if(isLet(init,node)){t.ensureBlock(node);node.body._letDeclarators=[init]}var letScoping=new LetScoping(node,node.body,parent,scope,file);letScoping.run()};exports.Program=exports.BlockStatement=function(block,parent,scope,context,file){if(!t.isLoop(parent)){var letScoping=new LetScoping(false,block,parent,scope,file);letScoping.run()}};function LetScoping(loopParent,block,parent,scope,file){this.loopParent=loopParent;this.parent=parent;this.scope=scope;this.block=block;this.file=file;this.outsideLetReferences=object();this.hasLetReferences=false;this.letReferences=block._letReferences=object();this.body=[]}LetScoping.prototype.run=function(){var block=this.block;if(block._letDone)return;block._letDone=true;var needsClosure=this.getLetReferences();if(t.isFunction(this.parent)||t.isProgram(this.block))return;if(!this.hasLetReferences)return;if(needsClosure){this.needsClosure()}else{this.remap()}};function replace(node,parent,scope,context,remaps){if(!t.isReferencedIdentifier(node,parent))return;var remap=remaps[node.name];if(!remap)return;var own=scope.get(node.name,true);if(own===remap.node){node.name=remap.uid}else{if(context)context.skip()}}var replaceVisitor={enter:replace};function traverseReplace(node,parent,scope,remaps){replace(node,parent,scope,null,remaps);traverse(node,replaceVisitor,scope,remaps)}LetScoping.prototype.remap=function(){var hasRemaps=false;var letRefs=this.letReferences;var scope=this.scope;var remaps=object();for(var key in letRefs){var ref=letRefs[key];if(scope.parentHas(key)){var uid=scope.generateUidIdentifier(ref.name).name;ref.name=uid;hasRemaps=true;remaps[key]=remaps[uid]={node:ref,uid:uid}}}if(!hasRemaps)return;var loopParent=this.loopParent;if(loopParent){traverseReplace(loopParent.right,loopParent,scope,remaps);traverseReplace(loopParent.test,loopParent,scope,remaps);traverseReplace(loopParent.update,loopParent,scope,remaps)}traverse(this.block,replaceVisitor,scope,remaps)};LetScoping.prototype.needsClosure=function(){var block=this.block;this.has=this.checkLoop();this.hoistVarDeclarations();var params=values(this.outsideLetReferences);var fn=t.functionExpression(null,params,t.blockStatement(block.body));fn._aliasFunction=true;block.body=this.body;var call=t.callExpression(fn,params);var ret=this.scope.generateUidIdentifier("ret");var hasYield=traverse.hasType(fn.body,this.scope,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}var hasAsync=traverse.hasType(fn.body,this.scope,"AwaitExpression",t.FUNCTION_TYPES);if(hasAsync){fn.async=true;call=t.awaitExpression(call,true)}this.build(ret,call)};var letReferenceFunctionVisitor={enter:function(node,parent,scope,context,state){if(!t.isReferencedIdentifier(node,parent))return;if(scope.hasOwn(node.name,true))return;if(!state.letReferences[node.name])return;state.closurify=true}};var letReferenceBlockVisitor={enter:function(node,parent,scope,context,state){if(t.isFunction(node)){traverse(node,letReferenceFunctionVisitor,scope,state);return context.skip()}}};LetScoping.prototype.getLetReferences=function(){var block=this.block;var declarators=block._letDeclarators||[];var declar;for(var i=0;i<declarators.length;i++){declar=declarators[i];extend(this.outsideLetReferences,t.getDeclarations(declar))}if(block.body){for(i=0;i<block.body.length;i++){declar=block.body[i];if(isLet(declar,block)){declarators=declarators.concat(declar.declarations)}}}for(i=0;i<declarators.length;i++){declar=declarators[i];var keys=t.getDeclarations(declar);extend(this.letReferences,keys);this.hasLetReferences=true}if(!this.hasLetReferences)return;standardiseLets(declarators);var state={letReferences:this.letReferences,closurify:false};traverse(this.block,letReferenceBlockVisitor,this.scope,state);return state.closurify};var loopNodeTo=function(node){if(t.isBreakStatement(node)){return"break"}else if(t.isContinueStatement(node)){return"continue"}};var loopVisitor={enter:function(node,parent,scope,context,state){var replace;if(t.isLoop(node)){state.ignoreLabeless=true;traverse(node,loopVisitor,scope,state);state.ignoreLabeless=false}if(t.isFunction(node)||t.isLoop(node)){return context.skip()}var loopText=loopNodeTo(node);if(loopText){if(node.label){if(state.innerLabels.indexOf(node.label.name)>=0){return}loopText=loopText+"|"+node.label.name}else{if(state.ignoreLabeless)return;if(t.isBreakStatement(node)&&t.isSwitchCase(parent))return}state.hasBreakContinue=true;state.map[loopText]=node;replace=t.literal(loopText)}if(t.isReturnStatement(node)){state.hasReturn=true;replace=t.objectExpression([t.property("init",t.identifier("v"),node.argument||t.identifier("undefined"))])}if(replace){replace=t.returnStatement(replace);return t.inherits(replace,node)}}};var loopLabelVisitor={enter:function(node,parent,scope,context,state){if(t.isLabeledStatement(node)){state.innerLabels.push(node.label.name)}}};LetScoping.prototype.checkLoop=function(){var state={hasBreakContinue:false,ignoreLabeless:false,innerLabels:[],hasReturn:false,isLoop:!!this.loopParent,map:{}};traverse(this.block,loopLabelVisitor,this.scope,state);traverse(this.block,loopVisitor,this.scope,state);return state};var hoistVarDeclarationsVisitor={enter:function(node,parent,scope,context,self){if(t.isForStatement(node)){if(isVar(node.init,node)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left,node)){node.left=node.left.declarations[0].id}}else if(isVar(node,parent)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return context.skip()}}};LetScoping.prototype.hoistVarDeclarations=function(){traverse(this.block,hoistVarDeclarationsVisitor,this.scope,this)};LetScoping.prototype.pushDeclar=function(node){this.body.push(t.variableDeclaration(node.kind,node.declarations.map(function(declar){return t.variableDeclarator(declar.id)})));var replace=[];for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];if(!declar.init)continue;var expr=t.assignmentExpression("=",declar.id,declar.init);replace.push(t.inherits(expr,declar))}return replace};LetScoping.prototype.build=function(ret,call){var has=this.has;if(has.hasReturn||has.hasBreakContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};LetScoping.prototype.buildHas=function(ret,call){var body=this.body;body.push(t.variableDeclaration("var",[t.variableDeclarator(ret,call)]));var loopParent=this.loopParent;var retCheck;var has=this.has;var cases=[];if(has.hasReturn){retCheck=util.template("let-scoping-return",{RETURN:ret})}if(has.hasBreakContinue){if(!loopParent){throw new Error("Has no loop parent but we're trying to reassign breaks "+"and continues, something is going wrong here.")}for(var key in has.map){cases.push(t.switchCase(t.literal(key),[has.map[key]]))}if(has.hasReturn){cases.push(t.switchCase(null,[retCheck]))}if(cases.length===1){var single=cases[0];body.push(t.ifStatement(t.binaryExpression("===",ret,single.test),single.consequent[0]))}else{body.push(t.switchStatement(ret,cases))}}else{if(has.hasReturn)body.push(retCheck)}}},{"../../../helpers/object":26,"../../../traverse":98,"../../../types":102,"../../../util":105,"lodash/object/extend":258,"lodash/object/values":263}],57:[function(require,module,exports){"use strict";var ReplaceSupers=require("../../helpers/replace-supers");var nameMethod=require("../../helpers/name-method");var util=require("../../../util");var t=require("../../../types");exports.ClassDeclaration=function(node,parent,scope,context,file){return new Class(node,file,scope,true).run()};exports.ClassExpression=function(node,parent,scope,context,file){if(!node.id){if(t.isProperty(parent)&&parent.value===node&&!parent.computed&&t.isIdentifier(parent.key)){node.id=parent.key }if(t.isVariableDeclarator(parent)&&t.isIdentifier(parent.id)){node.id=parent.id}}return new Class(node,file,scope,false).run()};function Class(node,file,scope,isStatement){this.isStatement=isStatement;this.scope=scope;this.node=node;this.file=file;this.hasInstanceMutators=false;this.hasStaticMutators=false;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||scope.generateUidIdentifier("class");this.superName=node.superClass;this.isLoose=file.isLoose("es6.classes")}Class.prototype.run=function(){var superName=this.superName;var className=this.className;var file=this.file;var body=this.body=[];var constructor;if(this.node.id){constructor=t.functionDeclaration(className,[],t.blockStatement([]));body.push(constructor)}else{constructor=t.functionExpression(null,[],t.blockStatement([]));body.push(t.variableDeclaration("var",[t.variableDeclarator(className,constructor)]))}this.constructor=constructor;var closureParams=[];var closureArgs=[];if(superName){closureArgs.push(superName);if(!t.isIdentifier(superName)){var superRef=this.scope.generateUidBasedOnNode(superName,this.file);superName=superRef}closureParams.push(superName);this.superName=superName;body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"),[className,superName])))}this.buildBody();t.inheritsComments(body[0],this.node);var init;if(body.length===1){init=t.toExpression(constructor)}else{body.push(t.returnStatement(className));init=t.callExpression(t.functionExpression(null,closureParams,t.blockStatement(body)),closureArgs)}if(this.isStatement){return t.variableDeclaration("let",[t.variableDeclarator(className,init)])}else{return init}};Class.prototype.buildBody=function(){var constructor=this.constructor;var className=this.className;var superName=this.superName;var classBody=this.node.body.body;var body=this.body;for(var i=0;i<classBody.length;i++){var node=classBody[i];if(t.isMethodDefinition(node)){var replaceSupers=new ReplaceSupers({methodNode:node,className:this.className,superName:this.superName,isLoose:this.isLoose,scope:this.scope,file:this.file});replaceSupers.replace();if(node.key.name==="constructor"){this.pushConstructor(node)}else{this.pushMethod(node)}}else if(t.isPrivateDeclaration(node)){this.closure=true;body.unshift(node)}}if(!this.hasConstructor&&superName&&!t.isFalsyExpression(superName)){var defaultConstructorTemplate="class-super-constructor-call";if(this.isLoose)defaultConstructorTemplate+="-loose";constructor.body.body.push(util.template(defaultConstructorTemplate,{CLASS_NAME:className,SUPER_NAME:this.superName},true))}var instanceProps;var staticProps;if(this.hasInstanceMutators){instanceProps=util.buildDefineProperties(this.instanceMutatorMap)}if(this.hasStaticMutators){staticProps=util.buildDefineProperties(this.staticMutatorMap)}if(instanceProps||staticProps){staticProps=staticProps||t.literal(null);var args=[className,staticProps];if(instanceProps)args.push(instanceProps);body.push(t.expressionStatement(t.callExpression(this.file.addHelper("prototype-properties"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var kind=node.kind;if(kind===""){nameMethod.property(node,this.file,this.scope);if(this.isLoose){var className=this.className;if(!node.static)className=t.memberExpression(className,t.identifier("prototype"));methodName=t.memberExpression(className,methodName,node.computed);var expr=t.expressionStatement(t.assignmentExpression("=",methodName,node.value));t.inheritsComments(expr,node);this.body.push(expr);return}kind="value"}var mutatorMap=this.instanceMutatorMap;if(node.static){this.hasStaticMutators=true;mutatorMap=this.staticMutatorMap}else{this.hasInstanceMutators=true}util.pushMutatorMap(mutatorMap,methodName,kind,node.computed,node);util.pushMutatorMap(mutatorMap,methodName,"enumerable",node.computed,false)};Class.prototype.pushConstructor=function(method){if(method.kind){throw this.file.errorWithNode(method,"illegal kind for constructor method")}var construct=this.constructor;var fn=method.value;this.hasConstructor=true;t.inherits(construct,fn);t.inheritsComments(construct,method);construct._ignoreUserWhitespace=true;construct.params=fn.params;construct.body=fn.body}},{"../../../types":102,"../../../util":105,"../../helpers/name-method":33,"../../helpers/replace-supers":36}],58:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var visitor={enter:function(node,parent,scope,context,state){if(t.isDeclaration(node)||t.isAssignmentExpression(node)){var ids=t.getDeclarations(node);for(var key in ids){var id=ids[key];var constant=state.constants[key];if(!constant)continue;if(id===constant)continue;throw state.file.errorWithNode(id,key+" is read-only")}}else if(t.isScope(node)){context.skip()}}};exports.Scope=function(node,parent,scope,context,file){traverse(node,visitor,scope,{constants:scope.getAllDeclarationsOfKind("const"),file:file})};exports.VariableDeclaration=function(node){if(node.kind==="const")node.kind="let"}},{"../../../traverse":98,"../../../types":102}],59:[function(require,module,exports){"use strict";var t=require("../../../types");var buildVariableAssign=function(opts,id,init){var op=opts.operator;if(t.isMemberExpression(id))op="=";var node;if(op){node=t.expressionStatement(t.assignmentExpression(op,id,init))}else{node=t.variableDeclaration(opts.kind,[t.variableDeclarator(id,init)])}node._blockHoist=opts.blockHoist;return node};var buildVariableDeclar=function(opts,id,init){var declar=t.variableDeclaration("var",[t.variableDeclarator(id,init)]);declar._blockHoist=opts.blockHoist;return declar};var push=function(opts,nodes,elem,parentId){if(t.isObjectPattern(elem)){pushObjectPattern(opts,nodes,elem,parentId)}else if(t.isArrayPattern(elem)){pushArrayPattern(opts,nodes,elem,parentId)}else if(t.isAssignmentPattern(elem)){pushAssignmentPattern(opts,nodes,elem,parentId)}else{nodes.push(buildVariableAssign(opts,elem,parentId))}};var pushAssignmentPattern=function(opts,nodes,pattern,parentId){var tempParentId=opts.scope.generateUidBasedOnNode(parentId,opts.file);var declar=t.variableDeclaration("var",[t.variableDeclarator(tempParentId,parentId)]);declar._blockHoist=opts.blockHoist;nodes.push(declar);nodes.push(buildVariableAssign(opts,pattern.left,t.conditionalExpression(t.binaryExpression("===",tempParentId,t.identifier("undefined")),pattern.right,tempParentId)))};var pushObjectPattern=function(opts,nodes,pattern,parentId){for(var i=0;i<pattern.properties.length;i++){var prop=pattern.properties[i];if(t.isSpreadProperty(prop)){var keys=[];for(var i2=0;i2<pattern.properties.length;i2++){var prop2=pattern.properties[i2];if(i2>=i)break;if(t.isSpreadProperty(prop2))continue;var key=prop2.key;if(t.isIdentifier(key)){key=t.literal(prop2.key.name)}keys.push(key)}keys=t.arrayExpression(keys);var value=t.callExpression(opts.file.addHelper("object-without-properties"),[parentId,keys]);nodes.push(buildVariableAssign(opts,prop.argument,value))}else{if(t.isLiteral(prop.key))prop.computed=true;var pattern2=prop.value;var patternId2=t.memberExpression(parentId,prop.key,prop.computed);if(t.isPattern(pattern2)){push(opts,nodes,pattern2,patternId2)}else{nodes.push(buildVariableAssign(opts,pattern2,patternId2))}}}};var pushArrayPattern=function(opts,nodes,pattern,parentId){if(!pattern.elements)return;var i;var hasRest=false;for(i=0;i<pattern.elements.length;i++){if(t.isRestElement(pattern.elements[i])){hasRest=true;break}}var toArray=opts.file.toArray(parentId,!hasRest&&pattern.elements.length);var _parentId=opts.scope.generateUidBasedOnNode(parentId,opts.file);nodes.push(buildVariableDeclar(opts,_parentId,toArray));parentId=_parentId;for(i=0;i<pattern.elements.length;i++){var elem=pattern.elements[i];if(!elem)continue;i=+i;var newPatternId;if(t.isRestElement(elem)){newPatternId=opts.file.toArray(parentId);if(i>0){newPatternId=t.callExpression(t.memberExpression(newPatternId,t.identifier("slice")),[t.literal(i)])}elem=elem.argument}else{newPatternId=t.memberExpression(parentId,t.literal(i),true)}push(opts,nodes,elem,newPatternId)}};var pushPattern=function(opts){var nodes=opts.nodes;var pattern=opts.pattern;var parentId=opts.id;var scope=opts.scope;if(!t.isArrayExpression(parentId)&&!t.isMemberExpression(parentId)&&!t.isIdentifier(parentId)){var key=scope.generateUidBasedOnNode(parentId);nodes.push(buildVariableDeclar(opts,key,parentId));parentId=key}push(opts,nodes,pattern,parentId)};exports.ForInStatement=exports.ForOfStatement=function(node,parent,scope,context,file){var declar=node.left;if(!t.isVariableDeclaration(declar))return;var pattern=declar.declarations[0].id;if(!t.isPattern(pattern))return;var key=scope.generateUidIdentifier("ref");node.left=t.variableDeclaration(declar.kind,[t.variableDeclarator(key,null)]);var nodes=[];push({kind:declar.kind,file:file,scope:scope},nodes,pattern,key);t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.Function=function(node,parent,scope,context,file){var nodes=[];var hasDestructuring=false;node.params=node.params.map(function(pattern,i){if(!t.isPattern(pattern))return pattern;hasDestructuring=true;var parentId=scope.generateUidIdentifier("ref");pushPattern({blockHoist:node.params.length-i,pattern:pattern,nodes:nodes,scope:scope,file:file,kind:"var",id:parentId});return parentId});if(!hasDestructuring)return;t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.CatchClause=function(node,parent,scope,context,file){var pattern=node.param;if(!t.isPattern(pattern))return;var ref=scope.generateUidIdentifier("ref");node.param=ref;var nodes=[];push({kind:"var",file:file,scope:scope},nodes,pattern,ref);node.body.body=nodes.concat(node.body.body)};exports.ExpressionStatement=function(node,parent,scope,context,file){var expr=node.expression;if(expr.type!=="AssignmentExpression")return;if(!t.isPattern(expr.left))return;if(file.isConsequenceExpressionStatement(node))return;var nodes=[];var ref=scope.generateUidIdentifier("ref");nodes.push(t.variableDeclaration("var",[t.variableDeclarator(ref,expr.right)]));push({operator:expr.operator,file:file,scope:scope},nodes,expr.left,ref);return nodes};exports.AssignmentExpression=function(node,parent,scope,context,file){if(!t.isPattern(node.left))return;var ref=scope.generateUidIdentifier("temp");scope.push({key:ref.name,id:ref});var nodes=[];nodes.push(t.assignmentExpression("=",ref,node.right));push({operator:node.operator,file:file,scope:scope},nodes,node.left,ref);nodes.push(ref);return t.toSequenceExpression(nodes,scope)};exports.VariableDeclaration=function(node,parent,scope,context,file){if(t.isForInStatement(parent)||t.isForOfStatement(parent))return;var nodes=[];var i;var declar;var hasPattern=false;for(i=0;i<node.declarations.length;i++){declar=node.declarations[i];if(t.isPattern(declar.id)){hasPattern=true;break}}if(!hasPattern)return;for(i=0;i<node.declarations.length;i++){declar=node.declarations[i];var patternId=declar.init;var pattern=declar.id;var opts={pattern:pattern,nodes:nodes,scope:scope,kind:node.kind,file:file,id:patternId};if(t.isPattern(pattern)&&patternId){pushPattern(opts);if(+i!==node.declarations.length-1){t.inherits(nodes[nodes.length-1],declar)}}else{nodes.push(t.inherits(buildVariableAssign(opts,declar.id,declar.init),declar))}}if(!t.isProgram(parent)&&!t.isBlockStatement(parent)){declar=null;for(i=0;i<nodes.length;i++){node=nodes[i];declar=declar||t.variableDeclaration(node.kind,[]);if(!t.isVariableDeclaration(node)&&declar.kind!==node.kind){throw file.errorWithNode(node,"Cannot use this node within the current parent")}declar.declarations=declar.declarations.concat(node.declarations)}return declar}return nodes}},{"../../../types":102}],60:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.ForOfStatement=function(node,parent,scope,context,file){var callback=spec;if(file.isLoose("es6.forOf"))callback=loose;var build=callback(node,parent,scope,context,file);var declar=build.declar;var loop=build.loop;var block=loop.body;t.inheritsComments(loop,node);t.ensureBlock(node);if(declar){block.body.push(declar)}block.body=block.body.concat(node.body.body);loop._scopeInfo=node._scopeInfo;return loop};var loose=function(node,parent,scope,context,file){var left=node.left;var declar,id;if(t.isIdentifier(left)||t.isPattern(left)){id=left}else if(t.isVariableDeclaration(left)){id=scope.generateUidIdentifier("ref");declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,id)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var loop=util.template("for-of-loose",{LOOP_OBJECT:scope.generateUidIdentifier("iterator"),IS_ARRAY:scope.generateUidIdentifier("isArray"),OBJECT:node.right,INDEX:scope.generateUidIdentifier("i"),ID:id});if(!declar){loop.body.body.shift()}return{declar:declar,loop:loop}};var spec=function(node,parent,scope,context,file){var left=node.left;var declar;var stepKey=scope.generateUidIdentifier("step");var stepValue=t.memberExpression(stepKey,t.identifier("value"));if(t.isIdentifier(left)||t.isPattern(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var loop=util.template("for-of",{ITERATOR_KEY:scope.generateUidIdentifier("iterator"),STEP_KEY:stepKey,OBJECT:node.right});return{declar:declar,loop:loop}}},{"../../../types":102,"../../../util":105}],61:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ImportDeclaration=function(node,parent,scope,context,file){var nodes=[];if(node.specifiers.length){for(var i=0;i<node.specifiers.length;i++){file.moduleFormatter.importSpecifier(node.specifiers[i],node,nodes,parent)}}else{file.moduleFormatter.importDeclaration(node,nodes,parent)}if(nodes.length===1){nodes[0]._blockHoist=node._blockHoist}return nodes};exports.ExportDeclaration=function(node,parent,scope,context,file){var nodes=[];var i;if(node.declaration){if(t.isVariableDeclaration(node.declaration)){var declar=node.declaration.declarations[0];declar.init=declar.init||t.identifier("undefined")}file.moduleFormatter.exportDeclaration(node,nodes,parent)}else if(node.specifiers){for(i=0;i<node.specifiers.length;i++){file.moduleFormatter.exportSpecifier(node.specifiers[i],node,nodes,parent)}}if(node._blockHoist){for(i=0;i<nodes.length;i++){nodes[i]._blockHoist=node._blockHoist}}return nodes}},{"../../../types":102}],62:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var util=require("../../../util");var t=require("../../../types");var hasDefaults=function(node){for(var i=0;i<node.params.length;i++){if(t.isAssignmentPattern(node.params[i]))return true}return false};var iifeVisitor={enter:function(node,parent,scope,context,state){if(t.isReferencedIdentifier(node,parent)&&state.scope.hasOwn(node.name)){state.iife=true;context.stop()}}};exports.Function=function(node,parent,scope){if(!hasDefaults(node))return;t.ensureBlock(node);var body=[];var argsIdentifier=t.identifier("arguments");argsIdentifier._ignoreAliasFunctions=true;var lastNonDefaultParam=0;var state={iife:false,scope:scope};for(var i=0;i<node.params.length;i++){var param=node.params[i];if(!t.isAssignmentPattern(param)){lastNonDefaultParam=+i+1;continue}var left=param.left;var right=param.right;node.params[i]=scope.generateUidIdentifier("x");if(!state.iife){if(t.isIdentifier(right)&&scope.hasOwn(right.name)){state.iife=true}else{traverse(right,iifeVisitor,scope,state)}}var defNode=util.template("default-parameter",{VARIABLE_NAME:left,DEFAULT_VALUE:right,ARGUMENT_KEY:t.literal(+i),ARGUMENTS:argsIdentifier},true);defNode._blockHoist=node.params.length-i;body.push(defNode)}node.params=node.params.slice(0,lastNonDefaultParam);if(state.iife){var container=t.functionExpression(null,[],node.body,node.generator);container._aliasFunction=true;body.push(t.returnStatement(t.callExpression(container,[])));node.body=t.blockStatement(body)}else{node.body.body=body.concat(node.body.body)}}},{"../../../traverse":98,"../../../types":102,"../../../util":105}],63:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");var hasRest=function(node){return t.isRestElement(node.params[node.params.length-1])};exports.Function=function(node,parent,scope){if(!hasRest(node))return;var rest=node.params.pop().argument;var argsId=t.identifier("arguments");argsId._ignoreAliasFunctions=true;var start=t.literal(node.params.length);var key=scope.generateUidIdentifier("key");var len=scope.generateUidIdentifier("len");var arrKey=key;var arrLen=len;if(node.params.length){arrKey=t.binaryExpression("-",key,start);arrLen=t.conditionalExpression(t.binaryExpression(">",len,start),t.binaryExpression("-",len,start),t.literal(0))}if(t.isPattern(rest)){var pattern=rest;rest=scope.generateUidIdentifier("ref");var restDeclar=t.variableDeclaration("var",[t.variableDeclarator(pattern,rest)]);restDeclar._blockHoist=node.params.length+1;node.body.body.unshift(restDeclar)}var loop=util.template("rest",{ARGUMENTS:argsId,ARRAY_KEY:arrKey,ARRAY_LEN:arrLen,START:start,ARRAY:rest,KEY:key,LEN:len});loop._blockHoist=node.params.length+1;node.body.body.unshift(loop)}},{"../../../types":102,"../../../util":105}],64:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ObjectExpression=function(node,parent,scope,context,file){var hasComputed=false;for(var i=0;i<node.properties.length;i++){hasComputed=t.isProperty(node.properties[i],{computed:true,kind:"init"});if(hasComputed)break}if(!hasComputed)return;var initProps=[];var objId=scope.generateUidBasedOnNode(parent);var body=[];var container=t.functionExpression(null,[],t.blockStatement(body));container._aliasFunction=true;var callback=spec;if(file.isLoose("es6.properties.computed"))callback=loose;var result=callback(node,body,objId,initProps,file);if(result)return result;body.unshift(t.variableDeclaration("var",[t.variableDeclarator(objId,t.objectExpression(initProps))]));body.push(t.returnStatement(objId));return t.callExpression(container,[])};var loose=function(node,body,objId){for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];body.push(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,prop.computed),prop.value)))}};var spec=function(node,body,objId,initProps,file){var props=node.properties;var prop,key;for(var i=0;i<props.length;i++){prop=props[i];if(prop.kind!=="init")continue;key=prop.key;if(!prop.computed&&t.isIdentifier(key)){prop.key=t.literal(key.name)}}var broken=false;for(i=0;i<props.length;i++){prop=props[i];if(prop.computed){broken=true}if(prop.kind!=="init"||!broken||t.isLiteral(t.toComputedKey(prop,prop.key),{value:"__proto__"})){initProps.push(prop);props[i]=null}}for(i=0;i<props.length;i++){prop=props[i];if(!prop)continue;key=prop.key;var bodyNode;if(prop.computed&&t.isMemberExpression(key)&&t.isIdentifier(key.object,{name:"Symbol"})){bodyNode=t.assignmentExpression("=",t.memberExpression(objId,key,true),prop.value)}else{bodyNode=t.callExpression(file.addHelper("define-property"),[objId,key,prop.value])}body.push(t.expressionStatement(bodyNode))}if(body.length===1){var first=body[0].expression;if(t.isCallExpression(first)){first.arguments[0]=t.objectExpression(initProps);return first}}}},{"../../../types":102}],65:[function(require,module,exports){"use strict";var nameMethod=require("../../helpers/name-method");var t=require("../../../types");var clone=require("lodash/lang/clone");exports.Property=function(node,parent,scope,context,file){if(node.method){node.method=false;nameMethod.property(node,file,scope)}if(node.shorthand){node.shorthand=false;node.key=t.removeComments(clone(node.key))}}},{"../../../types":102,"../../helpers/name-method":33,"lodash/lang/clone":241}],66:[function(require,module,exports){"use strict";var t=require("../../../types");var contains=require("lodash/collection/contains");var getSpreadLiteral=function(spread,file){return file.toArray(spread.argument)};var hasSpread=function(nodes){for(var i=0;i<nodes.length;i++){if(t.isSpreadElement(nodes[i])){return true}}return false};var build=function(props,file){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};for(var i=0;i<props.length;i++){var prop=props[i];if(t.isSpreadElement(prop)){push();nodes.push(getSpreadLiteral(prop,file))}else{_props.push(prop)}}push();return nodes};exports.ArrayExpression=function(node,parent,scope,context,file){var elements=node.elements;if(!hasSpread(elements))return;var nodes=build(elements,file);var first=nodes.shift();if(!t.isArrayExpression(first)){nodes.unshift(first);first=t.arrayExpression([])}return t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)};exports.CallExpression=function(node,parent,scope,context,file){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.identifier("undefined");node.arguments=[];var nodes;if(args.length===1&&args[0].argument.name==="arguments"){nodes=[args[0].argument]}else{nodes=build(args,file)}var first=nodes.shift();if(nodes.length){node.arguments.push(t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes))}else{node.arguments.push(first)}var callee=node.callee;if(t.isMemberExpression(callee)){var temp=scope.generateTempBasedOnNode(callee.object);if(temp){callee.object=t.assignmentExpression("=",temp,callee.object);contextLiteral=temp}else{contextLiteral=callee.object}t.appendToMemberExpression(callee,t.identifier("apply"))}else{node.callee=t.memberExpression(node.callee,t.identifier("apply"))}node.arguments.unshift(contextLiteral)};exports.NewExpression=function(node,parent,scope,context,file){var args=node.arguments;if(!hasSpread(args))return;var nativeType=t.isIdentifier(node.callee)&&contains(t.NATIVE_TYPE_NAMES,node.callee.name);var nodes=build(args,file);if(nativeType){nodes.unshift(t.arrayExpression([t.literal(null)]))}var first=nodes.shift();if(nodes.length){args=t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)}else{args=first}if(nativeType){return t.newExpression(t.callExpression(t.memberExpression(file.addHelper("bind"),t.identifier("apply")),[node.callee,args]),[])}else{return t.callExpression(file.addHelper("apply-constructor"),[node.callee,args])}}},{"../../../types":102,"lodash/collection/contains":176}],67:[function(require,module,exports){"use strict";var t=require("../../../types");var buildBinaryExpression=function(left,right){return t.binaryExpression("+",left,right)};exports.TaggedTemplateExpression=function(node,parent,scope,context,file){var args=[];var quasi=node.quasi;var strings=[];var raw=[];for(var i=0;i<quasi.quasis.length;i++){var elem=quasi.quasis[i];strings.push(t.literal(elem.value.cooked));raw.push(t.literal(elem.value.raw))}strings=t.arrayExpression(strings);raw=t.arrayExpression(raw);var templateName="tagged-template-literal";if(file.isLoose("es6.templateLiterals"))templateName+="-loose";args.push(t.callExpression(file.addHelper(templateName),[strings,raw]));args=args.concat(quasi.expressions);return t.callExpression(node.tag,args)};exports.TemplateLiteral=function(node){var nodes=[];var i;for(i=0;i<node.quasis.length;i++){var elem=node.quasis[i];nodes.push(t.literal(elem.value.cooked));var expr=node.expressions.shift();if(expr)nodes.push(expr)}if(nodes.length>1){var last=nodes[nodes.length-1];if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());for(i=0;i<nodes.length;i++){root=buildBinaryExpression(root,nodes[i])}return root}else{return nodes[0]}}},{"../../../types":102}],68:[function(require,module,exports){"use strict";var rewritePattern=require("regexpu/rewrite-pattern");var pull=require("lodash/array/pull");exports.Literal=function(node){var regex=node.regex;if(!regex)return;var flags=regex.flags.split("");if(regex.flags.indexOf("u")<0)return;pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{"lodash/array/pull":174,"regexpu/rewrite-pattern":283}],69:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.experimental=true;var container=function(parent,call,ret,file){if(t.isExpressionStatement(parent)&&!file.isConsequenceExpressionStatement(parent)){return call}else{var exprs=[];if(t.isSequenceExpression(call)){exprs=call.expressions}else{exprs.push(call)}exprs.push(ret);return t.sequenceExpression(exprs)}};exports.AssignmentExpression=function(node,parent,scope,context,file){var left=node.left;if(!t.isVirtualPropertyExpression(left))return;var value=node.right;var temp;if(!t.isExpressionStatement(parent)){temp=scope.generateTempBasedOnNode(node.right);if(temp)value=temp}if(node.operator!=="="){value=t.binaryExpression(node.operator[0],util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object}),value)}var call=util.template("abstract-expression-set",{PROPERTY:left.property,OBJECT:left.object,VALUE:value});if(temp){call=t.sequenceExpression([t.assignmentExpression("=",temp,node.right),call])}return container(parent,call,value,file)};exports.UnaryExpression=function(node,parent,scope,context,file){var arg=node.argument;if(!t.isVirtualPropertyExpression(arg))return;if(node.operator!=="delete")return;var call=util.template("abstract-expression-delete",{PROPERTY:arg.property,OBJECT:arg.object});return container(parent,call,t.literal(true),file)};exports.CallExpression=function(node,parent,scope){var callee=node.callee;if(!t.isVirtualPropertyExpression(callee))return;var temp=scope.generateTempBasedOnNode(callee.object);var call=util.template("abstract-expression-call",{PROPERTY:callee.property,OBJECT:temp||callee.object});call.arguments=call.arguments.concat(node.arguments);if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,callee.object),call])}else{return call}};exports.VirtualPropertyExpression=function(node){return util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object})};exports.PrivateDeclaration=function(node){return t.variableDeclaration("const",node.declarations.map(function(id){return t.variableDeclarator(id,t.newExpression(t.identifier("WeakMap"),[]))}))}},{"../../../types":102,"../../../util":105}],70:[function(require,module,exports){"use strict";var buildComprehension=require("../../helpers/build-comprehension");var traverse=require("../../../traverse");var util=require("../../../util");var t=require("../../../types");exports.experimental=true;exports.ComprehensionExpression=function(node,parent,scope,context,file){var callback=array;if(node.generator)callback=generator;return callback(node,parent,scope,file)};var generator=function(node){var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);container._aliasFunction=true;body.push(buildComprehension(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])};var array=function(node,parent,scope,file){var uid=scope.generateUidBasedOnNode(parent,file);var container=util.template("array-comprehension-container",{KEY:uid});container.callee._aliasFunction=true;var block=container.callee.body;var body=block.body;if(traverse.hasType(node,scope,"YieldExpression",t.FUNCTION_TYPES)){container.callee.generator=true;container=t.yieldExpression(container,true)}var returnStatement=body.pop();body.push(buildComprehension(node,function(){return util.template("array-push",{STATEMENT:node.body,KEY:uid},true)}));body.push(returnStatement);return container}},{"../../../traverse":98,"../../../types":102,"../../../util":105,"../../helpers/build-comprehension":30}],71:[function(require,module,exports){"use strict";exports.experimental=true;var build=require("../../helpers/build-binary-assignment-operator-transformer");var t=require("../../../types");var MATH_POW=t.memberExpression(t.identifier("Math"),t.identifier("pow"));build(exports,{operator:"**",build:function(left,right){return t.callExpression(MATH_POW,[left,right])}})},{"../../../types":102,"../../helpers/build-binary-assignment-operator-transformer":29}],72:[function(require,module,exports){"use strict";var t=require("../../../types");exports.experimental=true;exports.ObjectExpression=function(node,parent,scope,context,file){var hasSpread=false;var i;var prop;for(i=0;i<node.properties.length;i++){prop=node.properties[i];if(t.isSpreadProperty(prop)){hasSpread=true;break}}if(!hasSpread)return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};for(i=0;i<node.properties.length;i++){prop=node.properties[i];if(t.isSpreadProperty(prop)){push();args.push(prop.argument)}else{props.push(prop)}}push();if(!t.isObjectExpression(args[0])){args.unshift(t.objectExpression([]))}return t.callExpression(file.addHelper("extends"),args)}},{"../../../types":102}],73:[function(require,module,exports){module.exports={useStrict:require("./other/use-strict"),"validation.undeclaredVariableCheck":require("./validation/undeclared-variable-check"),"validation.noForInOfAssignment":require("./validation/no-for-in-of-assignment"),"validation.setters":require("./validation/setters"),"spec.blockScopedFunctions":require("./spec/block-scoped-functions"),"playground.malletOperator":require("./playground/mallet-operator"),"playground.methodBinding":require("./playground/method-binding"),"playground.memoizationOperator":require("./playground/memoization-operator"),"playground.objectGetterMemoization":require("./playground/object-getter-memoization"),react:require("./other/react"),_modules:require("./internal/modules"),"es7.comprehensions":require("./es7/comprehensions"),"es6.arrowFunctions":require("./es6/arrow-functions"),"es6.classes":require("./es6/classes"),asyncToGenerator:require("./other/async-to-generator"),bluebirdCoroutines:require("./other/bluebird-coroutines"),"es7.objectSpread":require("./es7/object-spread"),"es7.exponentiationOperator":require("./es7/exponentiation-operator"),"es6.spread":require("./es6/spread"),"es6.templateLiterals":require("./es6/template-literals"),"es5.properties.mutators":require("./es5/properties.mutators"),"es6.properties.shorthand":require("./es6/properties.shorthand"),"es6.properties.computed":require("./es6/properties.computed"),"es6.forOf":require("./es6/for-of"),"es6.unicodeRegex":require("./es6/unicode-regex"),"es7.abstractReferences":require("./es7/abstract-references"),"es6.constants":require("./es6/constants"),"es6.blockScoping":require("./es6/block-scoping"),"es6.blockScopingTDZ":require("./es6/block-scoping-tdz"),"es6.parameters.default":require("./es6/parameters.default"),"es6.parameters.rest":require("./es6/parameters.rest"),"es6.destructuring":require("./es6/destructuring"),regenerator:require("./other/regenerator"),selfContained:require("./other/self-contained"),"es6.modules":require("./es6/modules"),_blockHoist:require("./internal/block-hoist"),"spec.protoToAssign":require("./spec/proto-to-assign"),_declarations:require("./internal/declarations"),_aliasFunctions:require("./internal/alias-functions"),_moduleFormatter:require("./internal/module-formatter"),"spec.typeofSymbol":require("./spec/typeof-symbol"),"spec.undefinedToVoid":require("./spec/undefined-to-void"),"minification.propertyLiterals":require("./minification/property-literals"),"minification.memberExpressionLiterals":require("./minification/member-expression-literals")}},{"./es5/properties.mutators":53,"./es6/arrow-functions":54,"./es6/block-scoping":56,"./es6/block-scoping-tdz":55,"./es6/classes":57,"./es6/constants":58,"./es6/destructuring":59,"./es6/for-of":60,"./es6/modules":61,"./es6/parameters.default":62,"./es6/parameters.rest":63,"./es6/properties.computed":64,"./es6/properties.shorthand":65,"./es6/spread":66,"./es6/template-literals":67,"./es6/unicode-regex":68,"./es7/abstract-references":69,"./es7/comprehensions":70,"./es7/exponentiation-operator":71,"./es7/object-spread":72,"./internal/alias-functions":74,"./internal/block-hoist":75,"./internal/declarations":76,"./internal/module-formatter":77,"./internal/modules":78,"./minification/member-expression-literals":79,"./minification/property-literals":80,"./other/async-to-generator":81,"./other/bluebird-coroutines":82,"./other/react":83,"./other/regenerator":84,"./other/self-contained":85,"./other/use-strict":86,"./playground/mallet-operator":87,"./playground/memoization-operator":88,"./playground/method-binding":89,"./playground/object-getter-memoization":90,"./spec/block-scoped-functions":91,"./spec/proto-to-assign":92,"./spec/typeof-symbol":93,"./spec/undefined-to-void":94,"./validation/no-for-in-of-assignment":95,"./validation/setters":96,"./validation/undeclared-variable-check":97}],74:[function(require,module,exports){"use strict"; var traverse=require("../../../traverse");var t=require("../../../types");var functionChildrenVisitor={enter:function(node,parent,scope,context,state){if(t.isFunction(node)&&!node._aliasFunction){return context.skip()}if(node._ignoreAliasFunctions)return context.skip();var getId;if(t.isIdentifier(node)&&node.name==="arguments"){getId=state.getArgumentsId}else if(t.isThisExpression(node)){getId=state.getThisId}else{return}if(t.isReferenced(node,parent))return getId()}};var functionVisitor={enter:function(node,parent,scope,context,state){if(!node._aliasFunction){if(t.isFunction(node)){return context.skip()}else{return}}traverse(node,functionChildrenVisitor,scope,state);return context.skip()}};var go=function(getBody,node,scope){var argumentsId;var thisId;var state={getArgumentsId:function(){return argumentsId=argumentsId||scope.generateUidIdentifier("arguments")},getThisId:function(){return thisId=thisId||scope.generateUidIdentifier("this")}};traverse(node,functionVisitor,scope,state);var body;var pushDeclaration=function(id,init){body=body||getBody();body.unshift(t.variableDeclaration("var",[t.variableDeclarator(id,init)]))};if(argumentsId){pushDeclaration(argumentsId,t.identifier("arguments"))}if(thisId){pushDeclaration(thisId,t.thisExpression())}};exports.Program=function(node,parent,scope){go(function(){return node.body},node,scope)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,scope){go(function(){t.ensureBlock(node);return node.body.body},node,scope)}},{"../../../traverse":98,"../../../types":102}],75:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var groupBy=require("lodash/collection/groupBy");var flatten=require("lodash/array/flatten");var values=require("lodash/object/values");exports.BlockStatement=exports.Program={exit:function(node){var hasChange=false;for(var i=0;i<node.body.length;i++){var bodyNode=node.body[i];if(bodyNode&&bodyNode._blockHoist!=null)hasChange=true}if(!hasChange)return;useStrict.wrap(node,function(){var nodePriorities=groupBy(node.body,function(bodyNode){var priority=bodyNode._blockHoist;if(priority==null)priority=1;if(priority===true)priority=2;return priority});node.body=flatten(values(nodePriorities).reverse())})}}},{"../../helpers/use-strict":37,"lodash/array/flatten":172,"lodash/collection/groupBy":179,"lodash/object/values":263}],76:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var t=require("../../../types");exports.secondPass=true;exports.BlockStatement=exports.Program=function(node){if(!node._declarations)return;var kinds={};var kind;useStrict.wrap(node,function(){for(var i in node._declarations){var declar=node._declarations[i];kind=declar.kind||"var";var declarNode=t.variableDeclarator(declar.id,declar.init);if(!declar.init){kinds[kind]=kinds[kind]||[];kinds[kind].push(declarNode)}else{node.body.unshift(t.variableDeclaration(kind,[declarNode]))}}for(kind in kinds){node.body.unshift(t.variableDeclaration(kind,kinds[kind]))}});node._declarations=null}},{"../../../types":102,"../../helpers/use-strict":37}],77:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");exports.ast={exit:function(ast,file){if(!file.transformers["es6.modules"].canRun())return;useStrict.wrap(ast.program,function(){ast.program.body=file.dynamicImports.concat(ast.program.body)});if(file.moduleFormatter.transform){file.moduleFormatter.transform(ast)}}}},{"../../helpers/use-strict":37}],78:[function(require,module,exports){"use strict";var t=require("../../../types");var resolveModuleSource=function(node,parent,scope,context,file){var resolveModuleSource=file.opts.resolveModuleSource;if(node.source&&resolveModuleSource){node.source.value=resolveModuleSource(node.source.value)}};exports.ImportDeclaration=resolveModuleSource;exports.ExportDeclaration=function(node,parent,scope){resolveModuleSource.apply(null,arguments);var declar=node.declaration;if(node.default){if(t.isClassDeclaration(declar)){node.declaration=declar.id;return[declar,node]}else if(t.isClassExpression(declar)){var temp=scope.generateUidIdentifier("default");declar=t.variableDeclaration("var",[t.variableDeclarator(temp,declar)]);node.declaration=temp;return[declar,node]}else if(t.isFunctionDeclaration(declar)){node._blockHoist=2;node.declaration=declar.id;return[declar,node]}}else{if(t.isFunctionDeclaration(declar)){node.specifiers=[t.importSpecifier(declar.id,declar.id)];node.declaration=null;node._blockHoist=2;return[declar,node]}}}},{"../../../types":102}],79:[function(require,module,exports){"use strict";var t=require("../../../types");exports.MemberExpression=function(node){var prop=node.property;if(node.computed&&t.isLiteral(prop)&&t.isValidIdentifier(prop.value)){node.property=t.identifier(prop.value);node.computed=false}else if(!node.computed&&t.isIdentifier(prop)&&!t.isValidIdentifier(prop.name)){node.property=t.literal(prop.name);node.computed=true}}},{"../../../types":102}],80:[function(require,module,exports){"use strict";var t=require("../../../types");exports.Property=function(node){var key=node.key;if(t.isLiteral(key)&&t.isValidIdentifier(key.value)){node.key=t.identifier(key.value);node.computed=false}else if(!node.computed&&t.isIdentifier(key)&&!t.isValidIdentifier(key.name)){node.key=t.literal(key.name)}}},{"../../../types":102}],81:[function(require,module,exports){"use strict";var remapAsyncToGenerator=require("../../helpers/remap-async-to-generator");var bluebirdCoroutines=require("./bluebird-coroutines");exports.optional=true;exports.manipulateOptions=bluebirdCoroutines.manipulateOptions;exports.Function=function(node,parent,scope,context,file){if(!node.async||node.generator)return;return remapAsyncToGenerator(node,file.addHelper("async-to-generator"),scope)}},{"../../helpers/remap-async-to-generator":35,"./bluebird-coroutines":82}],82:[function(require,module,exports){"use strict";var remapAsyncToGenerator=require("../../helpers/remap-async-to-generator");var t=require("../../../types");exports.manipulateOptions=function(opts){opts.experimental=true;opts.blacklist.push("regenerator")};exports.optional=true;exports.Function=function(node,parent,scope,context,file){if(!node.async||node.generator)return;return remapAsyncToGenerator(node,t.memberExpression(file.addImport("bluebird"),t.identifier("coroutine")),scope)}},{"../../../types":102,"../../helpers/remap-async-to-generator":35}],83:[function(require,module,exports){"use strict";var esutils=require("esutils");var react=require("../../helpers/react");var t=require("../../../types");exports.JSXIdentifier=function(node,parent){if(node.name==="this"&&t.isReferenced(node,parent)){return t.thisExpression()}else if(esutils.keyword.isIdentifierName(node.name)){node.type="Identifier"}else{return t.literal(node.name)}};exports.JSXNamespacedName=function(node,parent,scope,context,file){throw file.errorWithNode(node,"Namespace tags are not supported. ReactJSX is not XML.")};exports.JSXMemberExpression={exit:function(node){node.computed=t.isLiteral(node.property);node.type="MemberExpression"}};exports.JSXExpressionContainer=function(node){return node.expression};exports.JSXAttribute={exit:function(node){var value=node.value||t.literal(true);return t.inherits(t.property("init",node.name,value),node)}};var isCompatTag=function(tagName){return/^[a-z]|\-/.test(tagName)};exports.JSXOpeningElement={exit:function(node,parent,scope,context,file){var reactCompat=file.opts.reactCompat;var tagExpr=node.name;var args=[];var tagName;if(t.isIdentifier(tagExpr)){tagName=tagExpr.name}else if(t.isLiteral(tagExpr)){tagName=tagExpr.value}if(!reactCompat){if(tagName&&isCompatTag(tagName)){args.push(t.literal(tagName))}else{args.push(tagExpr)}}var attribs=node.attributes;if(attribs.length){attribs=buildJSXOpeningElementAttributes(attribs,file)}else{attribs=t.literal(null)}args.push(attribs);if(reactCompat){if(tagName&&isCompatTag(tagName)){return t.callExpression(t.memberExpression(t.memberExpression(t.identifier("React"),t.identifier("DOM")),tagExpr,t.isLiteral(tagExpr)),args)}}else{tagExpr=t.memberExpression(t.identifier("React"),t.identifier("createElement"))}return t.callExpression(tagExpr,args)}};var buildJSXOpeningElementAttributes=function(attribs,file){var _props=[];var objs=[];var pushProps=function(){if(!_props.length)return;objs.push(t.objectExpression(_props));_props=[]};while(attribs.length){var prop=attribs.shift();if(t.isJSXSpreadAttribute(prop)){pushProps();objs.push(prop.argument)}else{_props.push(prop)}}pushProps();if(objs.length===1){attribs=objs[0]}else{if(!t.isObjectExpression(objs[0])){objs.unshift(t.objectExpression([]))}attribs=t.callExpression(file.addHelper("extends"),objs)}return attribs};exports.JSXElement={exit:function(node){var callExpr=node.openingElement;for(var i=0;i<node.children.length;i++){var child=node.children[i];if(t.isLiteral(child)&&typeof child.value==="string"){cleanJSXElementLiteralChild(child,callExpr.arguments);continue}else if(t.isJSXEmptyExpression(child)){continue}callExpr.arguments.push(child)}if(callExpr.arguments.length>=3){callExpr._prettyCall=true}return t.inherits(callExpr,node)}};var cleanJSXElementLiteralChild=function(child,args){var lines=child.value.split(/\r\n|\n|\r/);for(var i=0;i<lines.length;i++){var line=lines[i];var isFirstLine=i===0;var isLastLine=i===lines.length-1;var trimmedLine=line.replace(/\t/g," ");if(!isFirstLine){trimmedLine=trimmedLine.replace(/^[ ]+/,"")}if(!isLastLine){trimmedLine=trimmedLine.replace(/[ ]+$/,"")}if(trimmedLine){args.push(t.literal(trimmedLine))}}};var addDisplayName=function(id,call){if(!react.isCreateClass(call))return;var props=call.arguments[0].properties;var safe=true;for(var i=0;i<props.length;i++){var prop=props[i];if(t.isIdentifier(prop.key,{name:"displayName"})){safe=false;break}}if(safe){props.unshift(t.property("init",t.identifier("displayName"),t.literal(id)))}};exports.AssignmentExpression=exports.Property=exports.VariableDeclarator=function(node){var left,right;if(t.isAssignmentExpression(node)){left=node.left;right=node.right}else if(t.isProperty(node)){left=node.key;right=node.value}else if(t.isVariableDeclarator(node)){left=node.id;right=node.init}if(t.isMemberExpression(left)){left=left.property}if(t.isIdentifier(left)){addDisplayName(left.name,right)}}},{"../../../types":102,"../../helpers/react":34,esutils:167}],84:[function(require,module,exports){"use strict";var regenerator=require("regenerator-6to5");exports.ast={before:function(ast,file){regenerator.transform(ast,{includeRuntime:file.opts.includeRegenerator&&"if used"})}}},{"regenerator-6to5":275}],85:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var util=require("../../../util");var core=require("core-js/library");var t=require("../../../types");var has=require("lodash/object/has");var contains=require("lodash/collection/contains");var coreHas=function(node){return node.name!=="_"&&has(core,node.name)};var ALIASABLE_CONSTRUCTORS=["Symbol","Promise","Map","WeakMap","Set","WeakSet"];var astVisitor={enter:function(node,parent,scope,context,file){var prop;if(t.isMemberExpression(node)&&t.isReferenced(node,parent)){var obj=node.object;prop=node.property;if(!t.isReferenced(obj,node))return;if(!node.computed&&coreHas(obj)&&has(core[obj.name],prop.name)){context.skip();return t.prependToMemberExpression(node,file.get("coreIdentifier"))}}else if(t.isReferencedIdentifier(node,parent)&&!t.isMemberExpression(parent)&&contains(ALIASABLE_CONSTRUCTORS,node.name)&&!scope.get(node.name,true)){return t.memberExpression(file.get("coreIdentifier"),node)}else if(t.isCallExpression(node)){if(node.arguments.length)return;var callee=node.callee;if(!t.isMemberExpression(callee))return;if(!callee.computed)return;prop=callee.property;if(!t.isIdentifier(prop.object,{name:"Symbol"}))return;if(!t.isIdentifier(prop.property,{name:"iterator"}))return;return util.template("corejs-iterator",{CORE_ID:file.get("coreIdentifier"),VALUE:callee.object})}}};exports.optional=true;exports.ast={enter:function(ast,file){file.setDynamic("runtimeIdentifier",function(){return file.addImport("6to5-runtime/helpers","to5Helpers")});file.setDynamic("coreIdentifier",function(){return file.addImport("6to5-runtime/core-js","core")});file.setDynamic("regeneratorIdentifier",function(){return file.addImport("6to5-runtime/regenerator","regeneratorRuntime")})},after:function(ast,file){traverse(ast,astVisitor,null,file)}};exports.Identifier=function(node,parent,scope,context,file){if(node.name==="regeneratorRuntime"&&t.isReferenced(node,parent)){return file.get("regeneratorIdentifier")}}},{"../../../traverse":98,"../../../types":102,"../../../util":105,"core-js/library":156,"lodash/collection/contains":176,"lodash/object/has":259}],86:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var t=require("../../../types");exports.ast={exit:function(ast){if(!useStrict.has(ast.program)){ast.program.body.unshift(t.expressionStatement(t.literal("use strict")))}}};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,scope,context){context.skip()};exports.ThisExpression=function(){return t.identifier("undefined")}},{"../../../types":102,"../../helpers/use-strict":37}],87:[function(require,module,exports){"use strict";var build=require("../../helpers/build-conditional-assignment-operator-transformer");var t=require("../../../types");exports.playground=true;build(exports,{is:function(node,file){var is=t.isAssignmentExpression(node)&&node.operator==="||=";if(is){var left=node.left;if(!t.isMemberExpression(left)&&!t.isIdentifier(left)){throw file.errorWithNode(left,"Expected type MemeberExpression or Identifier")}return true}},build:function(node){return t.unaryExpression("!",node,true)}})},{"../../../types":102,"../../helpers/build-conditional-assignment-operator-transformer":31}],88:[function(require,module,exports){"use strict";var build=require("../../helpers/build-conditional-assignment-operator-transformer");var t=require("../../../types");exports.playground=true;build(exports,{is:function(node){var is=t.isAssignmentExpression(node)&&node.operator==="?=";if(is)t.assertMemberExpression(node.left);return is},build:function(node,file){return t.unaryExpression("!",t.callExpression(t.memberExpression(file.addHelper("has-own"),t.identifier("call")),[node.object,node.property]),true)}})},{"../../../types":102,"../../helpers/build-conditional-assignment-operator-transformer":31}],89:[function(require,module,exports){"use strict";var t=require("../../../types");exports.playground=true;exports.BindMemberExpression=function(node,parent,scope){var object=node.object;var prop=node.property;var temp=scope.generateTempBasedOnNode(node.object);if(temp)object=temp;var call=t.callExpression(t.memberExpression(t.memberExpression(object,prop),t.identifier("bind")),[object].concat(node.arguments));if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,node.object),call])}else{return call}};exports.BindFunctionExpression=function(node,parent,scope,context,file){var buildCall=function(args){var param=scope.generateUidIdentifier("val");return t.functionExpression(null,[param],t.blockStatement([t.returnStatement(t.callExpression(t.memberExpression(param,node.callee),args))]))};var temp=scope.generateTemp(file,"args");return t.sequenceExpression([t.assignmentExpression("=",temp,t.arrayExpression(node.arguments)),buildCall(node.arguments.map(function(node,i){return t.memberExpression(temp,t.literal(i),true)}))])}},{"../../../types":102}],90:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");exports.playground=true;var visitor={enter:function(node,parent,scope,context,state){if(t.isFunction(node))return;if(t.isReturnStatement(node)&&node.argument){node.argument=t.memberExpression(t.callExpression(state.file.addHelper("define-property"),[t.thisExpression(),state.key,node.argument]),state.key,true)}}};exports.Property=exports.MethodDefinition=function(node,parent,scope,context,file){if(node.kind!=="memo")return;node.kind="get";var value=node.value;t.ensureBlock(value);var key=node.key;if(t.isIdentifier(key)&&!node.computed){key=t.literal(key.name)}var state={key:key,file:file};traverse(value,visitor,scope,state)}},{"../../../traverse":98,"../../../types":102}],91:[function(require,module,exports){"use strict";var t=require("../../../types");exports.BlockStatement=function(node,parent){if(t.isFunction(parent)&&parent.body===node||t.isExportDeclaration(parent)){return}for(var i=0;i<node.body.length;i++){var func=node.body[i];if(!t.isFunctionDeclaration(func))continue;var declar=t.variableDeclaration("let",[t.variableDeclarator(func.id,t.toExpression(func))]);declar._blockHoist=2;func.id=null;node.body[i]=declar}}},{"../../../types":102}],92:[function(require,module,exports){"use strict";var t=require("../../../types");var pull=require("lodash/array/pull");var isProtoKey=function(node){return t.isLiteral(t.toComputedKey(node,node.key),{value:"__proto__"})};var isProtoAssignmentExpression=function(node){var left=node.left;return t.isMemberExpression(left)&&t.isLiteral(t.toComputedKey(left,left.property),{value:"__proto__"})};var buildDefaultsCallExpression=function(expr,ref,file){return t.expressionStatement(t.callExpression(file.addHelper("defaults"),[ref,expr.right]))};exports.optional=true;exports.secondPass=true;exports.AssignmentExpression=function(node,parent,scope,context,file){if(!isProtoAssignmentExpression(node))return;var nodes=[];var left=node.left.object;var temp=scope.generateTempBasedOnNode(node.left.object);nodes.push(t.expressionStatement(t.assignmentExpression("=",temp,left)));nodes.push(buildDefaultsCallExpression(node,temp,file));if(temp)nodes.push(temp);return t.toSequenceExpression(nodes)};exports.ExpressionStatement=function(node,parent,scope,context,file){var expr=node.expression;if(!t.isAssignmentExpression(expr,{operator:"="}))return;if(isProtoAssignmentExpression(expr)){return buildDefaultsCallExpression(expr,expr.left.object,file)}};exports.ObjectExpression=function(node,parent,scope,context,file){var proto;for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(isProtoKey(prop)){proto=prop.value;pull(node.properties,prop)}}if(proto){var args=[t.objectExpression([]),proto];if(node.properties.length)args.push(node);return t.callExpression(file.addHelper("extends"),args)}}},{"../../../types":102,"lodash/array/pull":174}],93:[function(require,module,exports){"use strict";var t=require("../../../types");exports.optional=true;exports.UnaryExpression=function(node,parent,scope,context,file){context.skip();if(node.operator==="typeof"){var call=t.callExpression(file.addHelper("typeof"),[node.argument]);if(t.isIdentifier(node.argument)){var undefLiteral=t.literal("undefined");return t.conditionalExpression(t.binaryExpression("===",t.unaryExpression("typeof",node.argument),undefLiteral),undefLiteral,call)}else{return call}}}},{"../../../types":102}],94:[function(require,module,exports){"use strict";var t=require("../../../types");exports.optional=true;exports.Identifier=function(node,parent){if(node.name==="undefined"&&t.isReferenced(node,parent)){return t.unaryExpression("void",t.literal(0),true)}}},{"../../../types":102}],95:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ForInStatement=exports.ForOfStatement=function(node,parent,scope,context,file){var left=node.left;if(t.isVariableDeclaration(left)){var declar=left.declarations[0];if(declar.init)throw file.errorWithNode(declar,"No assignments allowed in for-in/of head")}}},{"../../../types":102}],96:[function(require,module,exports){"use strict";exports.MethodDefinition=exports.Property=function(node,parent,scope,context,file){if(node.kind==="set"&&node.value.params.length!==1){throw file.errorWithNode(node.value,"Setters must have only one parameter")}}},{}],97:[function(require,module,exports){"use strict";var levenshtein=require("../../../helpers/levenshtein");var t=require("../../../types");exports.optional=true;exports.Identifier=function(node,parent,scope,context,file){if(!t.isReferenced(node,parent))return;if(scope.has(node.name,true))return;var msg="Reference to undeclared variable";var declarations=scope.getAllDeclarations();var closest;var shortest=-1;for(var name in declarations){var distance=levenshtein(node.name,name);if(distance<=0||distance>3)continue;if(distance<=shortest)continue;closest=name;shortest=distance}if(closest){msg+=" - Did you mean "+closest+"?"}throw file.errorWithNode(node,msg,ReferenceError)}},{"../../../helpers/levenshtein":25,"../../../types":102}],98:[function(require,module,exports){"use strict";module.exports=traverse;var Scope=require("./scope");var t=require("../types");var contains=require("lodash/collection/contains");var flatten=require("lodash/array/flatten");var compact=require("lodash/array/compact");function TraversalContext(){this.shouldFlatten=false;this.shouldRemove=false;this.shouldSkip=false;this.shouldStop=false}TraversalContext.prototype.flatten=function(){this.shouldFlatten=true};TraversalContext.prototype.remove=function(){this.shouldRemove=true;this.shouldSkip=true};TraversalContext.prototype.skip=function(){this.shouldSkip=true};TraversalContext.prototype.stop=function(){this.shouldStop=true;this.shouldSkip=true};TraversalContext.prototype.reset=function(){this.shouldRemove=false;this.shouldSkip=false;this.shouldStop=false};function replaceNode(obj,key,node,result){var isArray=Array.isArray(result);var inheritTo=result;if(isArray)inheritTo=result[0];if(inheritTo)t.inheritsComments(inheritTo,node);obj[key]=result;if(isArray&&contains(t.STATEMENT_OR_BLOCK_KEYS,key)&&!t.isBlockStatement(obj)){t.ensureBlock(obj,key)}if(isArray){return true}}TraversalContext.prototype.enterNode=function(obj,key,node,enter,parent,scope,state){var result=enter(node,parent,scope,this,state);var flatten=false;if(result){flatten=replaceNode(obj,key,node,result);node=result;if(flatten){this.shouldFlatten=true}}if(this.shouldRemove){obj[key]=null;this.shouldFlatten=true}return node};TraversalContext.prototype.exitNode=function(obj,key,node,exit,parent,scope,state){var result=exit(node,parent,scope,this,state);var flatten=false;if(result){flatten=replaceNode(obj,key,node,result);node=result;if(flatten){this.shouldFlatten=true}}return node};TraversalContext.prototype.visitNode=function(obj,key,opts,scope,parent,state){this.reset();var node=obj[key];if(opts.blacklist&&opts.blacklist.indexOf(node.type)>-1){return}var ourScope=scope;if(!opts.noScope&&t.isScope(node)){ourScope=new Scope(node,parent,scope)}node=this.enterNode(obj,key,node,opts.enter,parent,ourScope,state);if(this.shouldSkip){return this.shouldStop}if(Array.isArray(node)){for(var i=0;i<node.length;i++){traverseNode(node[i],opts,ourScope,state)}}else{traverseNode(node,opts,ourScope,state);this.exitNode(obj,key,node,opts.exit,parent,ourScope,state)}return this.shouldStop};TraversalContext.prototype.visit=function(node,key,opts,scope,state){var nodes=node[key];if(!nodes)return;if(!Array.isArray(nodes)){return this.visitNode(node,key,opts,scope,node,state)}if(nodes.length===0){return}for(var i=0;i<nodes.length;i++){if(nodes[i]&&this.visitNode(nodes,i,opts,scope,node,state)){return true}}if(this.shouldFlatten){node[key]=flatten(node[key]);if(key==="body"){node[key]=compact(node[key])}}};function traverseNode(node,opts,scope,state){var keys=t.VISITOR_KEYS[node.type];if(!keys)return;var context=new TraversalContext;for(var i=0;i<keys.length;i++){if(context.visit(node,keys[i],opts,scope,state)){return}}}function traverse(parent,opts,scope,state){if(!parent)return;if(!opts.noScope&&!scope){if(parent.type!=="Program"&&parent.type!=="File"){throw new Error("Must pass a scope unless traversing a Program/File got a "+parent.type+" node")}}if(!opts)opts={};if(!opts.enter)opts.enter=function(){};if(!opts.exit)opts.exit=function(){};if(Array.isArray(parent)){for(var i=0;i<parent.length;i++){traverseNode(parent[i],opts,scope,state)}}else{traverseNode(parent,opts,scope,state)}}function clearNode(node){node._declarations=null;node.extendedRange=null;node._scopeInfo=null;node.tokens=null;node.range=null;node.start=null;node.end=null;node.loc=null;node.raw=null;if(Array.isArray(node.trailingComments)){clearComments(node.trailingComments)}if(Array.isArray(node.leadingComments)){clearComments(node.leadingComments)}}var clearVisitor={noScope:true,enter:clearNode};function clearComments(comments){for(var i=0;i<comments.length;i++){clearNode(comments[i])}}traverse.removeProperties=function(tree){clearNode(tree);traverse(tree,clearVisitor);return tree};traverse.explode=function(obj){for(var type in obj){var fns=obj[type];var aliases=t.FLIPPED_ALIAS_KEYS[type];if(aliases){for(var i=0;i<aliases.length;i++){obj[aliases[i]]=fns}}}return obj};function hasBlacklistedType(node,parent,scope,context,state){if(node.type===state.type){state.has=true;context.skip()}}traverse.hasType=function(tree,scope,type,blacklistTypes){if(contains(blacklistTypes,tree.type))return false;if(tree.type===type)return true;var state={has:false,type:type};traverse(tree,{blacklist:blacklistTypes,enter:hasBlacklistedType},scope,state);return state.has}},{"../types":102,"./scope":99,"lodash/array/compact":171,"lodash/array/flatten":172,"lodash/collection/contains":176}],99:[function(require,module,exports){"use strict";module.exports=Scope;var traverse=require("./index");var globals=require("globals");var object=require("../helpers/object");var t=require("../types");var each=require("lodash/collection/each");var has=require("lodash/object/has");var contains=require("lodash/collection/contains");var flatten=require("lodash/array/flatten");var defaults=require("lodash/object/defaults");var FOR_KEYS=["left","init"];function Scope(block,parentBlock,parent,file){this.parent=parent;this.file=parent?parent.file:file;this.parentBlock=parentBlock;this.block=block;var info=this.getInfo();this.references=info.references;this.declarations=info.declarations;this.declarationKinds=info.declarationKinds}Scope.defaultDeclarations=flatten([globals.builtin,globals.browser,globals.node].map(Object.keys));Scope.prototype._add=function(node,references,throwOnDuplicate){if(!node)return;var ids=t.getDeclarations(node);for(var key in ids){var id=ids[key];if(throwOnDuplicate&&references[key]){throw this.file.errorWithNode(id,"Duplicate declaration",TypeError)}references[key]=id}};Scope.prototype.generateTemp=function(file,name){var id=file.generateUidIdentifier(name||"temp",this);this.push({key:id.name,id:id});return id};Scope.prototype.generateUidIdentifier=function(name){return this.file.generateUidIdentifier(name,this)};Scope.prototype.generateUidBasedOnNode=function(parent){var node=parent;if(t.isAssignmentExpression(parent)){node=parent.left}else if(t.isVariableDeclarator(parent)){node=parent.id}else if(t.isProperty(node)){node=node.key}var parts=[];var add=function(node){if(t.isMemberExpression(node)){add(node.object);add(node.property)}else if(t.isIdentifier(node)){parts.push(node.name)}else if(t.isLiteral(node)){parts.push(node.value)}else if(t.isCallExpression(node)){add(node.callee)}};add(node);var id=parts.join("$");id=id.replace(/^_/,"")||"ref";return this.file.generateUidIdentifier(id,this)};Scope.prototype.generateTempBasedOnNode=function(node){if(t.isIdentifier(node)&&this.has(node.name,true)){return null}var id=this.generateUidBasedOnNode(node);this.push({key:id.name,id:id});return id};var functionVariableVisitor={enter:function(node,parent,scope,context,state){if(t.isFor(node)){each(FOR_KEYS,function(key){var declar=node[key];if(t.isVar(declar))state.add(declar)})}if(t.isFunction(node))return context.skip();if(state.blockId&&node===state.blockId)return;if(t.isDeclaration(node)&&!t.isBlockScoped(node)){state.add(node)}}};var programReferenceVisitor={enter:function(node,parent,scope,context,add){if(t.isReferencedIdentifier(node,parent)&&!scope.has(node.name)){add(node,true)}}};var blockVariableVisitor={enter:function(node,parent,scope,context,add){if(t.isBlockScoped(node)){add(node,false,t.isLet(node))}else if(t.isScope(node)){context.skip()}}};Scope.prototype.getInfo=function(){var parent=this.parent;var block=this.block;var self=this;if(block._scopeInfo)return block._scopeInfo;var info=block._scopeInfo={};var references=info.references=object();var declarations=info.declarations=object();var declarationKinds=info.declarationKinds={};var add=function(node,reference,throwOnDuplicate){self._add(node,references);if(!reference){self._add(node,declarations,throwOnDuplicate);self._add(node,declarationKinds[node.kind]=declarationKinds[node.kind]||object())}};if(parent&&t.isBlockStatement(block)&&t.isFor(parent.block,{body:block})){return info}if(t.isFor(block)){each(FOR_KEYS,function(key){var node=block[key];if(t.isBlockScoped(node))add(node,false,true)});if(t.isBlockStatement(block.body)){block=block.body}}if(t.isBlockStatement(block)||t.isProgram(block)){traverse(block,blockVariableVisitor,this,add)}if(t.isCatchClause(block)){add(block.param)}if(t.isComprehensionExpression(block)){add(block)}if(t.isProgram(block)||t.isFunction(block)){traverse(block,functionVariableVisitor,this,{blockId:block.id,add:add})}if(t.isFunctionExpression(block)&&block.id){if(!t.isProperty(this.parentBlock,{method:true})){add(block.id)}}if(t.isProgram(block)){traverse(block,programReferenceVisitor,this,add)}if(t.isFunction(block)){each(block.params,function(param){add(param)})}return info};Scope.prototype.push=function(opts){var block=this.block;if(t.isFor(block)||t.isCatchClause(block)||t.isFunction(block)){t.ensureBlock(block);block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){block._declarations=block._declarations||{};block._declarations[opts.key]={kind:opts.kind,id:opts.id,init:opts.init}}else{throw new TypeError("cannot add a declaration here in node type "+block.type)}};Scope.prototype.add=function(node){var scope=this.getFunctionParent();scope._add(node,scope.references)};Scope.prototype.getFunctionParent=function(){var scope=this;while(scope.parent&&!t.isFunction(scope.block)){scope=scope.parent}return scope};Scope.prototype.getAllDeclarations=function(){var ids=object();var scope=this;do{defaults(ids,scope.declarations);scope=scope.parent}while(scope);return ids};Scope.prototype.getAllDeclarationsOfKind=function(kind){var ids=object();var scope=this;do{defaults(ids,scope.declarationKinds[kind]);scope=scope.parent}while(scope);return ids};Scope.prototype.get=function(id,decl){return id&&(this.getOwn(id,decl)||this.parentGet(id,decl))};Scope.prototype.getOwn=function(id,decl){var refs=this.references;if(decl)refs=this.declarations;return has(refs,id)&&refs[id]};Scope.prototype.parentGet=function(id,decl){return this.parent&&this.parent.get(id,decl)};Scope.prototype.has=function(id,decl){if(!id)return false;if(this.hasOwn(id,decl))return true;if(this.parentHas(id,decl))return true;if(contains(Scope.defaultDeclarations,id))return true;return false};Scope.prototype.hasOwn=function(id,decl){return!!this.getOwn(id,decl)};Scope.prototype.parentHas=function(id,decl){return this.parent&&this.parent.has(id,decl)}},{"../helpers/object":26,"../types":102,"./index":98,globals:169,"lodash/array/flatten":172,"lodash/collection/contains":176,"lodash/collection/each":177,"lodash/object/defaults":257,"lodash/object/has":259}],100:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement","Loop","While"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement","Loop","While"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],PrivateDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function","Expression"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function","Expression"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary","Expression"],BinaryExpression:["Binary","Expression"],UnaryExpression:["UnaryLike","Expression"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class","Expression"],ForOfStatement:["Statement","For","Scope","Loop"],ForInStatement:["Statement","For","Scope","Loop"],ForStatement:["Statement","For","Scope","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],AssignmentPattern:["Pattern"],Property:["UserWhitespacable"],JSXElement:["UserWhitespacable","Expression"],ArrayExpression:["Expression"],AssignmentExpression:["Expression"],AwaitExpression:["Expression"],BindFunctionExpression:["Expression"],BindMemberExpression:["Expression"],CallExpression:["Expression"],ComprehensionExpression:["Expression","Scope"],ConditionalExpression:["Expression"],Identifier:["Expression"],Literal:["Expression"],MemberExpression:["Expression"],NewExpression:["Expression"],ObjectExpression:["Expression"],SequenceExpression:["Expression"],TaggedTemplateExpression:["Expression"],ThisExpression:["Expression"],UpdateExpression:["Expression"],VirtualPropertyExpression:["Expression"],JSXEmptyExpression:["Expression"],JSXMemberExpression:["Expression"],YieldExpression:["Expression"]} },{}],101:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrowFunctionExpression:["params","body"],AssignmentExpression:["operator","left","right"],BinaryExpression:["operator","left","right"],BlockStatement:["body"],CallExpression:["callee","arguments"],ConditionalExpression:["test","consequent","alternate"],ExpressionStatement:["expression"],File:["program","comments","tokens"],FunctionExpression:["id","params","body","generator"],FunctionDeclaration:["id","params","body","generator"],Identifier:["name"],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],Literal:["value"],LogicalExpression:["operator","left","right"],MemberExpression:["object","property","computed"],MethodDefinition:["key","value","computed","kind"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],WithStatement:["object","body"],YieldExpression:["argument","delegate"]}},{}],102:[function(require,module,exports){"use strict";var toFastProperties=require("../helpers/to-fast-properties");var esutils=require("esutils");var object=require("../helpers/object");var Node=require("./node");var each=require("lodash/collection/each");var uniq=require("lodash/array/uniq");var compact=require("lodash/array/compact");var defaults=require("lodash/object/defaults");var isString=require("lodash/lang/isString");var t=exports;function registerType(type,skipAliasCheck){var is=t["is"+type]=function(node,opts){return t.is(type,node,opts,skipAliasCheck)};t["assert"+type]=function(node,opts){opts=opts||{};if(!is(node,opts)){throw new Error("Expected type "+JSON.stringify(type)+" with option "+JSON.stringify(opts))}}}t.STATEMENT_OR_BLOCK_KEYS=["consequent","body"];t.NATIVE_TYPE_NAMES=["Array","Object","Number","Boolean","Date","Array","String"];t.VISITOR_KEYS=require("./visitor-keys");t.ALIAS_KEYS=require("./alias-keys");t.FLIPPED_ALIAS_KEYS={};each(t.VISITOR_KEYS,function(keys,type){registerType(type,true)});each(t.ALIAS_KEYS,function(aliases,type){each(aliases,function(alias){var types=t.FLIPPED_ALIAS_KEYS[alias]=t.FLIPPED_ALIAS_KEYS[alias]||[];types.push(type)})});each(t.FLIPPED_ALIAS_KEYS,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;registerType(type,false)});t.is=function(type,node,opts,skipAliasCheck){if(!node)return;var typeMatches=type===node.type;if(!typeMatches&&!skipAliasCheck){var aliases=t.FLIPPED_ALIAS_KEYS[type];if(typeof aliases!=="undefined"){typeMatches=aliases.indexOf(node.type)>-1}}if(!typeMatches){return false}if(typeof opts!=="undefined"){return t.shallowEqual(node,opts)}return true};t.BUILDER_KEYS=defaults(require("./builder-keys"),t.VISITOR_KEYS);each(t.BUILDER_KEYS,function(keys,type){t[type[0].toLowerCase()+type.slice(1)]=function(){var args=arguments;var node=new Node;node.start=null;node.type=type;each(keys,function(key,i){node[key]=args[i]});return node}});t.toComputedKey=function(node,key){if(!node.computed){if(t.isIdentifier(key))key=t.literal(key.name)}return key};t.isFalsyExpression=function(node){if(t.isLiteral(node)){return!node.value}else if(t.isIdentifier(node)){return node.name==="undefined"}return false};t.toSequenceExpression=function(nodes,scope){var exprs=[];each(nodes,function(node){if(t.isExpression(node)){exprs.push(node)}if(t.isExpressionStatement(node)){exprs.push(node.expression)}else if(t.isVariableDeclaration(node)){each(node.declarations,function(declar){scope.push({kind:node.kind,key:declar.id.name,id:declar.id});exprs.push(t.assignmentExpression("=",declar.id,declar.init))})}});if(exprs.length===1){return exprs[0]}else{return t.sequenceExpression(exprs)}};t.shallowEqual=function(actual,expected){var keys=Object.keys(expected);for(var i=0;i<keys.length;i++){var key=keys[i];if(actual[key]!==expected[key]){return false}}return true};t.appendToMemberExpression=function(member,append,computed){member.object=t.memberExpression(member.object,member.property,member.computed);member.property=append;member.computed=!!computed;return member};t.prependToMemberExpression=function(member,append){member.object=t.memberExpression(append,member.object);return member};t.isReferenced=function(node,parent){if(t.isMemberExpression(parent)){if(parent.property===node&&parent.computed){return true}else if(parent.object===node){return true}else{return false}}if(t.isProperty(parent)&&parent.key===node){return parent.computed}if(t.isVariableDeclarator(parent)){return parent.id!==node}if(t.isFunction(parent)){for(var i=0;i<parent.params.length;i++){var param=parent.params[i];if(param===node)return false}return parent.id!==node}if(t.isClass(parent)){return parent.id!==node}if(t.isMethodDefinition(parent)){return parent.key===node&&parent.computed}if(t.isLabeledStatement(parent)){return false}if(t.isCatchClause(parent)){return parent.param!==node}if(t.isRestElement(parent)){return false}if(t.isAssignmentPattern(parent)){return parent.right!==node}if(t.isPattern(parent)){return false}if(t.isImportSpecifier(parent)){return false}if(t.isImportBatchSpecifier(parent)){return false}if(t.isPrivateDeclaration(parent)){return false}return true};t.isReferencedIdentifier=function(node,parent){return t.isIdentifier(node)&&t.isReferenced(node,parent)};t.isValidIdentifier=function(name){return isString(name)&&esutils.keyword.isIdentifierName(name)&&!esutils.keyword.isReservedWordES6(name,true)};t.toIdentifier=function(name){if(t.isIdentifier(name))return name.name;name=name+"";name=name.replace(/[^a-zA-Z0-9$_]/g,"-");name=name.replace(/^[-0-9]+/,"");name=name.replace(/[-\s]+(.)?/g,function(match,c){return c?c.toUpperCase():""});if(!t.isValidIdentifier(name)){name="_"+name}return name||"_"};t.ensureBlock=function(node,key){key=key||"body";node[key]=t.toBlock(node[key],node)};t.buildMatchMemberExpression=function(match,allowPartial){var parts=match.split(".");return function(member){if(!t.isMemberExpression(member))return false;var search=[member];var i=0;while(search.length){var node=search.shift();if(t.isIdentifier(node)){if(parts[i]!==node.name)return false}else if(t.isLiteral(node)){if(parts[i]!==node.value)return false}else if(t.isMemberExpression(node)){if(node.computed&&!t.isLiteral(node.property)){return false}else{search.push(node.object);search.push(node.property);continue}}else{return false}if(++i>parts.length){if(allowPartial){return true}else{return false}}}return true}};t.toStatement=function(node,ignore){if(t.isStatement(node)){return node}var mustHaveId=false;var newType;if(t.isClass(node)){mustHaveId=true;newType="ClassDeclaration"}else if(t.isFunction(node)){mustHaveId=true;newType="FunctionDeclaration"}else if(t.isAssignmentExpression(node)){return t.expressionStatement(node)}if(mustHaveId&&!node.id){newType=false}if(!newType){if(ignore){return false}else{throw new Error("cannot turn "+node.type+" to a statement")}}node.type=newType;return node};exports.toExpression=function(node){if(t.isExpressionStatement(node)){node=node.expression}if(t.isClass(node)){node.type="ClassExpression"}else if(t.isFunction(node)){node.type="FunctionExpression"}if(t.isExpression(node)){return node}else{throw new Error("cannot turn "+node.type+" to an expression")}};t.toBlock=function(node,parent){if(t.isBlockStatement(node)){return node}if(t.isEmptyStatement(node)){node=[]}if(!Array.isArray(node)){if(!t.isStatement(node)){if(t.isFunction(parent)){node=t.returnStatement(node)}else{node=t.expressionStatement(node)}}node=[node]}return t.blockStatement(node)};t.getDeclarations=function(node){var search=[].concat(node);var ids=object();while(search.length){var id=search.shift();if(!id)continue;var keys=t.getDeclarations.keys[id.type];if(t.isIdentifier(id)){ids[id.name]=id}else if(t.isExportDeclaration(id)){if(t.isDeclaration(node.declaration)){search.push(node.declaration)}}else if(keys){for(var i=0;i<keys.length;i++){var key=keys[i];search=search.concat(id[key]||[])}}}return ids};t.getDeclarations.keys={AssignmentExpression:["left"],ImportBatchSpecifier:["name"],ImportSpecifier:["name","id"],ExportSpecifier:["name","id"],VariableDeclarator:["id"],FunctionDeclaration:["id"],ClassDeclaration:["id"],MemeberExpression:["object"],SpreadElement:["argument"],RestElement:["argument"],Property:["value"],ComprehensionBlock:["left"],AssignmentPattern:["left"],PrivateDeclaration:["declarations"],ComprehensionExpression:["blocks"],ImportDeclaration:["specifiers"],VariableDeclaration:["declarations"],ArrayPattern:["elements"],ObjectPattern:["properties"]};t.isLet=function(node){return t.isVariableDeclaration(node)&&(node.kind!=="var"||node._let)};t.isBlockScoped=function(node){return t.isFunctionDeclaration(node)||t.isLet(node)};t.isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!node._let};t.COMMENT_KEYS=["leadingComments","trailingComments"];t.removeComments=function(child){each(t.COMMENT_KEYS,function(key){delete child[key]});return child};t.inheritsComments=function(child,parent){each(t.COMMENT_KEYS,function(key){child[key]=uniq(compact([].concat(child[key],parent[key])))});return child};t.inherits=function(child,parent){child.range=parent.range;child.start=parent.start;child.loc=parent.loc;child.end=parent.end;t.inheritsComments(child,parent);return child};t.getLastStatements=function(node){var nodes=[];var add=function(node){nodes=nodes.concat(t.getLastStatements(node))};if(t.isIfStatement(node)){add(node.consequent);add(node.alternate)}else if(t.isFor(node)||t.isWhile(node)){add(node.body)}else if(t.isProgram(node)||t.isBlockStatement(node)){add(node.body[node.body.length-1])}else if(node){nodes.push(node)}return nodes};t.getSpecifierName=function(specifier){return specifier.name||specifier.id};t.getSpecifierId=function(specifier){if(specifier.default){return t.identifier("default")}else{return specifier.id}};t.isSpecifierDefault=function(specifier){return specifier.default||t.isIdentifier(specifier.id)&&specifier.id.name==="default"};toFastProperties(t);toFastProperties(t.VISITOR_KEYS)},{"../helpers/object":26,"../helpers/to-fast-properties":27,"./alias-keys":100,"./builder-keys":101,"./node":103,"./visitor-keys":104,esutils:167,"lodash/array/compact":171,"lodash/array/uniq":175,"lodash/collection/each":177,"lodash/lang/isString":253,"lodash/object/defaults":257}],103:[function(require,module,exports){"use strict";module.exports=Node;var acorn=require("acorn-6to5");var oldNode=acorn.Node;acorn.Node=Node;function Node(){oldNode.apply(this)}},{"acorn-6to5":106}],104:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BindFunctionExpression:["callee","arguments"],BindMemberExpression:["object","property","arguments"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateDeclaration:["declarations"],Program:["body"],Property:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"],AnyTypeAnnotation:[],ArrayTypeAnnotation:[],BooleanTypeAnnotation:[],ClassProperty:["key"],DeclareClass:[],DeclareFunction:[],DeclareModule:[],DeclareVariable:[],FunctionTypeAnnotation:[],FunctionTypeParam:[],GenericTypeAnnotation:[],InterfaceExtends:[],InterfaceDeclaration:[],IntersectionTypeAnnotation:[],NullableTypeAnnotation:[],NumberTypeAnnotation:[],StringLiteralTypeAnnotation:[],StringTypeAnnotation:[],TupleTypeAnnotation:[],TypeofTypeAnnotation:[],TypeAlias:[],TypeAnnotation:[],TypeParameterDeclaration:[],TypeParameterInstantiation:[],ObjectTypeAnnotation:[],ObjectTypeCallProperty:[],ObjectTypeIndexer:[],ObjectTypeProperty:[],QualifiedTypeIdentifier:[],UnionTypeAnnotation:[],VoidTypeAnnotation:[],JSXAttribute:["name","value"],JSXClosingElement:["name"],JSXElement:["openingElement","closingElement","children"],JSXEmptyExpression:[],JSXExpressionContainer:["expression"],JSXIdentifier:[],JSXMemberExpression:["object","property"],JSXNamespacedName:["namespace","name"],JSXOpeningElement:["name","attributes"],JSXSpreadAttribute:["argument"]}},{}],105:[function(require,module,exports){(function(Buffer,__dirname){"use strict";require("./patch");var estraverse=require("estraverse");var codeFrame=require("./helpers/code-frame");var traverse=require("./traverse");var debug=require("debug/node");var acorn=require("acorn-6to5");var path=require("path");var util=require("util");var fs=require("fs");var t=require("./types");var each=require("lodash/collection/each");var isNumber=require("lodash/lang/isNumber");var isString=require("lodash/lang/isString");var isRegExp=require("lodash/lang/isRegExp");var isEmpty=require("lodash/lang/isEmpty");var clone=require("lodash/lang/clone");var cloneDeep=require("lodash/lang/cloneDeep");var has=require("lodash/object/has");var contains=require("lodash/collection/contains");exports.inherits=util.inherits;exports.debug=debug("6to5");exports.canCompile=function(filename,altExts){var exts=altExts||exports.canCompile.EXTENSIONS;var ext=path.extname(filename);return contains(exts,ext)};exports.canCompile.EXTENSIONS=[".js",".jsx",".es6",".es"];exports.isInteger=function(i){return isNumber(i)&&i%1===0};exports.resolve=function(loc){try{return require.resolve(loc)}catch(err){return null}};exports.trimRight=function(str){return str.replace(/[\n\s]+$/g,"")};exports.list=function(val){return val?val.split(","):[]};exports.regexify=function(val){if(!val)return new RegExp(/.^/);if(Array.isArray(val))val=val.join("|");if(isString(val))return new RegExp(val);if(isRegExp(val))return val;throw new TypeError("illegal type for regexify")};exports.arrayify=function(val){if(!val)return[];if(isString(val))return exports.list(val);if(Array.isArray(val))return val;throw new TypeError("illegal type for arrayify")};exports.isAbsolute=function(loc){if(!loc)return false;if(loc[0]==="/")return true;if(loc[1]===":"&&loc[2]==="\\")return true;return false};exports.sourceMapToComment=function(map){var json=JSON.stringify(map);var base64=new Buffer(json).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+base64};exports.pushMutatorMap=function(mutatorMap,key,kind,computed,value){var alias;if(t.isIdentifier(key)){alias=key.name;if(computed)alias="computed:"+alias}else if(t.isLiteral(key)){alias=String(key.value)}else{alias=JSON.stringify(traverse.removeProperties(cloneDeep(key)))}var map;if(has(mutatorMap,alias)){map=mutatorMap[alias]}else{map={}}mutatorMap[alias]=map;map._key=key;if(computed){map._computed=true}map[kind]=value};exports.buildDefineProperties=function(mutatorMap){var objExpr=t.objectExpression([]);each(mutatorMap,function(map){var mapNode=t.objectExpression([]);var propNode=t.property("init",map._key,mapNode,map._computed);if(!map.get&&!map.set){map.writable=t.literal(true)}if(map.enumerable===false){delete map.enumerable}else{map.enumerable=t.literal(true)}map.configurable=t.literal(true);each(map,function(node,key){if(key[0]==="_")return;node=clone(node);var inheritNode=node;if(t.isMethodDefinition(node))node=node.value;var prop=t.property("init",t.identifier(key),node);t.inheritsComments(prop,inheritNode);t.removeComments(inheritNode);mapNode.properties.push(prop)});objExpr.properties.push(propNode)});return objExpr};var templateVisitor={enter:function(node,parent,scope,context,nodes){if(t.isIdentifier(node)&&has(nodes,node.name)){return nodes[node.name]}}};exports.template=function(name,nodes,keepExpression){var template=exports.templates[name];if(!template)throw new ReferenceError("unknown template "+name);if(nodes===true){keepExpression=true;nodes=null}template=cloneDeep(template);if(!isEmpty(nodes)){traverse(template,templateVisitor,null,nodes)}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(node)){return node.expression}else{return node}};exports.repeat=function(width,cha){cha=cha||" ";var result="";for(var i=0;i<width;i++){result+=cha}return result};exports.normaliseAst=function(ast,comments,tokens){if(ast&&ast.type==="Program"){return t.file(ast,comments||[],tokens||[])}else{throw new Error("Not a valid ast?")}};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowImportExportEverywhere:opts.allowImportExportEverywhere,allowReturnOutsideFunction:true,ecmaVersion:opts.experimental?7:6,playground:opts.playground,strictMode:opts.strictMode,onComment:comments,locations:true,onToken:tokens,ranges:true});estraverse.attachComments(ast,comments,tokens);ast=exports.normaliseAst(ast,comments,tokens);if(callback){return callback(ast)}else{return ast}}catch(err){if(!err._6to5){err._6to5=true;var message=opts.filename+": "+err.message;var loc=err.loc;if(loc){var frame=codeFrame(code,loc.line,loc.column+1);message+=frame}if(err.stack)err.stack=err.stack.replace(err.message,message);err.message=message}throw err}};exports.parseTemplate=function(loc,code){var ast=exports.parse({filename:loc},code).program;return traverse.removeProperties(ast)};var loadTemplates=function(){var templates={};var templatesLoc=__dirname+"/transformation/templates";if(!fs.existsSync(templatesLoc)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://github.com/6to5/6to5/issues")}each(fs.readdirSync(templatesLoc),function(name){if(name[0]===".")return;var key=path.basename(name,path.extname(name));var loc=templatesLoc+"/"+name;var code=fs.readFileSync(loc,"utf8");templates[key]=exports.parseTemplate(loc,code)});return templates};try{exports.templates=require("../../templates.json")}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err;exports.templates=loadTemplates()}}).call(this,require("buffer").Buffer,"/lib/6to5")},{"../../templates.json":297,"./helpers/code-frame":24,"./patch":28,"./traverse":98,"./types":102,"acorn-6to5":106,buffer:123,"debug/node":158,estraverse:163,fs:121,"lodash/collection/contains":176,"lodash/collection/each":177,"lodash/lang/clone":241,"lodash/lang/cloneDeep":242,"lodash/lang/isEmpty":246,"lodash/lang/isNumber":249,"lodash/lang/isRegExp":252,"lodash/lang/isString":253,"lodash/object/has":259,path:130,util:147}],106:[function(require,module,exports){(function(root,mod){if(typeof exports=="object"&&typeof module=="object")return mod(exports);if(typeof define=="function"&&define.amd)return define(["exports"],mod);mod(root.acorn||(root.acorn={}))})(this,function(exports){"use strict";exports.version="0.11.1";var options,input,inputLen,sourceFile;exports.parse=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();var startPos=options.locations?[tokPos,curPosition()]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={playground:false,ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,allowImportExportEverywhere:false,allowHashBang:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};exports.parseExpressionAt=function(inpt,pos,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState(pos);initParserState();return parseExpression()};var isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};function setOptions(opts){options={};for(var opt in defaultOptions)options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];sourceFile=options.sourceFile||null;if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){tokens.push(token)}}if(isArray(options.onComment)){var comments=options.onComment;options.onComment=function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation;comment.loc.start=startLoc;comment.loc.end=endLoc}if(options.ranges)comment.range=[start,end];comments.push(comment)}}if(options.strictMode){strict=true}if(options.ecmaVersion>=6){isKeyword=isEcma6Keyword}else{isKeyword=isEcma5AndLessKeyword}}var getLineInfo=exports.getLineInfo=function(input,offset){for(var line=1,cur=0;;){lineBreak.lastIndex=cur;var match=lineBreak.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length}else break}return{line:line,column:offset-cur}};function Token(){this.type=tokType;this.value=tokVal;this.start=tokStart;this.end=tokEnd;if(options.locations){this.loc=new SourceLocation;this.loc.end=tokEndLoc}if(options.ranges)this.range=[tokStart,tokEnd]}exports.Token=Token;exports.tokenize=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();skipSpace();function getToken(){lastEnd=tokEnd;readToken();return new Token}getToken.jumpTo=function(pos,exprAllowed){tokPos=pos;if(options.locations){tokCurLine=1;tokLineStart=lineBreak.lastIndex=0;var match;while((match=lineBreak.exec(input))&&match.index<pos){++tokCurLine;tokLineStart=match.index+match[0].length}}tokExprAllowed=!!exprAllowed;skipSpace()};getToken.current=function(){return new Token};if(typeof Symbol!=="undefined"){getToken[Symbol.iterator]=function(){return{next:function(){var token=getToken();return{done:token.type===_eof,value:token}}}}}getToken.options=options;return getToken};var tokPos;var tokStart,tokEnd;var tokStartLoc,tokEndLoc;var tokType,tokVal;var tokContext,tokExprAllowed;var tokCurLine,tokLineStart;var lastStart,lastEnd,lastEndLoc;var inFunction,inGenerator,inAsync,labels,strict,inXJSChild,inXJSTag,inType;function initParserState(){lastStart=lastEnd=tokPos;if(options.locations)lastEndLoc=curPosition();inFunction=inGenerator=inAsync=false;labels=[];skipSpace();readToken()}function raise(pos,message){var loc=getLineInfo(input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=tokPos;throw err}var empty=[];var _num={type:"num"},_regexp={type:"regexp"},_string={type:"string"};var _name={type:"name"},_eof={type:"eof"};var _jsxName={type:"jsxName"};var _xjsName={type:"xjsName"},_xjsText={type:"xjsText"};var _break={keyword:"break"},_case={keyword:"case",beforeExpr:true},_catch={keyword:"catch"};var _continue={keyword:"continue"},_debugger={keyword:"debugger"},_default={keyword:"default"};var _do={keyword:"do",isLoop:true},_else={keyword:"else",beforeExpr:true};var _finally={keyword:"finally"},_for={keyword:"for",isLoop:true},_function={keyword:"function"};var _if={keyword:"if"},_return={keyword:"return",beforeExpr:true},_switch={keyword:"switch"};var _throw={keyword:"throw",beforeExpr:true},_try={keyword:"try"},_var={keyword:"var"};var _let={keyword:"let"},_const={keyword:"const"};var _while={keyword:"while",isLoop:true},_with={keyword:"with"},_new={keyword:"new",beforeExpr:true};var _this={keyword:"this"};var _class={keyword:"class"},_extends={keyword:"extends",beforeExpr:true};var _export={keyword:"export"},_import={keyword:"import"};var _yield={keyword:"yield",beforeExpr:true};var _null={keyword:"null",atomValue:null},_true={keyword:"true",atomValue:true};var _false={keyword:"false",atomValue:false};var _in={keyword:"in",binop:7,beforeExpr:true};var keywordTypes={"break":_break,"case":_case,"catch":_catch,"continue":_continue,"debugger":_debugger,"default":_default,"do":_do,"else":_else,"finally":_finally,"for":_for,"function":_function,"if":_if,"return":_return,"switch":_switch,"throw":_throw,"try":_try,"var":_var,let:_let,"const":_const,"while":_while,"with":_with,"null":_null,"true":_true,"false":_false,"new":_new,"in":_in,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":_this,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":_class,"extends":_extends,"export":_export,"import":_import,"yield":_yield};var _bracketL={type:"[",beforeExpr:true},_bracketR={type:"]"},_braceL={type:"{",beforeExpr:true};var _braceR={type:"}"},_parenL={type:"(",beforeExpr:true},_parenR={type:")"};var _comma={type:",",beforeExpr:true},_semi={type:";",beforeExpr:true};var _colon={type:":",beforeExpr:true},_dot={type:"."},_question={type:"?",beforeExpr:true};var _arrow={type:"=>",beforeExpr:true},_template={type:"template"};var _ellipsis={type:"...",beforeExpr:true};var _backQuote={type:"`"},_dollarBraceL={type:"${",beforeExpr:true};var _jsxText={type:"jsxText"};var _paamayimNekudotayim={type:"::",beforeExpr:true};var _at={type:"@"};var _hash={type:"#"};var _slash={binop:10,beforeExpr:true},_eq={isAssign:true,beforeExpr:true};var _assign={isAssign:true,beforeExpr:true};var _incDec={postfix:true,prefix:true,isUpdate:true},_prefix={prefix:true,beforeExpr:true};var _logicalOR={binop:1,beforeExpr:true};var _logicalAND={binop:2,beforeExpr:true};var _bitwiseOR={binop:3,beforeExpr:true};var _bitwiseXOR={binop:4,beforeExpr:true};var _bitwiseAND={binop:5,beforeExpr:true};var _equality={binop:6,beforeExpr:true};var _relational={binop:7,beforeExpr:true};var _bitShift={binop:8,beforeExpr:true};var _plusMin={binop:9,prefix:true,beforeExpr:true};var _modulo={binop:10,beforeExpr:true};var _star={binop:10,beforeExpr:true};var _exponent={binop:11,beforeExpr:true,rightAssociative:true};var _jsxTagStart={type:"jsxTagStart"},_jsxTagEnd={type:"jsxTagEnd"};exports.tokTypes={bracketL:_bracketL,bracketR:_bracketR,braceL:_braceL,braceR:_braceR,parenL:_parenL,parenR:_parenR,comma:_comma,semi:_semi,colon:_colon,dot:_dot,ellipsis:_ellipsis,question:_question,slash:_slash,eq:_eq,name:_name,eof:_eof,num:_num,regexp:_regexp,string:_string,paamayimNekudotayim:_paamayimNekudotayim,exponent:_exponent,at:_at,hash:_hash,arrow:_arrow,template:_template,star:_star,assign:_assign,backQuote:_backQuote,dollarBraceL:_dollarBraceL};for(var kw in keywordTypes)exports.tokTypes["_"+kw]=keywordTypes[kw];var isReservedWord3=function anonymous(str){switch(str.length){case 6:switch(str){case"double":case"export":case"import":case"native":case"public":case"static":case"throws":return true}return false;case 4:switch(str){case"byte":case"char":case"enum":case"goto":case"long":return true}return false;case 5:switch(str){case"class":case"final":case"float":case"short":case"super":return true}return false;case 7:switch(str){case"boolean":case"extends":case"package":case"private":return true}return false;case 9:switch(str){case"interface":case"protected":case"transient":return true}return false;case 8:switch(str){case"abstract":case"volatile":return true}return false;case 10:return str==="implements";case 3:return str==="int";case 12:return str==="synchronized"}};var isReservedWord5=function anonymous(str){switch(str.length){case 5:switch(str){case"class":case"super":case"const":return true}return false;case 6:switch(str){case"export":case"import":return true}return false;case 4:return str==="enum";case 7:return str==="extends"}};var isStrictReservedWord=function anonymous(str){switch(str.length){case 9:switch(str){case"interface":case"protected":return true}return false;case 7:switch(str){case"package":case"private":return true}return false;case 6:switch(str){case"public":case"static":return true}return false;case 10:return str==="implements";case 3:return str==="let";case 5:return str==="yield"}};var isStrictBadIdWord=function anonymous(str){switch(str){case"eval":case"arguments":return true}return false};var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var isEcma5AndLessKeyword=function anonymous(str){switch(str.length){case 4:switch(str){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 5:switch(str){case"break":case"catch":case"throw":case"while":case"false":return true}return false;case 3:switch(str){case"for":case"try":case"var":case"new":return true}return false;case 6:switch(str){case"return":case"switch":case"typeof":case"delete":return true}return false;case 8:switch(str){case"continue":case"debugger":case"function":return true}return false;case 2:switch(str){case"do":case"if":case"in":return true}return false;case 7:switch(str){case"default":case"finally":return true}return false;case 10:return str==="instanceof"}};var ecma6AndLessKeywords=ecma5AndLessKeywords+" let const class extends export import yield";var isEcma6Keyword=function anonymous(str){switch(str.length){case 5:switch(str){case"break":case"catch":case"throw":case"while":case"false":case"const":case"class":case"yield":return true}return false;case 4:switch(str){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 6:switch(str){case"return":case"switch":case"typeof":case"delete":case"export":case"import":return true}return false;case 3:switch(str){case"for":case"try":case"var":case"new":case"let":return true}return false;case 8:switch(str){case"continue":case"debugger":case"function":return true}return false;case 7:switch(str){case"default":case"finally":case"extends":return true}return false;case 2:switch(str){case"do":case"if":case"in":return true}return false;case 10:return str==="instanceof"}};var isKeyword=isEcma5AndLessKeyword;var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ"; var nonASCIIidentifierChars="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");var decimalNumber=/^\d+$/;var hexNumber=/^[\da-fA-F]+$/;var newline=/[\n\r\u2028\u2029]/;function isNewLine(code){return code===10||code===13||code===8232||code==8233}var lineBreak=/\r\n|[\n\r\u2028\u2029]/g;var isIdentifierStart=exports.isIdentifierStart=function(code){if(code<65)return code===36;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))};var isIdentifierChar=exports.isIdentifierChar=function(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))};function Position(line,col){this.line=line;this.column=col}Position.prototype.offset=function(n){return new Position(this.line,this.column+n)};function curPosition(){return new Position(tokCurLine,tokPos-tokLineStart)}function initTokenState(pos){if(pos){tokPos=pos;tokLineStart=Math.max(0,input.lastIndexOf("\n",pos));tokCurLine=input.slice(0,tokLineStart).split(newline).length}else{tokCurLine=1;tokPos=tokLineStart=0}tokType=_eof;tokContext=[b_stat];tokExprAllowed=true;inType=strict=false;if(tokPos===0&&options.allowHashBang&&input.slice(0,2)==="#!"){skipLineComment(2)}}var b_stat={token:"{",isExpr:false},b_expr={token:"{",isExpr:true},b_tmpl={token:"${",isExpr:true};var p_stat={token:"(",isExpr:false},p_expr={token:"(",isExpr:true};var q_tmpl={token:"`",isExpr:true},f_expr={token:"function",isExpr:true};var j_oTag={token:"<tag",isExpr:false},j_cTag={token:"</tag",isExpr:false},j_expr={token:"<tag>...</tag>",isExpr:true};function curTokContext(){return tokContext[tokContext.length-1]}function braceIsBlock(prevType){var parent;if(prevType===_colon&&(parent=curTokContext()).token=="{")return!parent.isExpr;if(prevType===_return)return newline.test(input.slice(lastEnd,tokStart));if(prevType===_else||prevType===_semi||prevType===_eof)return true;if(prevType==_braceL)return curTokContext()===b_stat;return!tokExprAllowed}function finishToken(type,val){tokEnd=tokPos;if(options.locations)tokEndLoc=curPosition();var prevType=tokType,preserveSpace=false;tokType=type;tokVal=val;if(type===_parenR||type===_braceR){var out=tokContext.pop();if(out===b_tmpl){preserveSpace=tokExprAllowed=true}else if(out===b_stat&&curTokContext()===f_expr){tokContext.pop();tokExprAllowed=false}else{tokExprAllowed=!(out&&out.isExpr)}}else if(type===_braceL){switch(curTokContext()){case j_oTag:tokContext.push(b_expr);break;case j_expr:tokContext.push(b_tmpl);break;default:tokContext.push(braceIsBlock(prevType)?b_stat:b_expr)}tokExprAllowed=true}else if(type===_dollarBraceL){tokContext.push(b_tmpl);tokExprAllowed=true}else if(type==_parenL){var statementParens=prevType===_if||prevType===_for||prevType===_with||prevType===_while;tokContext.push(statementParens?p_stat:p_expr);tokExprAllowed=true}else if(type==_incDec){}else if(type.keyword&&prevType==_dot){tokExprAllowed=false}else if(type==_function){if(curTokContext()!==b_stat){tokContext.push(f_expr)}tokExprAllowed=false}else if(type===_backQuote){if(curTokContext()===q_tmpl){tokContext.pop()}else{tokContext.push(q_tmpl);preserveSpace=true}tokExprAllowed=false}else if(type===_jsxTagStart){tokContext.push(j_expr);tokContext.push(j_oTag);tokExprAllowed=false}else if(type===_jsxTagEnd){var out=tokContext.pop();if(out===j_oTag&&prevType===_slash||out===j_cTag){tokContext.pop();preserveSpace=tokExprAllowed=curTokContext()===j_expr}else{preserveSpace=tokExprAllowed=true}}else if(type===_jsxText){preserveSpace=tokExprAllowed=true}else if(type===_slash&&prevType===_jsxTagStart){tokContext.length-=2;tokContext.push(j_cTag);tokExprAllowed=false}else{tokExprAllowed=type.beforeExpr}if(!preserveSpace)skipSpace()}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&curPosition();var start=tokPos,end=input.indexOf("*/",tokPos+=2);if(end===-1)raise(tokPos-2,"Unterminated comment");tokPos=end+2;if(options.locations){lineBreak.lastIndex=start;var match;while((match=lineBreak.exec(input))&&match.index<tokPos){++tokCurLine;tokLineStart=match.index+match[0].length}}if(options.onComment)options.onComment(true,input.slice(start+2,end),start,tokPos,startLoc,options.locations&&curPosition())}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&curPosition();var ch=input.charCodeAt(tokPos+=startSkip);while(tokPos<inputLen&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++tokPos;ch=input.charCodeAt(tokPos)}if(options.onComment)options.onComment(false,input.slice(start+startSkip,tokPos),start,tokPos,startLoc,options.locations&&curPosition())}function skipSpace(){while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(ch===32){++tokPos}else if(ch===13){++tokPos;var next=input.charCodeAt(tokPos);if(next===10){++tokPos}if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch===10||ch===8232||ch===8233){++tokPos;if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch>8&&ch<14){++tokPos}else if(ch===47){var next=input.charCodeAt(tokPos+1);if(next===42){skipBlockComment()}else if(next===47){skipLineComment(2)}else break}else if(ch===160){++tokPos}else if(ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++tokPos}else{break}}}function readToken_dot(){var next=input.charCodeAt(tokPos+1);if(next>=48&&next<=57)return readNumber(true);var next2=input.charCodeAt(tokPos+2);if(options.playground&&next===63){tokPos+=2;return finishToken(_dotQuestion)}else if(options.ecmaVersion>=6&&next===46&&next2===46){tokPos+=3;return finishToken(_ellipsis)}else{++tokPos;return finishToken(_dot)}}function readToken_slash(){var next=input.charCodeAt(tokPos+1);if(tokExprAllowed){++tokPos;return readRegexp()}if(next===61)return finishOp(_assign,2);return finishOp(_slash,1)}function readToken_modulo(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_modulo,1)}function readToken_mult(){var type=_star;var width=1;var next=input.charCodeAt(tokPos+1);if(options.ecmaVersion>=7&&next===42){width++;next=input.charCodeAt(tokPos+2);type=_exponent}if(next===61){width++;type=_assign}return finishOp(type,width)}function readToken_pipe_amp(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(options.playground&&input.charCodeAt(tokPos+2)===61)return finishOp(_assign,3);return finishOp(code===124?_logicalOR:_logicalAND,2)}if(next===61)return finishOp(_assign,2);return finishOp(code===124?_bitwiseOR:_bitwiseAND,1)}function readToken_caret(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_bitwiseXOR,1)}function readToken_plus_min(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(next==45&&input.charCodeAt(tokPos+2)==62&&newline.test(input.slice(lastEnd,tokPos))){skipLineComment(3);skipSpace();return readToken()}return finishOp(_incDec,2)}if(next===61)return finishOp(_assign,2);return finishOp(_plusMin,1)}function readToken_lt_gt(code){var next=input.charCodeAt(tokPos+1);var size=1;if(!inType&&next===code){size=code===62&&input.charCodeAt(tokPos+2)===62?3:2;if(input.charCodeAt(tokPos+size)===61)return finishOp(_assign,size+1);return finishOp(_bitShift,size)}if(next==33&&code==60&&input.charCodeAt(tokPos+2)==45&&input.charCodeAt(tokPos+3)==45){skipLineComment(4);skipSpace();return readToken()}if(!inType){if(tokExprAllowed&&code===60){++tokPos;return finishToken(_jsxTagStart)}if(code===62){var context=curTokContext();if(context===j_oTag||context===j_cTag){++tokPos;return finishToken(_jsxTagEnd)}}}if(next===61)size=input.charCodeAt(tokPos+2)===61?3:2;return finishOp(_relational,size)}function readToken_eq_excl(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_equality,input.charCodeAt(tokPos+2)===61?3:2);if(code===61&&next===62&&options.ecmaVersion>=6){tokPos+=2;return finishToken(_arrow)}return finishOp(code===61?_eq:_prefix,1)}function getTemplateToken(code){if(tokType===_string){if(code===96){++tokPos;return finishToken(_bquote)}else if(code===36&&input.charCodeAt(tokPos+1)===123){tokPos+=2;return finishToken(_dollarBraceL)}}return readTmplString()}function getTokenFromCode(code){switch(code){case 46:return readToken_dot();case 40:++tokPos;return finishToken(_parenL);case 41:++tokPos;return finishToken(_parenR);case 59:++tokPos;return finishToken(_semi);case 44:++tokPos;return finishToken(_comma);case 91:++tokPos;return finishToken(_bracketL);case 93:++tokPos;return finishToken(_bracketR);case 123:++tokPos;return finishToken(_braceL);case 125:++tokPos;return finishToken(_braceR);case 63:++tokPos;return finishToken(_question);case 64:if(options.playground){++tokPos;return finishToken(_at)}case 35:if(options.playground){++tokPos;return finishToken(_hash)}case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_paamayimNekudotayim)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return finishToken(_backQuote)}else{return false}case 48:var next=input.charCodeAt(tokPos+1);if(next===120||next===88)return readRadixNumber(16);if(options.ecmaVersion>=6){if(next===111||next===79)return readRadixNumber(8);if(next===98||next===66)return readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(false);case 34:case 39:return inXJSTag?readXJSStringLiteral():readString(code);case 47:return readToken_slash();case 37:return readToken_modulo();case 42:return readToken_mult();case 124:case 38:return readToken_pipe_amp(code);case 94:return readToken_caret();case 43:case 45:return readToken_plus_min(code);case 60:case 62:return readToken_lt_gt(code);case 61:case 33:return readToken_eq_excl(code);case 126:return finishOp(_prefix,1)}return false}function readToken(){tokStart=tokPos;if(options.locations)tokStartLoc=curPosition();if(tokPos>=inputLen)return finishToken(_eof);var context=curTokContext();if(context===q_tmpl){return readTmplToken()}if(context===j_expr){return readJSXToken()}var code=input.charCodeAt(tokPos);if(context===j_oTag||context===j_cTag){if(isIdentifierStart(code))return readJSXWord()}else if(context===j_expr){return readJSXToken()}else{if(isIdentifierStart(code)||code===92)return readWord()}var tok=getTokenFromCode(code);if(tok===false){var ch=String.fromCharCode(code);if(ch==="\\"||nonASCIIidentifierStart.test(ch))return readWord();raise(tokPos,"Unexpected character '"+ch+"'")}return tok}function finishOp(type,size,shouldSkipSpace){var str=input.slice(tokPos,tokPos+size);tokPos+=size;finishToken(type,str,shouldSkipSpace)}var regexpUnicodeSupport=false;try{new RegExp("￿","u");regexpUnicodeSupport=true}catch(e){}function readRegexp(){var content="",escaped,inClass,start=tokPos;for(;;){if(tokPos>=inputLen)raise(start,"Unterminated regular expression");var ch=nextChar();if(newline.test(ch))raise(start,"Unterminated regular expression");if(!escaped){if(ch==="[")inClass=true;else if(ch==="]"&&inClass)inClass=false;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}else escaped=false;++tokPos}var content=input.slice(start,tokPos);++tokPos;var mods=readWord1();var tmp=content;if(mods){var validFlags=/^[gmsiy]*$/;if(options.ecmaVersion>=6)validFlags=/^[gmsiyu]*$/;if(!validFlags.test(mods))raise(start,"Invalid regular expression flag");if(mods.indexOf("u")>=0&&!regexpUnicodeSupport){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(tmp)}catch(e){if(e instanceof SyntaxError)raise(start,"Error parsing regular expression: "+e.message);raise(e)}try{var value=new RegExp(content,mods)}catch(err){value=null}return finishToken(_regexp,{pattern:content,flags:mods,value:value})}function readInt(radix,len){var start=tokPos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=input.charCodeAt(tokPos),val;if(code>=97)val=code-97+10;else if(code>=65)val=code-65+10;else if(code>=48&&code<=57)val=code-48;else val=Infinity;if(val>=radix)break;++tokPos;total=total*radix+val}if(tokPos===start||len!=null&&tokPos-start!==len)return null;return total}function readRadixNumber(radix){tokPos+=2;var val=readInt(radix);if(val==null)raise(tokStart+2,"Expected number in radix "+radix);if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");return finishToken(_num,val)}function readNumber(startsWithDot){var start=tokPos,isFloat=false,octal=input.charCodeAt(tokPos)===48;if(!startsWithDot&&readInt(10)===null)raise(start,"Invalid number");if(input.charCodeAt(tokPos)===46){++tokPos;readInt(10);isFloat=true}var next=input.charCodeAt(tokPos);if(next===69||next===101){next=input.charCodeAt(++tokPos);if(next===43||next===45)++tokPos;if(readInt(10)===null)raise(start,"Invalid number");isFloat=true}if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");var str=input.slice(start,tokPos),val;if(isFloat)val=parseFloat(str);else if(!octal||str.length===1)val=parseInt(str,10);else if(/[89]/.test(str)||strict)raise(start,"Invalid number");else val=parseInt(str,8);return finishToken(_num,val)}function readCodePoint(){var ch=input.charCodeAt(tokPos),code;if(ch===123){if(options.ecmaVersion<6)unexpected();++tokPos;code=readHexChar(input.indexOf("}",tokPos)-tokPos);++tokPos;if(code>1114111)unexpected()}else{code=readHexChar(4)}if(code<=65535){return String.fromCharCode(code)}var cu1=(code-65536>>10)+55296;var cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function readString(quote){var isJSX=curTokContext()===j_oTag;var out="",chunkStart=++tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===quote)break;if(ch===92&&!isJSX){out+=input.slice(chunkStart,tokPos);out+=readEscapedChar();chunkStart=tokPos}else if(ch===38&&isJSX){out+=input.slice(chunkStart,tokPos);out+=readJSXEntity();chunkStart=tokPos}else{if(isNewLine(ch))raise(tokStart,"Unterminated string constant");++tokPos}}out+=input.slice(chunkStart,tokPos++);return finishToken(_string,out)}function readTmplToken(){var out="",chunkStart=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated template");var ch=input.charCodeAt(tokPos);if(ch===96||ch===36&&input.charCodeAt(tokPos+1)===123){if(tokPos===tokStart&&tokType===_template){if(ch===36){tokPos+=2;return finishToken(_dollarBraceL)}else{++tokPos;return finishToken(_backQuote)}}out+=input.slice(chunkStart,tokPos);return finishToken(_template,out)}if(ch===92){out+=input.slice(chunkStart,tokPos);out+=readEscapedChar();chunkStart=tokPos}else if(isNewLine(ch)){out+=input.slice(chunkStart,tokPos);++tokPos;if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;out+="\n"}else{out+=String.fromCharCode(ch)}if(options.locations){++tokCurLine;tokLineStart=tokPos}chunkStart=tokPos}else{++tokPos}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",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:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readJSXEntity(){var str="",count=0,entity;var ch=input[tokPos];if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=input[tokPos++];if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}return entity}function readJSXToken(){var out="",start=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated JSX contents");var ch=input.charCodeAt(tokPos);switch(ch){case 123:case 60:if(tokPos===start){return getTokenFromCode(ch)}return finishToken(_jsxText,out);case 38:out+=readJSXEntity();break;default:++tokPos;if(isNewLine(ch)){if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;ch=10}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=String.fromCharCode(ch)}}}function readEscapedChar(){var ch=input.charCodeAt(++tokPos);var octal=/^[0-7]+/.exec(input.slice(tokPos,tokPos+3));if(octal)octal=octal[0];while(octal&&parseInt(octal,8)>255)octal=octal.slice(0,-1);if(octal==="0")octal=null;++tokPos;if(octal){if(strict)raise(tokPos-2,"Octal literal in strict mode");tokPos+=octal.length-1;return String.fromCharCode(parseInt(octal,8))}else{switch(ch){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(readHexChar(2));case 117:return readCodePoint();case 116:return" ";case 98:return"\b";case 118:return" ";case 102:return"\f";case 48:return"\x00";case 13:if(input.charCodeAt(tokPos)===10)++tokPos;case 10:if(options.locations){tokLineStart=tokPos;++tokCurLine}return"";default:return String.fromCharCode(ch)}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",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:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readXJSEntity(){var str="",count=0,entity;var ch=nextChar();if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}return entity}function readXJSText(stopChars){var str="";while(tokPos<inputLen){var ch=nextChar();if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=readXJSEntity()}else{++tokPos;if(ch==="\r"&&nextChar()==="\n"){str+=ch;++tokPos;ch="\n"}if(ch==="\n"&&options.locations){tokLineStart=tokPos;++tokCurLine}str+=ch}}return finishToken(_xjsText,str)}function readXJSStringLiteral(){var quote=input.charCodeAt(tokPos);if(quote!==34&&quote!==39){raise("String literal must starts with a quote")}++tokPos;readXJSText([String.fromCharCode(quote)]);if(quote!==input.charCodeAt(tokPos)){unexpected()}++tokPos;return finishToken(tokType,tokVal)}function readHexChar(len){var n=readInt(16,len);if(n===null)raise(tokStart,"Bad character escape sequence");return n}var containsEsc;function readWord1(){containsEsc=false;var word="",first=true,chunkStart=tokPos;for(;;){var ch=input.charCodeAt(tokPos);if(isIdentifierChar(ch)){++tokPos}else if(ch===92){containsEsc=true;word+=input.slice(chunkStart,tokPos);if(input.charCodeAt(++tokPos)!=117)raise(tokPos,"Expecting Unicode escape sequence \\uXXXX");++tokPos;var esc=readHexChar(4);var escStr=String.fromCharCode(esc);if(!escStr)raise(tokPos-1,"Invalid Unicode escape");if(!(first?isIdentifierStart(esc):isIdentifierChar(esc)))raise(tokPos-4,"Invalid Unicode escape");word+=escStr;chunkStart=tokPos}else{break}first=false}return word+input.slice(chunkStart,tokPos)}function readWord(){var word=readWord1();var type=inXJSTag?_xjsName:_name;if(!containsEsc&&isKeyword(word))type=keywordTypes[word];return finishToken(type,word)}function readJSXWord(){var ch,start=tokPos;do{ch=input.charCodeAt(++tokPos)}while(isIdentifierChar(ch)||ch===45);return finishToken(_jsxName,input.slice(start,tokPos))}function next(){if(options.onToken)options.onToken(new Token);lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;readToken()}function setStrict(strct){strict=strct;if(tokType!==_num&&tokType!==_string)return;tokPos=tokStart;if(options.locations){while(tokPos<tokLineStart){tokLineStart=input.lastIndexOf("\n",tokLineStart-2)+1;--tokCurLine}}skipSpace();readToken()}function Node(){this.type=null;this.start=tokStart;this.end=null}exports.Node=Node;function SourceLocation(){this.start=tokStartLoc;this.end=null;if(sourceFile!==null)this.source=sourceFile}function startNode(){var node=new exports.Node;if(options.locations)node.loc=new SourceLocation;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[tokStart,0];return node}function storeCurrentPos(){return options.locations?[tokStart,tokStartLoc]:tokStart}function startNodeAt(pos){var node=new exports.Node,start=pos;if(options.locations){node.loc=new SourceLocation;node.loc.start=start[1];start=pos[0]}node.start=start;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[start,0];return node}function finishNode(node,type){node.type=type;node.end=lastEnd;if(options.locations)node.loc.end=lastEndLoc;if(options.ranges)node.range[1]=lastEnd;return node}function finishNodeAt(node,type,pos){if(options.locations){node.loc.end=pos[1];pos=pos[0]}node.type=type;node.end=pos;if(options.ranges)node.range[1]=pos;return node}function isUseStrict(stmt){return options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.value==="use strict"}function eat(type){if(tokType===type){next();return true}else{return false}}function isContextual(name){return tokType===_name&&tokVal===name}function eatContextual(name){return tokVal===name&&eat(_name)}function expectContextual(name){if(!eatContextual(name))unexpected()}function canInsertSemicolon(){return!options.strictSemicolons&&(tokType===_eof||tokType===_braceR||newline.test(input.slice(lastEnd,tokStart)))}function semicolon(){if(!eat(_semi)&&!canInsertSemicolon())unexpected()}function expect(type){eat(type)||unexpected()}function nextChar(){return input.charAt(tokPos)}function unexpected(pos){raise(pos!=null?pos:tokStart,"Unexpected token")}function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)}function toAssignable(node){if(options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":case"MemberExpression":case"VirtualPropertyExpression":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":node.type="ObjectPattern";for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(prop.kind!=="init")raise(prop.key.start,"Object pattern can't contain getter or setter");toAssignable(prop.value)}break;case"ArrayExpression":node.type="ArrayPattern";toAssignableList(node.elements);break;case"AssignmentExpression":if(node.operator==="="){node.type="AssignmentPattern"}else{raise(node.left.end,"Only '=' operator can be used for specifying default value.")}break;default:raise(node.start,"Assigning to rvalue")}}return node}function toAssignableList(exprList){if(exprList.length){for(var i=0;i<exprList.length-1;i++){toAssignable(exprList[i])}var last=exprList[exprList.length-1];switch(last.type){case"RestElement":break;case"SpreadElement":last.type="RestElement";var arg=last.argument;toAssignable(arg);if(arg.type!=="Identifier"&&arg.type!=="ArrayPattern")unexpected(arg.start);break;default:toAssignable(last)}}return exprList}function parseSpread(refShorthandDefaultPos){var node=startNode();next();node.argument=parseMaybeAssign(refShorthandDefaultPos);return finishNode(node,"SpreadElement")}function parseRest(){var node=startNode();next();node.argument=tokType===_name||tokType===_bracketL?parseAssignableAtom():unexpected();return finishNode(node,"RestElement")}function parseAssignableAtom(){if(options.ecmaVersion<6)return parseIdent();switch(tokType){case _name:return parseIdent();case _bracketL:var node=startNode();next();node.elements=parseAssignableList(_bracketR,true);return finishNode(node,"ArrayPattern");case _braceL:return parseObj(true);default:unexpected()}}function parseAssignableList(close,allowEmpty){var elts=[],first=true;while(!eat(close)){first?first=false:expect(_comma);if(tokType===_ellipsis){elts.push(parseAssignableListItemTypes(parseRest()));expect(close);break}var elem;if(allowEmpty&&tokType===_comma){elem=null}else{var left=parseAssignableAtom();parseAssignableListItemTypes(left);elem=parseMaybeDefault(null,left)}elts.push(elem)}return elts}function parseAssignableListItemTypes(param){if(eat(_question)){param.optional=true}if(tokType===_colon){param.typeAnnotation=parseTypeAnnotation()}finishNode(param,param.type);return param}function parseMaybeDefault(startPos,left){left=left||parseAssignableAtom();if(!eat(_eq))return left;var node=startPos?startNodeAt(startPos):startNode();node.operator="=";node.left=left;node.right=parseMaybeAssign();return finishNode(node,"AssignmentPattern")}function checkFunctionParam(param,nameHash){switch(param.type){case"Identifier":if(isStrictReservedWord(param.name)||isStrictBadIdWord(param.name))raise(param.start,"Defining '"+param.name+"' in strict mode");if(has(nameHash,param.name))raise(param.start,"Argument name clash in strict mode");nameHash[param.name]=true;break;case"ObjectPattern":for(var i=0;i<param.properties.length;i++)checkFunctionParam(param.properties[i].value,nameHash);break;case"ArrayPattern":for(var i=0;i<param.elements.length;i++){var elem=param.elements[i];if(elem)checkFunctionParam(elem,nameHash)}break;case"RestElement":return checkFunctionParam(param.argument,nameHash)}}function checkPropClash(prop,propHash){if(options.ecmaVersion>=6)return;var key=prop.key,name;switch(key.type){case"Identifier":name=key.name;break;case"Literal":name=String(key.value);break;default:return}var kind=prop.kind||"init",other;if(has(propHash,name)){other=propHash[name];var isGetSet=kind!=="init";if((strict||isGetSet)&&other[kind]||!(isGetSet^other.init))raise(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}}other[kind]=true}function checkLVal(expr,isBinding){switch(expr.type){case"Identifier":if(strict&&(isStrictBadIdWord(expr.name)||isStrictReservedWord(expr.name)))raise(expr.start,(isBinding?"Binding ":"Assigning to ")+expr.name+" in strict mode");break;case"MemberExpression":if(isBinding)raise(expr.start,"Binding to member expression");break;case"ObjectPattern":for(var i=0;i<expr.properties.length;i++){var prop=expr.properties[i];if(prop.type==="Property")prop=prop.value;checkLVal(prop,isBinding)}break;case"ArrayPattern":for(var i=0;i<expr.elements.length;i++){var elem=expr.elements[i];if(elem)checkLVal(elem,isBinding)}break;case"AssignmentPattern":checkLVal(expr.left);break;case"SpreadProperty":case"VirtualPropertyExpression":break;case"RestElement":checkLVal(expr.argument);break;default:raise(expr.start,"Assigning to rvalue")}}function parseTopLevel(node){var first=true;if(!node.body)node.body=[];while(tokType!==_eof){var stmt=parseStatement(true,true);node.body.push(stmt);if(first&&isUseStrict(stmt))setStrict(true);first=false}next();return finishNode(node,"Program")}var loopLabel={kind:"loop"},switchLabel={kind:"switch"};function parseStatement(declaration,topLevel){var starttype=tokType,node=startNode(); switch(starttype){case _break:case _continue:return parseBreakContinueStatement(node,starttype.keyword);case _debugger:return parseDebuggerStatement(node);case _do:return parseDoStatement(node);case _for:return parseForStatement(node);case _function:if(!declaration&&options.ecmaVersion>=6)unexpected();return parseFunctionStatement(node);case _class:if(!declaration)unexpected();return parseClass(node,true);case _if:return parseIfStatement(node);case _return:return parseReturnStatement(node);case _switch:return parseSwitchStatement(node);case _throw:return parseThrowStatement(node);case _try:return parseTryStatement(node);case _let:case _const:if(!declaration)unexpected();case _var:return parseVarStatement(node,starttype.keyword);case _while:return parseWhileStatement(node);case _with:return parseWithStatement(node);case _braceL:return parseBlock();case _semi:return parseEmptyStatement(node);case _export:case _import:if(!topLevel&&!options.allowImportExportEverywhere)raise(tokStart,"'import' and 'export' may only appear at the top level");return starttype===_import?parseImport(node):parseExport(node);default:var maybeName=tokVal,expr=parseExpression();if(options.ecmaVersion>=7&&starttype===_name&&maybeName==="async"&&tokType===_function&&!canInsertSemicolon()){next();var func=parseFunctionStatement(node);func.async=true;return func}if(starttype===_name&&expr.type==="Identifier"){if(eat(_colon)){return parseLabeledStatement(node,maybeName,expr)}if(options.ecmaVersion>=7&&expr.name==="private"&&tokType===_name){return parsePrivate(node)}else if(expr.name==="declare"){if(tokType===_class||tokType===_name||tokType===_function||tokType===_var){return parseDeclare(node)}}else if(tokType===_name){if(expr.name==="interface"){return parseInterface(node)}else if(expr.name==="type"){return parseTypeAlias(node)}}}if(expr.type==="FunctionExpression"&&expr.async){if(expr.id){expr.type="FunctionDeclaration";return expr}else{unexpected(expr.start+"async function ".length)}}return parseExpressionStatement(node,expr)}}function parseBreakContinueStatement(node,keyword){var isBreak=keyword=="break";next();if(eat(_semi)||canInsertSemicolon())node.label=null;else if(tokType!==_name)unexpected();else{node.label=parseIdent();semicolon()}for(var i=0;i<labels.length;++i){var lab=labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break;if(node.label&&isBreak)break}}if(i===labels.length)raise(node.start,"Unsyntactic "+keyword);return finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}function parseDebuggerStatement(node){next();semicolon();return finishNode(node,"DebuggerStatement")}function parseDoStatement(node){next();labels.push(loopLabel);node.body=parseStatement(false);labels.pop();expect(_while);node.test=parseParenExpression();if(options.ecmaVersion>=6)eat(_semi);else semicolon();return finishNode(node,"DoWhileStatement")}function parseForStatement(node){next();labels.push(loopLabel);expect(_parenL);if(tokType===_semi)return parseFor(node,null);if(tokType===_var||tokType===_let){var init=startNode(),varKind=tokType.keyword,isLet=tokType===_let;next();parseVar(init,true,varKind);finishNode(init,"VariableDeclaration");if((tokType===_in||options.ecmaVersion>=6&&isContextual("of"))&&init.declarations.length===1&&!(isLet&&init.declarations[0].init))return parseForIn(node,init);return parseFor(node,init)}var refShorthandDefaultPos={start:0};var init=parseExpression(true,refShorthandDefaultPos);if(tokType===_in||options.ecmaVersion>=6&&isContextual("of")){toAssignable(init);checkLVal(init);return parseForIn(node,init)}else if(refShorthandDefaultPos.start){unexpected(refShorthandDefaultPos.start)}return parseFor(node,init)}function parseFunctionStatement(node){next();return parseFunction(node,true,false)}function parseIfStatement(node){next();node.test=parseParenExpression();node.consequent=parseStatement(false);node.alternate=eat(_else)?parseStatement(false):null;return finishNode(node,"IfStatement")}function parseReturnStatement(node){if(!inFunction&&!options.allowReturnOutsideFunction)raise(tokStart,"'return' outside of function");next();if(eat(_semi)||canInsertSemicolon())node.argument=null;else{node.argument=parseExpression();semicolon()}return finishNode(node,"ReturnStatement")}function parseSwitchStatement(node){next();node.discriminant=parseParenExpression();node.cases=[];expect(_braceL);labels.push(switchLabel);for(var cur,sawDefault;tokType!=_braceR;){if(tokType===_case||tokType===_default){var isCase=tokType===_case;if(cur)finishNode(cur,"SwitchCase");node.cases.push(cur=startNode());cur.consequent=[];next();if(isCase)cur.test=parseExpression();else{if(sawDefault)raise(lastStart,"Multiple default clauses");sawDefault=true;cur.test=null}expect(_colon)}else{if(!cur)unexpected();cur.consequent.push(parseStatement(true))}}if(cur)finishNode(cur,"SwitchCase");next();labels.pop();return finishNode(node,"SwitchStatement")}function parseThrowStatement(node){next();if(newline.test(input.slice(lastEnd,tokStart)))raise(lastEnd,"Illegal newline after throw");node.argument=parseExpression();semicolon();return finishNode(node,"ThrowStatement")}function parseTryStatement(node){next();node.block=parseBlock();node.handler=null;if(tokType===_catch){var clause=startNode();next();expect(_parenL);clause.param=parseAssignableAtom();checkLVal(clause.param,true);expect(_parenR);clause.guard=null;clause.body=parseBlock();node.handler=finishNode(clause,"CatchClause")}node.guardedHandlers=empty;node.finalizer=eat(_finally)?parseBlock():null;if(!node.handler&&!node.finalizer)raise(node.start,"Missing catch or finally clause");return finishNode(node,"TryStatement")}function parseVarStatement(node,kind){next();parseVar(node,false,kind);semicolon();return finishNode(node,"VariableDeclaration")}function parseWhileStatement(node){next();node.test=parseParenExpression();labels.push(loopLabel);node.body=parseStatement(false);labels.pop();return finishNode(node,"WhileStatement")}function parseWithStatement(node){if(strict)raise(tokStart,"'with' in strict mode");next();node.object=parseParenExpression();node.body=parseStatement(false);return finishNode(node,"WithStatement")}function parseEmptyStatement(node){next();return finishNode(node,"EmptyStatement")}function parseLabeledStatement(node,maybeName,expr){for(var i=0;i<labels.length;++i)if(labels[i].name===maybeName)raise(expr.start,"Label '"+maybeName+"' is already declared");var kind=tokType.isLoop?"loop":tokType===_switch?"switch":null;labels.push({name:maybeName,kind:kind});node.body=parseStatement(true);labels.pop();node.label=expr;return finishNode(node,"LabeledStatement")}function parseExpressionStatement(node,expr){node.expression=expr;semicolon();return finishNode(node,"ExpressionStatement")}function parseParenExpression(){expect(_parenL);var val=parseExpression();expect(_parenR);return val}function parseBlock(allowStrict){var node=startNode(),first=true,oldStrict;node.body=[];expect(_braceL);while(!eat(_braceR)){var stmt=parseStatement(true);node.body.push(stmt);if(first&&allowStrict&&isUseStrict(stmt)){oldStrict=strict;setStrict(strict=true)}first=false}if(oldStrict===false)setStrict(false);return finishNode(node,"BlockStatement")}function parseFor(node,init){node.init=init;expect(_semi);node.test=tokType===_semi?null:parseExpression();expect(_semi);node.update=tokType===_parenR?null:parseExpression();expect(_parenR);node.body=parseStatement(false);labels.pop();return finishNode(node,"ForStatement")}function parseForIn(node,init){var type=tokType===_in?"ForInStatement":"ForOfStatement";next();node.left=init;node.right=parseExpression();expect(_parenR);node.body=parseStatement(false);labels.pop();return finishNode(node,type)}function parseVar(node,noIn,kind){node.declarations=[];node.kind=kind;for(;;){var decl=startNode();decl.id=parseAssignableAtom();checkLVal(decl.id,true);if(tokType===_colon){decl.id.typeAnnotation=parseTypeAnnotation();finishNode(decl.id,decl.id.type)}decl.init=eat(_eq)?parseMaybeAssign(noIn):kind===_const.keyword?unexpected():null;node.declarations.push(finishNode(decl,"VariableDeclarator"));if(!eat(_comma))break}return node}function parseExpression(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseMaybeAssign(noIn,refShorthandDefaultPos);if(tokType===_comma){var node=startNodeAt(start);node.expressions=[expr];while(eat(_comma))node.expressions.push(parseMaybeAssign(noIn,refShorthandDefaultPos));return finishNode(node,"SequenceExpression")}return expr}function parseMaybeAssign(noIn,refShorthandDefaultPos,afterLeftParse){var failOnShorthandAssign;if(!refShorthandDefaultPos){refShorthandDefaultPos={start:0};failOnShorthandAssign=true}else{failOnShorthandAssign=false}var start=storeCurrentPos();var left=parseMaybeConditional(noIn,refShorthandDefaultPos);if(afterLeftParse)afterLeftParse(left);if(tokType.isAssign){var node=startNodeAt(start);node.operator=tokVal;node.left=tokType===_eq?toAssignable(left):left;refShorthandDefaultPos.start=0;checkLVal(left);next();node.right=parseMaybeAssign(noIn);return finishNode(node,"AssignmentExpression")}else if(failOnShorthandAssign&&refShorthandDefaultPos.start){unexpected(refShorthandDefaultPos.start)}return left}function parseMaybeConditional(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseExprOps(noIn,refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;if(eat(_question)){var node=startNodeAt(start);if(options.playground&&eat(_eq)){var left=node.left=toAssignable(expr);if(left.type!=="MemberExpression")raise(left.start,"You can only use member expressions in memoization assignment");node.right=parseMaybeAssign(noIn);node.operator="?=";return finishNode(node,"AssignmentExpression")}node.test=expr;node.consequent=parseMaybeAssign();expect(_colon);node.alternate=parseMaybeAssign(noIn);return finishNode(node,"ConditionalExpression")}return expr}function parseExprOps(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseMaybeUnary(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;return parseExprOp(expr,start,-1,noIn)}function parseExprOp(left,leftStart,minPrec,noIn){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)){if(prec>minPrec){var node=startNodeAt(leftStart);node.left=left;node.operator=tokVal;var op=tokType;next();var start=storeCurrentPos();node.right=parseExprOp(parseMaybeUnary(),start,op.rightAssociative?prec-1:prec,noIn);finishNode(node,op===_logicalOR||op===_logicalAND?"LogicalExpression":"BinaryExpression");return parseExprOp(node,leftStart,minPrec,noIn)}}return left}function parseMaybeUnary(refShorthandDefaultPos){if(tokType.prefix){var node=startNode(),update=tokType.isUpdate;node.operator=tokVal;node.prefix=true;next();node.argument=parseMaybeUnary();if(refShorthandDefaultPos&&refShorthandDefaultPos.start)unexpected(refShorthandDefaultPos.start);if(update)checkLVal(node.argument);else if(strict&&node.operator==="delete"&&node.argument.type==="Identifier")raise(node.start,"Deleting local variable in strict mode");return finishNode(node,update?"UpdateExpression":"UnaryExpression")}var start=storeCurrentPos();var expr=parseExprSubscripts(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;while(tokType.postfix&&!canInsertSemicolon()){var node=startNodeAt(start);node.operator=tokVal;node.prefix=false;node.argument=expr;checkLVal(expr);next();expr=finishNode(node,"UpdateExpression")}return expr}function parseExprSubscripts(refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseExprAtom(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;return parseSubscripts(expr,start)}function parseSubscripts(base,start,noCalls){if(options.playground&&eat(_hash)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return parseSubscripts(finishNode(node,"BindMemberExpression"),start,noCalls)}else if(eat(_paamayimNekudotayim)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);return parseSubscripts(finishNode(node,"VirtualPropertyExpression"),start,noCalls)}else if(eat(_dot)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);node.computed=false;return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(eat(_bracketL)){var node=startNodeAt(start);node.object=base;node.property=parseExpression();node.computed=true;expect(_bracketR);return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(!noCalls&&eat(_parenL)){var node=startNodeAt(start);node.callee=base;node.arguments=parseExprList(_parenR,false);return parseSubscripts(finishNode(node,"CallExpression"),start,noCalls)}else if(tokType===_backQuote){var node=startNodeAt(start);node.tag=base;node.quasi=parseTemplate();return parseSubscripts(finishNode(node,"TaggedTemplateExpression"),start,noCalls)}return base}function parseExprAtom(refShorthandDefaultPos){switch(tokType){case _this:var node=startNode();next();return finishNode(node,"ThisExpression");case _at:var start=storeCurrentPos();var node=startNode();var thisNode=startNode();next();node.object=finishNode(thisNode,"ThisExpression");node.property=parseSubscripts(parseIdent(),start);node.computed=false;return finishNode(node,"MemberExpression");case _yield:if(inGenerator)return parseYield();case _name:var start=storeCurrentPos();var node=startNode();var id=parseIdent(tokType!==_name);if(options.ecmaVersion>=7){if(id.name==="async"){if(tokType===_parenL){next();var exprList;if(tokType!==_parenR){var val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(eat(_arrow)){return parseArrowExpression(node,exprList,true)}else{node.callee=id;node.arguments=exprList;return parseSubscripts(finishNode(node,"CallExpression"),start)}}else if(tokType===_name){id=parseIdent();if(eat(_arrow)){return parseArrowExpression(node,[id],true)}return id}if(tokType===_function&&!canInsertSemicolon()){next();return parseFunction(node,false,true)}}else if(id.name==="await"){if(inAsync)return parseAwait(node)}}if(eat(_arrow)){return parseArrowExpression(node,[id])}return id;case _regexp:var node=startNode();node.regex={pattern:tokVal.pattern,flags:tokVal.flags};node.value=tokVal.value;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _num:case _string:case _jsxText:var node=startNode();node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _null:case _true:case _false:var node=startNode();node.value=tokType.atomValue;node.raw=tokType.keyword;next();return finishNode(node,"Literal");case _parenL:return parseParenAndDistinguishExpression();case _bracketL:var node=startNode();next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(node,false)}node.elements=parseExprList(_bracketR,true,true,refShorthandDefaultPos);return finishNode(node,"ArrayExpression");case _braceL:return parseObj(false,refShorthandDefaultPos);case _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _backQuote:return parseTemplate();case _hash:return parseBindFunctionExpression();case _jsxTagStart:return parseJSXElement();default:unexpected()}}function parseBindFunctionExpression(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return finishNode(node,"BindFunctionExpression")}function parseParenAndDistinguishExpression(){var start=storeCurrentPos(),val;if(options.ecmaVersion>=6){next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(startNodeAt(start),true)}var innerStart=storeCurrentPos(),exprList=[],first=true;var refShorthandDefaultPos={start:0},spreadStart,innerParenStart,typeStart;var parseParenItem=function(node){if(tokType===_colon){typeStart=typeStart||tokStart;node.returnType=parseTypeAnnotation()}return node};while(tokType!==_parenR){first?first=false:expect(_comma);if(tokType===_ellipsis){spreadStart=tokStart;exprList.push(parseParenItem(parseRest()));break}else{if(tokType===_parenL&&!innerParenStart){innerParenStart=tokStart}exprList.push(parseMaybeAssign(false,refShorthandDefaultPos,parseParenItem))}}var innerEnd=storeCurrentPos();expect(_parenR);if(eat(_arrow)){if(innerParenStart)unexpected(innerParenStart);return parseArrowExpression(startNodeAt(start),exprList)}if(!exprList.length)unexpected(lastStart);if(typeStart)unexpected(typeStart);if(spreadStart)unexpected(spreadStart);if(refShorthandDefaultPos.start)unexpected(refShorthandDefaultPos.start);if(exprList.length>1){val=startNodeAt(innerStart);val.expressions=exprList;finishNodeAt(val,"SequenceExpression",innerEnd)}else{val=exprList[0]}}else{val=parseParenExpression()}if(options.preserveParens){var par=startNodeAt(start);par.expression=val;return finishNode(par,"ParenthesizedExpression")}else{return val}}function parseNew(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL))node.arguments=parseExprList(_parenR,false);else node.arguments=empty;return finishNode(node,"NewExpression")}function parseTemplateElement(){var elem=startNode();elem.value={raw:input.slice(tokStart,tokEnd),cooked:tokVal};next();elem.tail=tokType===_backQuote;return finishNode(elem,"TemplateElement")}function parseTemplate(){var node=startNode();next();node.expressions=[];var curElt=parseTemplateElement();node.quasis=[curElt];while(!curElt.tail){expect(_dollarBraceL);node.expressions.push(parseExpression());expect(_braceR);node.quasis.push(curElt=parseTemplateElement())}next();return finishNode(node,"TemplateLiteral")}function parseObj(isPattern,refShorthandDefaultPos){var node=startNode(),first=true,propHash={};node.properties=[];next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),start,isGenerator=false,isAsync=false;if(options.ecmaVersion>=7&&tokType===_ellipsis){prop=parseSpread();prop.type="SpreadProperty";node.properties.push(prop);continue}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern){start=storeCurrentPos()}else{isGenerator=eat(_star)}}if(options.ecmaVersion>=7&&isContextual("async")){var asyncId=parseIdent();if(tokType===_colon||tokType===_parenL){prop.key=asyncId}else{isAsync=true;parsePropertyName(prop)}}else{parsePropertyName(prop)}var typeParameters;if(isRelational("<")){typeParameters=parseTypeParameterDeclaration();if(tokType!==_parenL)unexpected()}if(eat(_colon)){prop.value=isPattern?parseMaybeDefault(start):parseMaybeAssign(false,refShorthandDefaultPos);prop.kind="init"}else if(options.ecmaVersion>=6&&tokType===_parenL){if(isPattern)unexpected();prop.kind="init";prop.method=true;prop.value=parseMethod(isGenerator,isAsync)}else if(options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set"||options.playground&&prop.key.name==="memo")&&(tokType!=_comma&&tokType!=_braceR)){if(isGenerator||isAsync||isPattern)unexpected();prop.kind=prop.key.name;parsePropertyName(prop);prop.value=parseMethod(false,false)}else if(options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){prop.kind="init";if(isPattern){prop.value=parseMaybeDefault(start,prop.key)}else if(tokType===_eq&&refShorthandDefaultPos){if(!refShorthandDefaultPos.start)refShorthandDefaultPos.start=tokStart;prop.value=parseMaybeDefault(start,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else unexpected();prop.value.typeParameters=typeParameters;checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}return finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")}function parsePropertyName(prop){if(options.ecmaVersion>=6){if(eat(_bracketL)){prop.computed=true;prop.key=parseExpression();expect(_bracketR);return}else{prop.computed=false}}prop.key=tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function initFunction(node,isAsync){node.id=null;if(options.ecmaVersion>=6){node.generator=false;node.expression=false}if(options.ecmaVersion>=7){node.async=isAsync}}function parseFunction(node,isStatement,isAsync,allowExpressionBody){initFunction(node,isAsync);if(options.ecmaVersion>=6){node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}parseFunctionParams(node);parseFunctionBody(node,allowExpressionBody);return finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")}function parseMethod(isGenerator,isAsync){var node=startNode();initFunction(node,isAsync);parseFunctionParams(node);var allowExpressionBody;if(options.ecmaVersion>=6){node.generator=isGenerator;allowExpressionBody=true}else{allowExpressionBody=false}parseFunctionBody(node,allowExpressionBody);return finishNode(node,"FunctionExpression")}function parseFunctionParams(node){expect(_parenL);node.params=parseAssignableList(_parenR,false);if(tokType===_colon){node.returnType=parseTypeAnnotation()}}function parseArrowExpression(node,params,isAsync){initFunction(node,isAsync);node.params=toAssignableList(params,true);parseFunctionBody(node,true);return finishNode(node,"ArrowFunctionExpression")}function parseFunctionBody(node,allowExpression){var isExpression=allowExpression&&tokType!==_braceL;var oldInAsync=inAsync;inAsync=node.async;if(isExpression){node.body=parseMaybeAssign();node.expression=true}else{var oldInFunc=inFunction,oldInGen=inGenerator,oldLabels=labels;inFunction=true;inGenerator=node.generator;labels=[];node.body=parseBlock(true);node.expression=false;inFunction=oldInFunc;inGenerator=oldInGen;labels=oldLabels}inAsync=oldInAsync;if(strict||!isExpression&&node.body.body.length&&isUseStrict(node.body.body[0])){var nameHash={};if(node.id)checkFunctionParam(node.id,{});for(var i=0;i<node.params.length;i++)checkFunctionParam(node.params[i],nameHash)}}function parsePrivate(node){node.declarations=[];do{node.declarations.push(parseIdent())}while(eat(_comma));semicolon();return finishNode(node,"PrivateDeclaration")}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}node.superClass=eat(_extends)?parseExprSubscripts():null;if(node.superClass&&isRelational("<")){node.superTypeParameters=parseTypeParameterInstantiation()}if(isContextual("implements")){next();node.implements=parseClassImplements()}var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){if(eat(_semi))continue;var method=startNode();if(options.ecmaVersion>=7&&isContextual("private")){next();classBody.body.push(parsePrivate(method));continue}var isGenerator=eat(_star);var isAsync=false;parsePropertyName(method);if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&method.key.name==="static"){if(isGenerator||isAsync)unexpected();method["static"]=true;isGenerator=eat(_star);parsePropertyName(method)}else{method["static"]=false}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&method.key.name==="async"){isAsync=true;parsePropertyName(method)}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set")||options.playground&&method.key.name==="memo"){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}if(tokType===_colon){method.typeAnnotation=parseTypeAnnotation();semicolon();classBody.body.push(finishNode(method,"ClassProperty"))}else{var typeParameters;if(isRelational("<")){typeParameters=parseTypeParameterDeclaration()}method.value=parseMethod(isGenerator,isAsync);method.value.typeParameters=typeParameters;classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseClassImplements(){var implemented=[];do{var node=startNode();node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}implemented.push(finishNode(node,"ClassImplements"))}while(eat(_comma));return implemented}function parseExprList(close,allowTrailingComma,allowEmpty,refShorthandDefaultPos){var elts=[],first=true;while(!eat(close)){if(!first){expect(_comma);if(allowTrailingComma&&options.allowTrailingCommas&&eat(close))break}else first=false;if(allowEmpty&&tokType===_comma){elts.push(null)}else{if(tokType===_ellipsis)elts.push(parseSpread(refShorthandDefaultPos));else elts.push(parseMaybeAssign(false,refShorthandDefaultPos))}}return elts}function parseIdent(liberal){var node=startNode();if(liberal&&options.forbidReserved=="everywhere")liberal=false;if(tokType===_name){if(!liberal&&(options.forbidReserved&&(options.ecmaVersion===3?isReservedWord3:isReservedWord5)(tokVal)||strict&&isStrictReservedWord(tokVal))&&input.slice(tokStart,tokEnd).indexOf("\\")==-1)raise(tokStart,"The keyword '"+tokVal+"' is reserved");node.name=tokVal}else if(liberal&&tokType.keyword){node.name=tokType.keyword}else{unexpected()}next();return finishNode(node,"Identifier")}function parseExport(node){next();if(tokType===_var||tokType===_const||tokType===_let||tokType===_function||tokType===_class||isContextual("async")){node.declaration=parseStatement(true);node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){var declar=node.declaration=parseMaybeAssign(true);if(declar.id){if(declar.type==="FunctionExpression"){declar.type="FunctionDeclaration"}else if(declar.type==="ClassExpression"){declar.type="ClassDeclaration"}}node["default"]=true;node.specifiers=null;node.source=null;semicolon()}else{var isBatch=tokType===_star;node.declaration=null;node["default"]=false;node.specifiers=parseExportSpecifiers();if(eatContextual("from")){node.source=tokType===_string?parseExprAtom():unexpected()}else{if(isBatch)unexpected();node.source=null}semicolon()}return finishNode(node,"ExportDeclaration")}function parseExportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();nodes.push(finishNode(node,"ExportBatchSpecifier"))}else{expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(tokType===_default);node.name=eatContextual("as")?parseIdent(true):null;nodes.push(finishNode(node,"ExportSpecifier"))}}return nodes}function parseImport(node){next();if(tokType===_string){node.specifiers=[];node.source=parseExprAtom()}else{node.specifiers=parseImportSpecifiers();expectContextual("from");node.source=tokType===_string?parseExprAtom():unexpected()}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_name){var node=startNode();node.id=parseIdent();checkLVal(node.id,true);node.name=null;node["default"]=true;nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}if(tokType===_star){var node=startNode();next();expectContextual("as");node.name=parseIdent();checkLVal(node.name,true);nodes.push(finishNode(node,"ImportBatchSpecifier"));return nodes}expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(true);node.name=eatContextual("as")?parseIdent():null;checkLVal(node.name||node.id,true);node["default"]=false;nodes.push(finishNode(node,"ImportSpecifier"))}return nodes}function parseYield(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){node.delegate=false;node.argument=null}else{node.delegate=eat(_star);node.argument=parseMaybeAssign()}return finishNode(node,"YieldExpression")}function parseAwait(node){if(eat(_semi)||canInsertSemicolon()){unexpected()}node.delegate=eat(_star);node.argument=parseMaybeAssign(true);return finishNode(node,"AwaitExpression")}function parseComprehension(node,isGenerator){node.blocks=[];while(tokType===_for){var block=startNode();next();expect(_parenL);block.left=parseAssignableAtom();checkLVal(block.left,true);expectContextual("of");block.right=parseExpression();expect(_parenR);node.blocks.push(finishNode(block,"ComprehensionBlock"))}node.filter=eat(_if)?parseParenExpression():null;node.body=parseExpression();expect(isGenerator?_parenR:_bracketR);node.generator=isGenerator;return finishNode(node,"ComprehensionExpression")}function getQualifiedJSXName(object){if(object.type==="JSXIdentifier"){return object.name}if(object.type==="JSXNamespacedName"){return object.namespace.name+":"+object.name.name}if(object.type==="JSXMemberExpression"){return getQualifiedJSXName(object.object)+"."+getQualifiedJSXName(object.property)}}function parseJSXIdentifier(){var node=startNode();if(tokType===_jsxName){node.name=tokVal}else if(tokType.keyword){node.name=tokType.keyword}else{unexpected()}next();return finishNode(node,"JSXIdentifier")}function parseJSXNamespacedName(){var start=storeCurrentPos();var name=parseJSXIdentifier();if(!eat(_colon))return name;var node=startNodeAt(start);node.namespace=name;node.name=parseJSXIdentifier();return finishNode(node,"JSXNamespacedName")}function parseJSXElementName(){var start=storeCurrentPos();var node=parseJSXNamespacedName();while(eat(_dot)){var newNode=startNodeAt(start);newNode.object=node;newNode.property=parseJSXIdentifier();node=finishNode(newNode,"JSXMemberExpression")}return node}function parseJSXAttributeValue(){switch(tokType){case _braceL:var node=parseJSXExpressionContainer();if(node.expression.type==="JSXEmptyExpression"){raise(node.start,"JSX attributes must only be assigned a non-empty "+"expression")}return node;case _jsxTagStart:return parseJSXElement();case _jsxText:case _string:return parseExprAtom();default:raise(tokStart,"JSX value should be either an expression or a quoted JSX text")}}function parseJSXEmptyExpression(){if(tokType!==_braceR){unexpected()}var tmp;tmp=tokStart;tokStart=lastEnd;lastEnd=tmp;tmp=tokStartLoc;tokStartLoc=lastEndLoc;lastEndLoc=tmp;return finishNode(startNode(),"JSXEmptyExpression")}function parseJSXExpressionContainer(){var node=startNode();next();node.expression=tokType===_braceR?parseJSXEmptyExpression():parseExpression();expect(_braceR);return finishNode(node,"JSXExpressionContainer")}function parseJSXAttribute(){var node=startNode();if(eat(_braceL)){expect(_ellipsis);node.argument=parseMaybeAssign();expect(_braceR);return finishNode(node,"JSXSpreadAttribute")}node.name=parseJSXNamespacedName();node.value=eat(_eq)?parseJSXAttributeValue():null;return finishNode(node,"JSXAttribute")}function parseJSXOpeningElementAt(start){var node=startNodeAt(start);node.attributes=[];node.name=parseJSXElementName();while(tokType!==_slash&&tokType!==_jsxTagEnd){node.attributes.push(parseJSXAttribute())}node.selfClosing=eat(_slash);expect(_jsxTagEnd);return finishNode(node,"JSXOpeningElement")}function parseJSXClosingElementAt(start){var node=startNodeAt(start);node.name=parseJSXElementName();expect(_jsxTagEnd);return finishNode(node,"JSXClosingElement")}function parseJSXElementAt(start){var node=startNodeAt(start);var children=[];var openingElement=parseJSXOpeningElementAt(start);var closingElement=null;if(!openingElement.selfClosing){contents:for(;;){switch(tokType){case _jsxTagStart:start=storeCurrentPos();next();if(eat(_slash)){closingElement=parseJSXClosingElementAt(start);break contents}children.push(parseJSXElementAt(start));break;case _jsxText:children.push(parseExprAtom());break;case _braceL:children.push(parseJSXExpressionContainer()); break;default:unexpected()}}if(getQualifiedJSXName(closingElement.name)!==getQualifiedJSXName(openingElement.name)){raise(closingElement.start,"Expected corresponding JSX closing tag for <"+getQualifiedJSXName(openingElement.name)+">")}}node.openingElement=openingElement;node.closingElement=closingElement;node.children=children;return finishNode(node,"JSXElement")}function isRelational(op){return tokType===_relational&&tokVal===op}function expectRelational(op){if(isRelational(op)){next()}else{unexpected()}}function parseJSXElement(){var start=storeCurrentPos();next();return parseJSXElementAt(start)}function parseDeclareClass(node){next();parseInterfaceish(node,true);return finishNode(node,"DeclareClass")}function parseDeclareFunction(node){next();var id=node.id=parseIdent();var typeNode=startNode();var typeContainer=startNode();if(isRelational("<")){typeNode.typeParameters=parseTypeParameterDeclaration()}else{typeNode.typeParameters=null}expect(_parenL);var tmp=parseFunctionTypeParams();typeNode.params=tmp.params;typeNode.rest=tmp.rest;expect(_parenR);expect(_colon);typeNode.returnType=parseType();typeContainer.typeAnnotation=finishNode(typeNode,"FunctionTypeAnnotation");id.typeAnnotation=finishNode(typeContainer,"TypeAnnotation");finishNode(id,id.type);semicolon();return finishNode(node,"DeclareFunction")}function parseDeclare(node){if(tokType===_class){return parseDeclareClass(node)}else if(tokType===_function){return parseDeclareFunction(node)}else if(tokType===_var){return parseDeclareVariable(node)}else if(isContextual("module")){return parseDeclareModule(node)}else{unexpected()}}function parseDeclareVariable(node){next();node.id=parseTypeAnnotatableIdentifier();semicolon();return finishNode(node,"DeclareVariable")}function parseDeclareModule(node){next();if(tokType===_string){node.id=parseExprAtom()}else{node.id=parseIdent()}var bodyNode=node.body=startNode();var body=bodyNode.body=[];expect(_braceL);while(tokType!==_braceR){var node2=startNode();next();body.push(parseDeclare(node2))}expect(_braceR);finishNode(bodyNode,"BlockStatement");return finishNode(node,"DeclareModule")}function parseInterfaceish(node,allowStatic){node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}node.extends=[];if(eat(_extends)){do{node.extends.push(parseInterfaceExtends())}while(eat(_comma))}node.body=parseObjectType(allowStatic)}function parseInterfaceExtends(){var node=startNode();node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}return finishNode(node,"InterfaceExtends")}function parseInterface(node){parseInterfaceish(node,false);return finishNode(node,"InterfaceDeclaration")}function parseTypeAlias(node){node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}expect(_eq);node.right=parseType();semicolon();return finishNode(node,"TypeAlias")}function parseTypeParameterDeclaration(){var node=startNode();node.params=[];expectRelational("<");while(!isRelational(">")){node.params.push(parseIdent());if(!isRelational(">")){expect(_comma)}}expectRelational(">");return finishNode(node,"TypeParameterDeclaration")}function parseTypeParameterInstantiation(){var node=startNode(),oldInType=inType;node.params=[];inType=true;expectRelational("<");while(!isRelational(">")){node.params.push(parseType());if(!isRelational(">")){expect(_comma)}}expectRelational(">");inType=oldInType;return finishNode(node,"TypeParameterInstantiation")}function parseObjectPropertyKey(){return tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function parseObjectTypeIndexer(node,isStatic){node.static=isStatic;expect(_bracketL);node.id=parseObjectPropertyKey();expect(_colon);node.key=parseType();expect(_bracketR);expect(_colon);node.value=parseType();return finishNode(node,"ObjectTypeIndexer")}function parseObjectTypeMethodish(node){node.params=[];node.rest=null;node.typeParameters=null;if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}expect(_parenL);while(tokType===_name){node.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){node.rest=parseFunctionTypeParam()}expect(_parenR);expect(_colon);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}function parseObjectTypeMethod(start,isStatic,key){var node=startNodeAt(start);node.value=parseObjectTypeMethodish(startNodeAt(start));node.static=isStatic;node.key=key;node.optional=false;return finishNode(node,"ObjectTypeProperty")}function parseObjectTypeCallProperty(node,isStatic){var valueNode=startNode();node.static=isStatic;node.value=parseObjectTypeMethodish(valueNode);return finishNode(node,"ObjectTypeCallProperty")}function parseObjectType(allowStatic){var nodeStart=startNode();var node;var optional=false;var property;var propertyKey;var propertyTypeAnnotation;var token;var isStatic;nodeStart.callProperties=[];nodeStart.properties=[];nodeStart.indexers=[];expect(_braceL);while(tokType!==_braceR){var start=storeCurrentPos();node=startNode();if(allowStatic&&isContextual("static")){next();isStatic=true}if(tokType===_bracketL){nodeStart.indexers.push(parseObjectTypeIndexer(node,isStatic))}else if(tokType===_parenL||isRelational("<")){nodeStart.callProperties.push(parseObjectTypeCallProperty(node,allowStatic))}else{if(isStatic&&tokType===_colon){propertyKey=parseIdent()}else{propertyKey=parseObjectPropertyKey()}if(isRelational("<")||tokType===_parenL){nodeStart.properties.push(parseObjectTypeMethod(start,isStatic,propertyKey))}else{if(eat(_question)){optional=true}expect(_colon);node.key=propertyKey;node.value=parseType();node.optional=optional;node.static=isStatic;nodeStart.properties.push(finishNode(node,"ObjectTypeProperty"))}}if(!eat(_semi)&&tokType!==_braceR){unexpected()}}expect(_braceR);return finishNode(nodeStart,"ObjectTypeAnnotation")}function parseGenericType(start,id){var node=startNodeAt(start);node.typeParameters=null;node.id=id;while(eat(_dot)){var node2=startNodeAt(start);node2.qualification=node.id;node2.id=parseIdent();node.id=finishNode(node2,"QualifiedTypeIdentifier")}if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}return finishNode(node,"GenericTypeAnnotation")}function parseVoidType(){var node=startNode();expect(keywordTypes["void"]);return finishNode(node,"VoidTypeAnnotation")}function parseTypeofType(){var node=startNode();expect(keywordTypes["typeof"]);node.argument=parsePrimaryType();return finishNode(node,"TypeofTypeAnnotation")}function parseTupleType(){var node=startNode();node.types=[];expect(_bracketL);while(tokPos<inputLen&&tokType!==_bracketR){node.types.push(parseType());if(tokType===_bracketR)break;expect(_comma)}expect(_bracketR);return finishNode(node,"TupleTypeAnnotation")}function parseFunctionTypeParam(){var optional=false;var node=startNode();node.name=parseIdent();if(eat(_question)){optional=true}expect(_colon);node.optional=optional;node.typeAnnotation=parseType();return finishNode(node,"FunctionTypeParam")}function parseFunctionTypeParams(){var ret={params:[],rest:null};while(tokType===_name){ret.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){ret.rest=parseFunctionTypeParam()}return ret}function identToTypeAnnotation(start,node,id){switch(id.name){case"any":return finishNode(node,"AnyTypeAnnotation");case"bool":case"boolean":return finishNode(node,"BooleanTypeAnnotation");case"number":return finishNode(node,"NumberTypeAnnotation");case"string":return finishNode(node,"StringTypeAnnotation");default:return parseGenericType(start,id)}}function parsePrimaryType(){var typeIdentifier=null;var params=null;var returnType=null;var start=storeCurrentPos();var node=startNode();var rest=null;var tmp;var typeParameters;var token;var type;var isGroupedType=false;switch(tokType){case _name:return identToTypeAnnotation(start,node,parseIdent());case _braceL:return parseObjectType();case _bracketL:return parseTupleType();case _relational:if(tokVal==="<"){node.typeParameters=parseTypeParameterDeclaration();expect(_parenL);tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}case _parenL:next();var tmpId;if(tokType!==_parenR&&tokType!==_ellipsis){if(tokType===_name){}else{isGroupedType=true}}if(isGroupedType){if(tmpId&&_parenR){type=tmpId}else{type=parseType();expect(_parenR)}if(eat(_arrow)){raise(node,"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType")}return type}tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();node.typeParameters=null;return finishNode(node,"FunctionTypeAnnotation");case _string:node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"StringLiteralTypeAnnotation");default:if(tokType.keyword){switch(tokType.keyword){case"void":return parseVoidType();case"typeof":return parseTypeofType()}}}unexpected()}function parsePostfixType(){var node=startNode();var type=node.elementType=parsePrimaryType();if(tokType===_bracketL){expect(_bracketL);expect(_bracketR);return finishNode(node,"ArrayTypeAnnotation")}return type}function parsePrefixType(){var node=startNode();if(eat(_question)){node.typeAnnotation=parsePrefixType();return finishNode(node,"NullableTypeAnnotation")}return parsePostfixType()}function parseIntersectionType(){var node=startNode();var type=parsePrefixType();node.types=[type];while(eat(_bitwiseAND)){node.types.push(parsePrefixType())}return node.types.length===1?type:finishNode(node,"IntersectionTypeAnnotation")}function parseUnionType(){var node=startNode();var type=parseIntersectionType();node.types=[type];while(eat(_bitwiseOR)){node.types.push(parseIntersectionType())}return node.types.length===1?type:finishNode(node,"UnionTypeAnnotation")}function parseType(){var oldInType=inType;inType=true;var type=parseUnionType();inType=oldInType;return type}function parseTypeAnnotation(){var node=startNode();var oldInType=inType;inType=true;expect(_colon);node.typeAnnotation=parseType();inType=oldInType;return finishNode(node,"TypeAnnotation")}function parseTypeAnnotatableIdentifier(requireTypeAnnotation,canBeOptionalParam){var node=startNode();var ident=parseIdent();var isOptionalParam=false;if(canBeOptionalParam&&eat(_question)){expect(_question);isOptionalParam=true}if(requireTypeAnnotation||tokType===_colon){ident.typeAnnotation=parseTypeAnnotation();finishNode(ident,ident.type)}if(isOptionalParam){ident.optional=true;finishNode(ident,ident.type)}return ident}})},{}],107:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var def=Type.def;var or=Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isNumber=builtin.number;var isBoolean=builtin.boolean;var isRegExp=builtin.RegExp;var shared=require("../lib/shared");var defaults=shared.defaults;var geq=shared.geq;def("Printable").field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("Node").bases("Printable").field("type",isString);def("SourceLocation").build("start","end","source").field("start",def("Position")).field("end",def("Position")).field("source",or(isString,null),defaults["null"]);def("Position").build("line","column").field("line",geq(1)).field("column",geq(0));def("Program").bases("Node").build("body").field("body",[def("Statement")]).field("comments",or([or(def("Block"),def("Line"))],null),defaults["null"],true);def("Function").bases("Node").field("id",or(def("Identifier"),null),defaults["null"]).field("params",[def("Pattern")]).field("body",or(def("BlockStatement"),def("Expression")));def("Statement").bases("Node");def("EmptyStatement").bases("Statement").build();def("BlockStatement").bases("Statement").build("body").field("body",[def("Statement")]);def("ExpressionStatement").bases("Statement").build("expression").field("expression",def("Expression"));def("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Statement")).field("alternate",or(def("Statement"),null),defaults["null"]);def("LabeledStatement").bases("Statement").build("label","body").field("label",def("Identifier")).field("body",def("Statement"));def("BreakStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("ContinueStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("WithStatement").bases("Statement").build("object","body").field("object",def("Expression")).field("body",def("Statement"));def("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",def("Expression")).field("cases",[def("SwitchCase")]).field("lexical",isBoolean,defaults["false"]);def("ReturnStatement").bases("Statement").build("argument").field("argument",or(def("Expression"),null));def("ThrowStatement").bases("Statement").build("argument").field("argument",def("Expression"));def("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",def("BlockStatement")).field("handler",or(def("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[def("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[def("CatchClause")],defaults.emptyArray).field("finalizer",or(def("BlockStatement"),null),defaults["null"]);def("CatchClause").bases("Node").build("param","guard","body").field("param",def("Pattern")).field("guard",or(def("Expression"),null),defaults["null"]).field("body",def("BlockStatement"));def("WhileStatement").bases("Statement").build("test","body").field("test",def("Expression")).field("body",def("Statement"));def("DoWhileStatement").bases("Statement").build("body","test").field("body",def("Statement")).field("test",def("Expression"));def("ForStatement").bases("Statement").build("init","test","update","body").field("init",or(def("VariableDeclaration"),def("Expression"),null)).field("test",or(def("Expression"),null)).field("update",or(def("Expression"),null)).field("body",def("Statement"));def("ForInStatement").bases("Statement").build("left","right","body","each").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement")).field("each",isBoolean);def("DebuggerStatement").bases("Statement").build();def("Declaration").bases("Statement");def("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",def("Identifier"));def("FunctionExpression").bases("Function","Expression").build("id","params","body");def("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",or("var","let","const")).field("declarations",[or(def("VariableDeclarator"),def("Identifier"))]);def("VariableDeclarator").bases("Node").build("id","init").field("id",def("Pattern")).field("init",or(def("Expression"),null));def("Expression").bases("Node","Pattern");def("ThisExpression").bases("Expression").build();def("ArrayExpression").bases("Expression").build("elements").field("elements",[or(def("Expression"),null)]);def("ObjectExpression").bases("Expression").build("properties").field("properties",[def("Property")]);def("Property").bases("Node").build("kind","key","value").field("kind",or("init","get","set")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Expression"));def("SequenceExpression").bases("Expression").build("expressions").field("expressions",[def("Expression")]);var UnaryOperator=or("-","+","!","~","typeof","void","delete");def("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",UnaryOperator).field("argument",def("Expression")).field("prefix",isBoolean,defaults["true"]);var BinaryOperator=or("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");def("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",BinaryOperator).field("left",def("Expression")).field("right",def("Expression"));var AssignmentOperator=or("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");def("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",AssignmentOperator).field("left",def("Pattern")).field("right",def("Expression"));var UpdateOperator=or("++","--");def("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",UpdateOperator).field("argument",def("Expression")).field("prefix",isBoolean);var LogicalOperator=or("||","&&");def("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",LogicalOperator).field("left",def("Expression")).field("right",def("Expression"));def("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Expression")).field("alternate",def("Expression"));def("NewExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("CallExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("MemberExpression").bases("Expression").build("object","property","computed").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("Pattern").bases("Node");def("ObjectPattern").bases("Pattern").build("properties").field("properties",[def("PropertyPattern")]);def("PropertyPattern").bases("Pattern").build("key","pattern").field("key",or(def("Literal"),def("Identifier"))).field("pattern",def("Pattern"));def("ArrayPattern").bases("Pattern").build("elements").field("elements",[or(def("Pattern"),null)]);def("SwitchCase").bases("Node").build("test","consequent").field("test",or(def("Expression"),null)).field("consequent",[def("Statement")]);def("Identifier").bases("Node","Expression","Pattern").build("name").field("name",isString);def("Literal").bases("Node","Expression").build("value").field("value",or(isString,isBoolean,null,isNumber,isRegExp));def("Block").bases("Printable").build("loc","value").field("value",isString);def("Line").bases("Printable").build("loc","value").field("value",isString)},{"../lib/shared":118,"../lib/types":119}],108:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;def("XMLDefaultDeclaration").bases("Declaration").field("namespace",def("Expression"));def("XMLAnyName").bases("Expression");def("XMLQualifiedIdentifier").bases("Expression").field("left",or(def("Identifier"),def("XMLAnyName"))).field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLAttributeSelector").bases("Expression").field("attribute",def("Expression"));def("XMLFilterExpression").bases("Expression").field("left",def("Expression")).field("right",def("Expression"));def("XMLElement").bases("XML","Expression").field("contents",[def("XML")]);def("XMLList").bases("XML","Expression").field("contents",[def("XML")]);def("XML").bases("Node");def("XMLEscape").bases("XML").field("expression",def("Expression"));def("XMLText").bases("XML").field("text",isString);def("XMLStartTag").bases("XML").field("contents",[def("XML")]);def("XMLEndTag").bases("XML").field("contents",[def("XML")]);def("XMLPointTag").bases("XML").field("contents",[def("XML")]);def("XMLName").bases("XML").field("contents",or(isString,[def("XML")]));def("XMLAttribute").bases("XML").field("value",isString);def("XMLCdata").bases("XML").field("contents",isString);def("XMLComment").bases("XML").field("contents",isString);def("XMLProcessingInstruction").bases("XML").field("target",isString).field("contents",or(isString,null))},{"../lib/types":119,"./core":107}],109:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var isObject=builtin.object;var isString=builtin.string;var defaults=require("../lib/shared").defaults;def("Function").field("generator",isBoolean,defaults["false"]).field("expression",isBoolean,defaults["false"]).field("defaults",[or(def("Expression"),null)],defaults.emptyArray).field("rest",or(def("Identifier"),null),defaults["null"]);def("FunctionDeclaration").build("id","params","body","generator","expression");def("FunctionExpression").build("id","params","body","generator","expression");def("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,defaults["null"]).field("generator",false);def("YieldExpression").bases("Expression").build("argument","delegate").field("argument",or(def("Expression"),null)).field("delegate",isBoolean,defaults["false"]);def("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionBlock").bases("Node").build("left","right","each").field("left",def("Pattern")).field("right",def("Expression")).field("each",isBoolean);def("ModuleSpecifier").bases("Literal").build("value").field("value",isString);def("Property").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("PropertyPattern").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);def("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",or("init","get","set","")).field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("value",def("Function")).field("computed",isBoolean,defaults["false"]);def("SpreadElement").bases("Node").build("argument").field("argument",def("Expression"));def("ArrayExpression").field("elements",[or(def("Expression"),def("SpreadElement"),null)]);def("NewExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("CallExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("SpreadElementPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));var ClassBodyElement=or(def("MethodDefinition"),def("VariableDeclarator"),def("ClassPropertyDefinition"),def("ClassProperty"));def("ClassProperty").bases("Declaration").build("key").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",ClassBodyElement);def("ClassBody").bases("Declaration").build("body").field("body",[ClassBodyElement]);def("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",def("Identifier")).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("ClassExpression").bases("Expression").build("id","body","superClass").field("id",or(def("Identifier"),null),defaults["null"]).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]).field("implements",[def("ClassImplements")],defaults.emptyArray);def("ClassImplements").bases("Node").build("id").field("id",def("Identifier")).field("superClass",or(def("Expression"),null),defaults["null"]);def("Specifier").bases("Node");def("NamedSpecifier").bases("Specifier").field("id",def("Identifier")).field("name",or(def("Identifier"),null),defaults["null"]);def("ExportSpecifier").bases("NamedSpecifier").build("id","name");def("ExportBatchSpecifier").bases("Specifier").build();def("ImportSpecifier").bases("NamedSpecifier").build("id","name");def("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",isBoolean).field("declaration",or(def("Declaration"),def("Expression"),null)).field("specifiers",[or(def("ExportSpecifier"),def("ExportBatchSpecifier"))],defaults.emptyArray).field("source",or(def("ModuleSpecifier"),null),defaults["null"]);def("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[or(def("ImportSpecifier"),def("ImportNamespaceSpecifier"),def("ImportDefaultSpecifier"))],defaults.emptyArray).field("source",def("ModuleSpecifier"));def("TaggedTemplateExpression").bases("Expression").field("tag",def("Expression")).field("quasi",def("TemplateLiteral"));def("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[def("TemplateElement")]).field("expressions",[def("Expression")]);def("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:isString,raw:isString}).field("tail",isBoolean)},{"../lib/shared":118,"../lib/types":119,"./core":107}],110:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("Function").field("async",isBoolean,defaults["false"]);def("SpreadProperty").bases("Node").build("argument").field("argument",def("Expression"));def("ObjectExpression").field("properties",[or(def("Property"),def("SpreadProperty"))]);def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));def("ObjectPattern").field("properties",[or(def("PropertyPattern"),def("SpreadPropertyPattern"))]);def("AwaitExpression").bases("Expression").build("argument","all").field("argument",or(def("Expression"),null)).field("all",isBoolean,defaults["false"])},{"../lib/shared":118,"../lib/types":119,"./core":107}],111:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("XJSAttribute").bases("Node").build("name","value").field("name",or(def("XJSIdentifier"),def("XJSNamespacedName"))).field("value",or(def("Literal"),def("XJSExpressionContainer"),null),defaults["null"]);def("XJSIdentifier").bases("Node").build("name").field("name",isString);def("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",def("XJSIdentifier")).field("name",def("XJSIdentifier"));def("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",or(def("XJSIdentifier"),def("XJSMemberExpression"))).field("property",def("XJSIdentifier")).field("computed",isBoolean,defaults.false);var XJSElementName=or(def("XJSIdentifier"),def("XJSNamespacedName"),def("XJSMemberExpression"));def("XJSSpreadAttribute").bases("Node").build("argument").field("argument",def("Expression"));var XJSAttributes=[or(def("XJSAttribute"),def("XJSSpreadAttribute"))];def("XJSExpressionContainer").bases("Expression").build("expression").field("expression",def("Expression"));def("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",def("XJSOpeningElement")).field("closingElement",or(def("XJSClosingElement"),null),defaults["null"]).field("children",[or(def("XJSElement"),def("XJSExpressionContainer"),def("XJSText"),def("Literal"))],defaults.emptyArray).field("name",XJSElementName,function(){return this.openingElement.name}).field("selfClosing",isBoolean,function(){return this.openingElement.selfClosing}).field("attributes",XJSAttributes,function(){return this.openingElement.attributes});def("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",XJSElementName).field("attributes",XJSAttributes,defaults.emptyArray).field("selfClosing",isBoolean,defaults["false"]);def("XJSClosingElement").bases("Node").build("name").field("name",XJSElementName);def("XJSText").bases("Literal").build("value").field("value",isString);def("XJSEmptyExpression").bases("Expression").build();def("Type").bases("Node");def("AnyTypeAnnotation").bases("Type");def("VoidTypeAnnotation").bases("Type");def("NumberTypeAnnotation").bases("Type");def("StringTypeAnnotation").bases("Type");def("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",isString).field("raw",isString);def("BooleanTypeAnnotation").bases("Type");def("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",def("Type"));def("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",def("Type"));def("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[def("FunctionTypeParam")]).field("returnType",def("Type")).field("rest",or(def("FunctionTypeParam"),null)).field("typeParameters",or(def("TypeParameterDeclaration"),null));def("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",def("Identifier")).field("typeAnnotation",def("Type")).field("optional",isBoolean);def("ArrayTypeAnnotation").bases("Type").build("elementType").field("elementType",def("Type"));def("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[def("ObjectTypeProperty")]).field("indexers",[def("ObjectTypeIndexer")],defaults.emptyArray).field("callProperties",[def("ObjectTypeCallProperty")],defaults.emptyArray);def("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",or(def("Literal"),def("Identifier"))).field("value",def("Type")).field("optional",isBoolean);def("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",def("Identifier")).field("key",def("Type")).field("value",def("Type"));def("ObjectTypeCallProperty").bases("Node").build("value").field("value",def("FunctionTypeAnnotation")).field("static",isBoolean,false);def("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("id",def("Identifier"));def("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("MemberTypeAnnotation").bases("Type").build("object","property").field("object",def("Identifier")).field("property",or(def("MemberTypeAnnotation"),def("GenericTypeAnnotation")));def("UnionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",def("Type"));def("Identifier").field("typeAnnotation",or(def("TypeAnnotation"),null),defaults["null"]);def("TypeParameterDeclaration").bases("Node").build("params").field("params",[def("Identifier")]); def("TypeParameterInstantiation").bases("Node").build("params").field("params",[def("Type")]);def("Function").field("returnType",or(def("TypeAnnotation"),null),defaults["null"]).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]);def("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",def("TypeAnnotation")).field("static",isBoolean,false);def("ClassImplements").field("typeParameters",or(def("TypeParameterInstantiation"),null),defaults["null"]);def("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]).field("body",def("ObjectTypeAnnotation")).field("extends",[def("InterfaceExtends")]);def("InterfaceExtends").bases("Node").build("id").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null)).field("right",def("Type"));def("TupleTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("DeclareVariable").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareFunction").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareClass").bases("InterfaceDeclaration").build("id");def("DeclareModule").bases("Statement").build("id","body").field("id",or(def("Identifier"),def("Literal"))).field("body",def("BlockStatement"))},{"../lib/shared":118,"../lib/types":119,"./core":107}],112:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var geq=require("../lib/shared").geq;def("ForOfStatement").bases("Statement").build("left","right","body").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement"));def("LetStatement").bases("Statement").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Statement"));def("LetExpression").bases("Expression").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Expression"));def("GraphExpression").bases("Expression").build("index","expression").field("index",geq(0)).field("expression",def("Literal"));def("GraphIndexExpression").bases("Expression").build("index").field("index",geq(0))},{"../lib/shared":118,"../lib/types":119,"./core":107}],113:[function(require,module,exports){var assert=require("assert");var types=require("../main");var getFieldNames=types.getFieldNames;var getFieldValue=types.getFieldValue;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isDate=types.builtInTypes.Date;var isRegExp=types.builtInTypes.RegExp;var hasOwn=Object.prototype.hasOwnProperty;function astNodesAreEquivalent(a,b,problemPath){if(isArray.check(problemPath)){problemPath.length=0}else{problemPath=null}return areEquivalent(a,b,problemPath)}astNodesAreEquivalent.assert=function(a,b){var problemPath=[];if(!astNodesAreEquivalent(a,b,problemPath)){if(problemPath.length===0){assert.strictEqual(a,b)}else{assert.ok(false,"Nodes differ in the following path: "+problemPath.map(subscriptForProperty).join(""))}}};function subscriptForProperty(property){if(/[_$a-z][_$a-z0-9]*/i.test(property)){return"."+property}return"["+JSON.stringify(property)+"]"}function areEquivalent(a,b,problemPath){if(a===b){return true}if(isArray.check(a)){return arraysAreEquivalent(a,b,problemPath)}if(isObject.check(a)){return objectsAreEquivalent(a,b,problemPath)}if(isDate.check(a)){return isDate.check(b)&&+a===+b}if(isRegExp.check(a)){return isRegExp.check(b)&&(a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.ignoreCase===b.ignoreCase)}return a==b}function arraysAreEquivalent(a,b,problemPath){isArray.assert(a);var aLength=a.length;if(!isArray.check(b)||b.length!==aLength){if(problemPath){problemPath.push("length")}return false}for(var i=0;i<aLength;++i){if(problemPath){problemPath.push(i)}if(i in a!==i in b){return false}if(!areEquivalent(a[i],b[i],problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),i)}}return true}function objectsAreEquivalent(a,b,problemPath){isObject.assert(a);if(!isObject.check(b)){return false}if(a.type!==b.type){if(problemPath){problemPath.push("type")}return false}var aNames=getFieldNames(a);var aNameCount=aNames.length;var bNames=getFieldNames(b);var bNameCount=bNames.length;if(aNameCount===bNameCount){for(var i=0;i<aNameCount;++i){var name=aNames[i];var aChild=getFieldValue(a,name);var bChild=getFieldValue(b,name);if(problemPath){problemPath.push(name)}if(!areEquivalent(aChild,bChild,problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),name)}}return true}if(!problemPath){return false}var seenNames=Object.create(null);for(i=0;i<aNameCount;++i){seenNames[aNames[i]]=true}for(i=0;i<bNameCount;++i){name=bNames[i];if(!hasOwn.call(seenNames,name)){problemPath.push(name);return false}delete seenNames[name]}for(name in seenNames){problemPath.push(name);break}return false}module.exports=astNodesAreEquivalent},{"../main":120,assert:122}],114:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isNumber=types.builtInTypes.number;var isArray=types.builtInTypes.array;var Path=require("./path");var Scope=require("./scope");function NodePath(value,parentPath,name){assert.ok(this instanceof NodePath);Path.call(this,value,parentPath,name)}require("util").inherits(NodePath,Path);var NPp=NodePath.prototype;Object.defineProperties(NPp,{node:{get:function(){Object.defineProperty(this,"node",{configurable:true,value:this._computeNode()});return this.node}},parent:{get:function(){Object.defineProperty(this,"parent",{configurable:true,value:this._computeParent()});return this.parent}},scope:{get:function(){Object.defineProperty(this,"scope",{configurable:true,value:this._computeScope()});return this.scope}}});NPp.replace=function(){delete this.node;delete this.parent;delete this.scope;return Path.prototype.replace.apply(this,arguments)};NPp.prune=function(){var remainingNodePath=this.parent;this.replace();return cleanUpNodesAfterPrune(remainingNodePath)};NPp._computeNode=function(){var value=this.value;if(n.Node.check(value)){return value}var pp=this.parentPath;return pp&&pp.node||null};NPp._computeParent=function(){var value=this.value;var pp=this.parentPath;if(!n.Node.check(value)){while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}if(pp){pp=pp.parentPath}}while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}return pp||null};NPp._computeScope=function(){var value=this.value;var pp=this.parentPath;var scope=pp&&pp.scope;if(n.Node.check(value)&&Scope.isEstablishedBy(value)){scope=new Scope(this,scope)}return scope||null};NPp.getValueProperty=function(name){return types.getFieldValue(this.value,name)};NPp.needsParens=function(assumeExpressionContext){var pp=this.parentPath;if(!pp){return false}var node=this.value;if(!n.Expression.check(node)){return false}if(node.type==="Identifier"){return false}while(!n.Node.check(pp.value)){pp=pp.parentPath;if(!pp){return false}}var parent=pp.value;switch(node.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return parent.type==="MemberExpression"&&this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":switch(parent.type){case"CallExpression":return this.name==="callee"&&parent.callee===node;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":var po=parent.operator;var pp=PRECEDENCE[po];var no=node.operator;var np=PRECEDENCE[no];if(pp>np){return true}if(pp===np&&this.name==="right"){assert.strictEqual(parent.right,node);return true}default:return false}case"SequenceExpression":switch(parent.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(parent.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return true;default:return false}case"Literal":return parent.type==="MemberExpression"&&isNumber.check(node.value)&&this.name==="object"&&parent.object===node;case"AssignmentExpression":case"ConditionalExpression":switch(parent.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&parent.callee===node;case"ConditionalExpression":return this.name==="test"&&parent.test===node;case"MemberExpression":return this.name==="object"&&parent.object===node;default:return false}default:if(parent.type==="NewExpression"&&this.name==="callee"&&parent.callee===node){return containsCallExpression(node)}}if(assumeExpressionContext!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function isBinary(node){return n.BinaryExpression.check(node)||n.LogicalExpression.check(node)}function isUnaryLike(node){return n.UnaryExpression.check(node)||n.SpreadElement&&n.SpreadElement.check(node)||n.SpreadProperty&&n.SpreadProperty.check(node)}var PRECEDENCE={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(tier,i){tier.forEach(function(op){PRECEDENCE[op]=i})});function containsCallExpression(node){if(n.CallExpression.check(node)){return true}if(isArray.check(node)){return node.some(containsCallExpression)}if(n.Node.check(node)){return types.someField(node,function(name,child){return containsCallExpression(child)})}return false}NPp.canBeFirstInStatement=function(){var node=this.node;return!n.FunctionExpression.check(node)&&!n.ObjectExpression.check(node)};NPp.firstInStatement=function(){return firstInStatement(this)};function firstInStatement(path){for(var node,parent;path.parent;path=path.parent){node=path.node;parent=path.parent.node;if(n.BlockStatement.check(parent)&&path.parent.name==="body"&&path.name===0){assert.strictEqual(parent.body[0],node);return true}if(n.ExpressionStatement.check(parent)&&path.name==="expression"){assert.strictEqual(parent.expression,node);return true}if(n.SequenceExpression.check(parent)&&path.parent.name==="expressions"&&path.name===0){assert.strictEqual(parent.expressions[0],node);continue}if(n.CallExpression.check(parent)&&path.name==="callee"){assert.strictEqual(parent.callee,node);continue}if(n.MemberExpression.check(parent)&&path.name==="object"){assert.strictEqual(parent.object,node);continue}if(n.ConditionalExpression.check(parent)&&path.name==="test"){assert.strictEqual(parent.test,node);continue}if(isBinary(parent)&&path.name==="left"){assert.strictEqual(parent.left,node);continue}if(n.UnaryExpression.check(parent)&&!parent.prefix&&path.name==="argument"){assert.strictEqual(parent.argument,node);continue}return false}return true}function cleanUpNodesAfterPrune(remainingNodePath){if(n.VariableDeclaration.check(remainingNodePath.node)){var declarations=remainingNodePath.get("declarations").value;if(!declarations||declarations.length===0){return remainingNodePath.prune()}}else if(n.ExpressionStatement.check(remainingNodePath.node)){if(!remainingNodePath.get("expression").value){return remainingNodePath.prune()}}else if(n.IfStatement.check(remainingNodePath.node)){cleanUpIfStatementAfterPrune(remainingNodePath)}return remainingNodePath}function cleanUpIfStatementAfterPrune(ifStatement){var testExpression=ifStatement.get("test").value;var alternate=ifStatement.get("alternate").value;var consequent=ifStatement.get("consequent").value;if(!consequent&&!alternate){var testExpressionStatement=b.expressionStatement(testExpression);ifStatement.replace(testExpressionStatement)}else if(!consequent&&alternate){var negatedTestExpression=b.unaryExpression("!",testExpression,true);if(n.UnaryExpression.check(testExpression)&&testExpression.operator==="!"){negatedTestExpression=testExpression.argument}ifStatement.get("test").replace(negatedTestExpression);ifStatement.get("consequent").replace(alternate);ifStatement.get("alternate").replace()}}module.exports=NodePath},{"./path":116,"./scope":117,"./types":119,assert:122,util:147}],115:[function(require,module,exports){var assert=require("assert");var types=require("./types");var NodePath=require("./node-path");var Node=types.namedTypes.Node;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isFunction=types.builtInTypes.function;var hasOwn=Object.prototype.hasOwnProperty;var undefined;function PathVisitor(){assert.ok(this instanceof PathVisitor);this._reusableContextStack=[];this._methodNameTable=computeMethodNameTable(this);this.Context=makeContextConstructor(this);this._visiting=false;this._changeReported=false}function computeMethodNameTable(visitor){var typeNames=Object.create(null);for(var methodName in visitor){if(/^visit[A-Z]/.test(methodName)){typeNames[methodName.slice("visit".length)]=true}}var supertypeTable=types.computeSupertypeLookupTable(typeNames);var methodNameTable=Object.create(null);var typeNames=Object.keys(supertypeTable);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];methodName="visit"+supertypeTable[typeName];if(isFunction.check(visitor[methodName])){methodNameTable[typeName]=methodName}}return methodNameTable}PathVisitor.fromMethodsObject=function fromMethodsObject(methods){if(methods instanceof PathVisitor){return methods}if(!isObject.check(methods)){return new PathVisitor}function Visitor(){assert.ok(this instanceof Visitor);PathVisitor.call(this)}var Vp=Visitor.prototype=Object.create(PVp);Vp.constructor=Visitor;extend(Vp,methods);extend(Visitor,PathVisitor);isFunction.assert(Visitor.fromMethodsObject);isFunction.assert(Visitor.visit);return new Visitor};function extend(target,source){for(var property in source){if(hasOwn.call(source,property)){target[property]=source[property]}}return target}PathVisitor.visit=function visit(node,methods){return PathVisitor.fromMethodsObject(methods).visit(node)};var PVp=PathVisitor.prototype;var recursiveVisitWarning=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");PVp.visit=function(){assert.ok(!this._visiting,recursiveVisitWarning);this._visiting=true;this._changeReported=false;var argc=arguments.length;var args=new Array(argc);for(var i=0;i<argc;++i){args[i]=arguments[i]}if(!(args[0]instanceof NodePath)){args[0]=new NodePath({root:args[0]}).get("root")}this.reset.apply(this,args);try{return this.visitWithoutReset(args[0])}finally{this._visiting=false}};PVp.reset=function(path){};PVp.visitWithoutReset=function(path){if(this instanceof this.Context){return this.visitor.visitWithoutReset(path)}assert.ok(path instanceof NodePath);var value=path.value;var methodName=Node.check(value)&&this._methodNameTable[value.type];if(methodName){var context=this.acquireContext(path);try{return context.invokeVisitorMethod(methodName)}finally{this.releaseContext(context)}}else{return visitChildren(path,this)}};function visitChildren(path,visitor){assert.ok(path instanceof NodePath);assert.ok(visitor instanceof PathVisitor);var value=path.value;if(isArray.check(value)){path.each(visitor.visitWithoutReset,visitor)}else if(!isObject.check(value)){}else{var childNames=types.getFieldNames(value);var childCount=childNames.length;var childPaths=[];for(var i=0;i<childCount;++i){var childName=childNames[i];if(!hasOwn.call(value,childName)){value[childName]=types.getFieldValue(value,childName)}childPaths.push(path.get(childName))}for(var i=0;i<childCount;++i){visitor.visitWithoutReset(childPaths[i])}}return path.value}PVp.acquireContext=function(path){if(this._reusableContextStack.length===0){return new this.Context(path)}return this._reusableContextStack.pop().reset(path)};PVp.releaseContext=function(context){assert.ok(context instanceof this.Context);this._reusableContextStack.push(context);context.currentPath=null};PVp.reportChanged=function(){this._changeReported=true};PVp.wasChangeReported=function(){return this._changeReported};function makeContextConstructor(visitor){function Context(path){assert.ok(this instanceof Context);assert.ok(this instanceof PathVisitor);assert.ok(path instanceof NodePath);Object.defineProperty(this,"visitor",{value:visitor,writable:false,enumerable:true,configurable:false});this.currentPath=path;this.needToCallTraverse=true;Object.seal(this)}assert.ok(visitor instanceof PathVisitor);var Cp=Context.prototype=Object.create(visitor);Cp.constructor=Context;extend(Cp,sharedContextProtoMethods);return Context}var sharedContextProtoMethods=Object.create(null);sharedContextProtoMethods.reset=function reset(path){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);this.currentPath=path;this.needToCallTraverse=true;return this};sharedContextProtoMethods.invokeVisitorMethod=function invokeVisitorMethod(methodName){assert.ok(this instanceof this.Context);assert.ok(this.currentPath instanceof NodePath);var result=this.visitor[methodName].call(this,this.currentPath);if(result===false){this.needToCallTraverse=false}else if(result!==undefined){this.currentPath=this.currentPath.replace(result)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}assert.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+methodName);var path=this.currentPath;return path&&path.value};sharedContextProtoMethods.traverse=function traverse(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;return visitChildren(path,PathVisitor.fromMethodsObject(newVisitor||this.visitor))};sharedContextProtoMethods.visit=function visit(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;return PathVisitor.fromMethodsObject(newVisitor||this.visitor).visitWithoutReset(path)};sharedContextProtoMethods.reportChanged=function reportChanged(){this.visitor.reportChanged()};module.exports=PathVisitor},{"./node-path":114,"./types":119,assert:122}],116:[function(require,module,exports){var assert=require("assert");var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var types=require("./types");var isArray=types.builtInTypes.array;var isNumber=types.builtInTypes.number;var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;function Path(value,parentPath,name){assert.ok(this instanceof Path);if(parentPath){assert.ok(parentPath instanceof Path)}else{parentPath=null;name=null}this.value=value;this.parentPath=parentPath;this.name=name;this.__childCache=null}var Pp=Path.prototype;function getChildCache(path){return path.__childCache||(path.__childCache=Object.create(null))}function getChildPath(path,name){var cache=getChildCache(path);var actualChildValue=path.getValueProperty(name);var childPath=cache[name];if(!hasOwn.call(cache,name)||childPath.value!==actualChildValue){childPath=cache[name]=new path.constructor(actualChildValue,path,name)}return childPath}Pp.getValueProperty=function getValueProperty(name){return this.value[name]};Pp.get=function get(name){var path=this;var names=arguments;var count=names.length;for(var i=0;i<count;++i){path=getChildPath(path,names[i])}return path};Pp.each=function each(callback,context){var childPaths=[];var len=this.value.length;var i=0;for(var i=0;i<len;++i){if(hasOwn.call(this.value,i)){childPaths[i]=this.get(i)}}context=context||this;for(i=0;i<len;++i){if(hasOwn.call(childPaths,i)){callback.call(context,childPaths[i])}}};Pp.map=function map(callback,context){var result=[];this.each(function(childPath){result.push(callback.call(this,childPath))},context);return result};Pp.filter=function filter(callback,context){var result=[];this.each(function(childPath){if(callback.call(this,childPath)){result.push(childPath)}},context);return result};function emptyMoves(){}function getMoves(path,offset,start,end){isArray.assert(path.value);if(offset===0){return emptyMoves}var length=path.value.length;if(length<1){return emptyMoves}var argc=arguments.length;if(argc===2){start=0;end=length}else if(argc===3){start=Math.max(start,0);end=length}else{start=Math.max(start,0);end=Math.min(end,length)}isNumber.assert(start);isNumber.assert(end);var moves=Object.create(null);var cache=getChildCache(path);for(var i=start;i<end;++i){if(hasOwn.call(path.value,i)){var childPath=path.get(i);assert.strictEqual(childPath.name,i);var newIndex=i+offset;childPath.name=newIndex;moves[newIndex]=childPath;delete cache[i]}}delete cache.length;return function(){for(var newIndex in moves){var childPath=moves[newIndex];assert.strictEqual(childPath.name,+newIndex);cache[newIndex]=childPath;path.value[newIndex]=childPath.value}}}Pp.shift=function shift(){var move=getMoves(this,-1);var result=this.value.shift();move();return result};Pp.unshift=function unshift(node){var move=getMoves(this,arguments.length);var result=this.value.unshift.apply(this.value,arguments);move();return result};Pp.push=function push(node){isArray.assert(this.value);delete getChildCache(this).length;return this.value.push.apply(this.value,arguments)};Pp.pop=function pop(){isArray.assert(this.value);var cache=getChildCache(this);delete cache[this.value.length-1];delete cache.length;return this.value.pop()};Pp.insertAt=function insertAt(index,node){var argc=arguments.length;var move=getMoves(this,argc-1,index);if(move===emptyMoves){return this}index=Math.max(index,0);for(var i=1;i<argc;++i){this.value[index+i-1]=arguments[i]}move();return this};Pp.insertBefore=function insertBefore(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};Pp.insertAfter=function insertAfter(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name+1];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};function repairRelationshipWithParent(path){assert.ok(path instanceof Path);var pp=path.parentPath;if(!pp){return path}var parentValue=pp.value;var parentCache=getChildCache(pp);if(parentValue[path.name]===path.value){parentCache[path.name]=path}else if(isArray.check(parentValue)){var i=parentValue.indexOf(path.value);if(i>=0){parentCache[path.name=i]=path}}else{parentValue[path.name]=path.value;parentCache[path.name]=path}assert.strictEqual(parentValue[path.name],path.value);assert.strictEqual(path.parentPath.get(path.name),path);return path}Pp.replace=function replace(replacement){var results=[];var parentValue=this.parentPath.value;var parentCache=getChildCache(this.parentPath);var count=arguments.length;repairRelationshipWithParent(this);if(isArray.check(parentValue)){var originalLength=parentValue.length;var move=getMoves(this.parentPath,count-1,this.name+1);var spliceArgs=[this.name,1];for(var i=0;i<count;++i){spliceArgs.push(arguments[i])}var splicedOut=parentValue.splice.apply(parentValue,spliceArgs);assert.strictEqual(splicedOut[0],this.value);assert.strictEqual(parentValue.length,originalLength-1+count);move();if(count===0){delete this.value;delete parentCache[this.name];this.__childCache=null}else{assert.strictEqual(parentValue[this.name],replacement);if(this.value!==replacement){this.value=replacement;this.__childCache=null}for(i=0;i<count;++i){results.push(this.parentPath.get(this.name+i))}assert.strictEqual(results[0],this)}}else if(count===1){if(this.value!==replacement){this.__childCache=null}this.value=parentValue[this.name]=replacement;results.push(this)}else if(count===0){delete parentValue[this.name];delete this.value;this.__childCache=null}else{assert.ok(false,"Could not replace path")}return results};module.exports=Path},{"./types":119,assert:122}],117:[function(require,module,exports){var assert=require("assert");var types=require("./types");var Type=types.Type;var namedTypes=types.namedTypes;var Node=namedTypes.Node;var Expression=namedTypes.Expression;var isArray=types.builtInTypes.array;var hasOwn=Object.prototype.hasOwnProperty;var b=types.builders;function Scope(path,parentScope){assert.ok(this instanceof Scope);assert.ok(path instanceof require("./node-path"));ScopeType.assert(path.value);var depth;if(parentScope){assert.ok(parentScope instanceof Scope);depth=parentScope.depth+1}else{parentScope=null;depth=0}Object.defineProperties(this,{path:{value:path},node:{value:path.value},isGlobal:{value:!parentScope,enumerable:true},depth:{value:depth},parent:{value:parentScope},bindings:{value:{}}})}var scopeTypes=[namedTypes.Program,namedTypes.Function,namedTypes.CatchClause];var ScopeType=Type.or.apply(Type,scopeTypes);Scope.isEstablishedBy=function(node){return ScopeType.check(node)};var Sp=Scope.prototype;Sp.didScan=false;Sp.declares=function(name){this.scan();return hasOwn.call(this.bindings,name)};Sp.declareTemporary=function(prefix){if(prefix){assert.ok(/^[a-z$_]/i.test(prefix),prefix)}else{prefix="t$"}prefix+=this.depth.toString(36)+"$";this.scan();var index=0;while(this.declares(prefix+index)){++index}var name=prefix+index;return this.bindings[name]=types.builders.identifier(name)};Sp.injectTemporary=function(identifier,init){identifier||(identifier=this.declareTemporary());var bodyPath=this.path.get("body");if(namedTypes.BlockStatement.check(bodyPath.value)){bodyPath=bodyPath.get("body")}bodyPath.unshift(b.variableDeclaration("var",[b.variableDeclarator(identifier,init||null)]));return identifier};Sp.scan=function(force){if(force||!this.didScan){for(var name in this.bindings){delete this.bindings[name]}scanScope(this.path,this.bindings);this.didScan=true}};Sp.getBindings=function(){this.scan();return this.bindings};function scanScope(path,bindings){var node=path.value;ScopeType.assert(node);if(namedTypes.CatchClause.check(node)){addPattern(path.get("param"),bindings)}else{recursiveScanScope(path,bindings)}}function recursiveScanScope(path,bindings){var node=path.value;if(path.parent&&namedTypes.FunctionExpression.check(path.parent.node)&&path.parent.node.id){addPattern(path.parent.get("id"),bindings)}if(!node){}else if(isArray.check(node)){path.each(function(childPath){recursiveScanChild(childPath,bindings)})}else if(namedTypes.Function.check(node)){path.get("params").each(function(paramPath){addPattern(paramPath,bindings)});recursiveScanChild(path.get("body"),bindings)}else if(namedTypes.VariableDeclarator.check(node)){addPattern(path.get("id"),bindings);recursiveScanChild(path.get("init"),bindings)}else if(node.type==="ImportSpecifier"||node.type==="ImportNamespaceSpecifier"||node.type==="ImportDefaultSpecifier"){addPattern(node.name?path.get("name"):path.get("id"),bindings)}else if(Node.check(node)&&!Expression.check(node)){types.eachField(node,function(name,child){var childPath=path.get(name);assert.strictEqual(childPath.value,child);recursiveScanChild(childPath,bindings)})}}function recursiveScanChild(path,bindings){var node=path.value;if(!node||Expression.check(node)){}else if(namedTypes.FunctionDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(namedTypes.ClassDeclaration&&namedTypes.ClassDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(ScopeType.check(node)){if(namedTypes.CatchClause.check(node)){var catchParamName=node.param.name;var hadBinding=hasOwn.call(bindings,catchParamName);recursiveScanScope(path.get("body"),bindings);if(!hadBinding){delete bindings[catchParamName]}}}else{recursiveScanScope(path,bindings)}}function addPattern(patternPath,bindings){var pattern=patternPath.value;namedTypes.Pattern.assert(pattern);if(namedTypes.Identifier.check(pattern)){if(hasOwn.call(bindings,pattern.name)){bindings[pattern.name].push(patternPath)}else{bindings[pattern.name]=[patternPath]}}else if(namedTypes.SpreadElement&&namedTypes.SpreadElement.check(pattern)){addPattern(patternPath.get("argument"),bindings)}}Sp.lookup=function(name){for(var scope=this;scope;scope=scope.parent)if(scope.declares(name))break;return scope};Sp.getGlobalScope=function(){var scope=this;while(!scope.isGlobal)scope=scope.parent;return scope};module.exports=Scope},{"./node-path":114,"./types":119,assert:122}],118:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var builtin=types.builtInTypes;var isNumber=builtin.number;exports.geq=function(than){return new Type(function(value){return isNumber.check(value)&&value>=than},isNumber+" >= "+than)};exports.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var naiveIsPrimitive=Type.or(builtin.string,builtin.number,builtin.boolean,builtin.null,builtin.undefined);exports.isPrimitive=new Type(function(value){if(value===null)return true;var type=typeof value;return!(type==="object"||type==="function")},naiveIsPrimitive.toString())},{"../lib/types":119}],119:[function(require,module,exports){var assert=require("assert");var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;var each=Ap.forEach;var Op=Object.prototype;var objToStr=Op.toString;var funObjStr=objToStr.call(function(){});var strObjStr=objToStr.call("");var hasOwn=Op.hasOwnProperty;function Type(check,name){var self=this;assert.ok(self instanceof Type,self);assert.strictEqual(objToStr.call(check),funObjStr,check+" is not a function");var nameObjStr=objToStr.call(name);assert.ok(nameObjStr===funObjStr||nameObjStr===strObjStr,name+" is neither a function nor a string");Object.defineProperties(self,{name:{value:name},check:{value:function(value,deep){var result=check.call(self,value,deep);if(!result&&deep&&objToStr.call(deep)===funObjStr)deep(self,value);return result}}})}var Tp=Type.prototype;exports.Type=Type;Tp.assert=function(value,deep){if(!this.check(value,deep)){var str=shallowStringify(value);assert.ok(false,str+" does not match type "+this);return false}return true};function shallowStringify(value){if(isObject.check(value))return"{"+Object.keys(value).map(function(key){return key+": "+value[key]}).join(", ")+"}";if(isArray.check(value))return"["+value.map(shallowStringify).join(", ")+"]";return JSON.stringify(value)}Tp.toString=function(){var name=this.name;if(isString.check(name))return name;if(isFunction.check(name))return name.call(this)+"";return name+" type"};var builtInTypes={};exports.builtInTypes=builtInTypes;function defBuiltInType(example,name){var objStr=objToStr.call(example);Object.defineProperty(builtInTypes,name,{enumerable:true,value:new Type(function(value){return objToStr.call(value)===objStr},name)});return builtInTypes[name]}var isString=defBuiltInType("","string");var isFunction=defBuiltInType(function(){},"function");var isArray=defBuiltInType([],"array");var isObject=defBuiltInType({},"object");var isRegExp=defBuiltInType(/./,"RegExp");var isDate=defBuiltInType(new Date,"Date");var isNumber=defBuiltInType(3,"number");var isBoolean=defBuiltInType(true,"boolean");var isNull=defBuiltInType(null,"null");var isUndefined=defBuiltInType(void 0,"undefined");function toType(from,name){if(from instanceof Type)return from;if(from instanceof Def)return from.type;if(isArray.check(from))return Type.fromArray(from);if(isObject.check(from))return Type.fromObject(from);if(isFunction.check(from))return new Type(from,name);return new Type(function(value){return value===from},isUndefined.check(name)?function(){return from+""}:name)}Type.or=function(){var types=[];var len=arguments.length;for(var i=0;i<len;++i)types.push(toType(arguments[i])); return new Type(function(value,deep){for(var i=0;i<len;++i)if(types[i].check(value,deep))return true;return false},function(){return types.join(" | ")})};Type.fromArray=function(arr){assert.ok(isArray.check(arr));assert.strictEqual(arr.length,1,"only one element type is permitted for typed arrays");return toType(arr[0]).arrayOf()};Tp.arrayOf=function(){var elemType=this;return new Type(function(value,deep){return isArray.check(value)&&value.every(function(elem){return elemType.check(elem,deep)})},function(){return"["+elemType+"]"})};Type.fromObject=function(obj){var fields=Object.keys(obj).map(function(name){return new Field(name,obj[name])});return new Type(function(value,deep){return isObject.check(value)&&fields.every(function(field){return field.type.check(value[field.name],deep)})},function(){return"{ "+fields.join(", ")+" }"})};function Field(name,type,defaultFn,hidden){var self=this;assert.ok(self instanceof Field);isString.assert(name);type=toType(type);var properties={name:{value:name},type:{value:type},hidden:{value:!!hidden}};if(isFunction.check(defaultFn)){properties.defaultFn={value:defaultFn}}Object.defineProperties(self,properties)}var Fp=Field.prototype;Fp.toString=function(){return JSON.stringify(this.name)+": "+this.type};Fp.getValue=function(obj){var value=obj[this.name];if(!isUndefined.check(value))return value;if(this.defaultFn)value=this.defaultFn.call(obj);return value};Type.def=function(typeName){isString.assert(typeName);return hasOwn.call(defCache,typeName)?defCache[typeName]:defCache[typeName]=new Def(typeName)};var defCache=Object.create(null);function Def(typeName){var self=this;assert.ok(self instanceof Def);Object.defineProperties(self,{typeName:{value:typeName},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new Type(function(value,deep){return self.check(value,deep)},typeName)}})}Def.fromValue=function(value){if(value&&typeof value==="object"){var type=value.type;if(typeof type==="string"&&hasOwn.call(defCache,type)){var d=defCache[type];if(d.finalized){return d}}}return null};var Dp=Def.prototype;Dp.isSupertypeOf=function(that){if(that instanceof Def){assert.strictEqual(this.finalized,true);assert.strictEqual(that.finalized,true);return hasOwn.call(that.allSupertypes,this.typeName)}else{assert.ok(false,that+" is not a Def")}};exports.getSupertypeNames=function(typeName){assert.ok(hasOwn.call(defCache,typeName));var d=defCache[typeName];assert.strictEqual(d.finalized,true);return d.supertypeList.slice(1)};exports.computeSupertypeLookupTable=function(candidates){var table={};var typeNames=Object.keys(defCache);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];var d=defCache[typeName];assert.strictEqual(d.finalized,true);for(var j=0;j<d.supertypeList.length;++j){var superTypeName=d.supertypeList[j];if(hasOwn.call(candidates,superTypeName)){table[typeName]=superTypeName;break}}}return table};Dp.checkAllFields=function(value,deep){var allFields=this.allFields;assert.strictEqual(this.finalized,true);function checkFieldByName(name){var field=allFields[name];var type=field.type;var child=field.getValue(value);return type.check(child,deep)}return isObject.check(value)&&Object.keys(allFields).every(checkFieldByName)};Dp.check=function(value,deep){assert.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!isObject.check(value))return false;var vDef=Def.fromValue(value);if(!vDef){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(value,deep)}return false}if(deep&&vDef===this)return this.checkAllFields(value,deep);if(!this.isSupertypeOf(vDef))return false;if(!deep)return true;return vDef.checkAllFields(value,deep)&&this.checkAllFields(value,false)};Dp.bases=function(){var bases=this.baseNames;assert.strictEqual(this.finalized,false);each.call(arguments,function(baseName){isString.assert(baseName);if(bases.indexOf(baseName)<0)bases.push(baseName)});return this};Object.defineProperty(Dp,"buildable",{value:false});var builders={};exports.builders=builders;var nodePrototype={};exports.defineMethod=function(name,func){var old=nodePrototype[name];if(isUndefined.check(func)){delete nodePrototype[name]}else{isFunction.assert(func);Object.defineProperty(nodePrototype,name,{enumerable:true,configurable:true,value:func})}return old};Dp.build=function(){var self=this;Object.defineProperty(self,"buildParams",{value:slice.call(arguments),writable:false,enumerable:false,configurable:true});assert.strictEqual(self.finalized,false);isString.arrayOf().assert(self.buildParams);if(self.buildable){return self}self.field("type",self.typeName,function(){return self.typeName});Object.defineProperty(self,"buildable",{value:true});Object.defineProperty(builders,getBuilderName(self.typeName),{enumerable:true,value:function(){var args=arguments;var argc=args.length;var built=Object.create(nodePrototype);assert.ok(self.finalized,"attempting to instantiate unfinalized type "+self.typeName);function add(param,i){if(hasOwn.call(built,param))return;var all=self.allFields;assert.ok(hasOwn.call(all,param),param);var field=all[param];var type=field.type;var value;if(isNumber.check(i)&&i<argc){value=args[i]}else if(field.defaultFn){value=field.defaultFn.call(built)}else{var message="no value or default function given for field "+JSON.stringify(param)+" of "+self.typeName+"("+self.buildParams.map(function(name){return all[name]}).join(", ")+")";assert.ok(false,message)}if(!type.check(value)){assert.ok(false,shallowStringify(value)+" does not match field "+field+" of type "+self.typeName)}built[param]=value}self.buildParams.forEach(function(param,i){add(param,i)});Object.keys(self.allFields).forEach(function(param){add(param)});assert.strictEqual(built.type,self.typeName);return built}});return self};function getBuilderName(typeName){return typeName.replace(/^[A-Z]+/,function(upperCasePrefix){var len=upperCasePrefix.length;switch(len){case 0:return"";case 1:return upperCasePrefix.toLowerCase();default:return upperCasePrefix.slice(0,len-1).toLowerCase()+upperCasePrefix.charAt(len-1)}})}Dp.field=function(name,type,defaultFn,hidden){assert.strictEqual(this.finalized,false);this.ownFields[name]=new Field(name,type,defaultFn,hidden);return this};var namedTypes={};exports.namedTypes=namedTypes;function getFieldNames(object){var d=Def.fromValue(object);if(d){return d.fieldNames.slice(0)}if("type"in object){assert.ok(false,"did not recognize object of type "+JSON.stringify(object.type))}return Object.keys(object)}exports.getFieldNames=getFieldNames;function getFieldValue(object,fieldName){var d=Def.fromValue(object);if(d){var field=d.allFields[fieldName];if(field){return field.getValue(object)}}return object[fieldName]}exports.getFieldValue=getFieldValue;exports.eachField=function(object,callback,context){getFieldNames(object).forEach(function(name){callback.call(this,name,getFieldValue(object,name))},context)};exports.someField=function(object,callback,context){return getFieldNames(object).some(function(name){return callback.call(this,name,getFieldValue(object,name))},context)};Object.defineProperty(Dp,"finalized",{value:false});Dp.finalize=function(){if(!this.finalized){var allFields=this.allFields;var allSupertypes=this.allSupertypes;this.baseNames.forEach(function(name){var def=defCache[name];def.finalize();extend(allFields,def.allFields);extend(allSupertypes,def.allSupertypes)});extend(allFields,this.ownFields);allSupertypes[this.typeName]=this;this.fieldNames.length=0;for(var fieldName in allFields){if(hasOwn.call(allFields,fieldName)&&!allFields[fieldName].hidden){this.fieldNames.push(fieldName)}}Object.defineProperty(namedTypes,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});populateSupertypeList(this.typeName,this.supertypeList)}};function populateSupertypeList(typeName,list){list.length=0;list.push(typeName);var lastSeen=Object.create(null);for(var pos=0;pos<list.length;++pos){typeName=list[pos];var d=defCache[typeName];assert.strictEqual(d.finalized,true);if(hasOwn.call(lastSeen,typeName)){delete list[lastSeen[typeName]]}lastSeen[typeName]=pos;list.push.apply(list,d.baseNames)}for(var to=0,from=to,len=list.length;from<len;++from){if(hasOwn.call(list,from)){list[to++]=list[from]}}list.length=to}function extend(into,from){Object.keys(from).forEach(function(name){into[name]=from[name]});return into}exports.finalize=function(){Object.keys(defCache).forEach(function(name){defCache[name].finalize()})}},{assert:122}],120:[function(require,module,exports){var types=require("./lib/types");require("./def/core");require("./def/es6");require("./def/es7");require("./def/mozilla");require("./def/e4x");require("./def/fb-harmony");types.finalize();exports.Type=types.Type;exports.builtInTypes=types.builtInTypes;exports.namedTypes=types.namedTypes;exports.builders=types.builders;exports.defineMethod=types.defineMethod;exports.getFieldNames=types.getFieldNames;exports.getFieldValue=types.getFieldValue;exports.eachField=types.eachField;exports.someField=types.someField;exports.getSupertypeNames=types.getSupertypeNames;exports.astNodesAreEquivalent=require("./lib/equiv");exports.finalize=types.finalize;exports.NodePath=require("./lib/node-path");exports.PathVisitor=require("./lib/path-visitor");exports.visit=exports.PathVisitor.visit},{"./def/core":107,"./def/e4x":108,"./def/es6":109,"./def/es7":110,"./def/fb-harmony":111,"./def/mozilla":112,"./lib/equiv":113,"./lib/node-path":114,"./lib/path-visitor":115,"./lib/types":119}],121:[function(require,module,exports){},{}],122:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&!isFinite(value)){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(util.isPrimitive(a)||util.isPrimitive(b)){return a===b}var aIsArgs=isArguments(a),bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return false;if(aIsArgs){a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}var ka=objectKeys(a),kb=objectKeys(b),key,i;if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":147}],123:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;var rootParent={};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()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){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(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){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){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}}if(length>0&&length<=Buffer.poolSize)buf.parent=rootParent;return buf}function SlowBuffer(subject,encoding,noZero){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding,noZero);var buf=new Buffer(subject,encoding,noZero);delete buf.parent;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};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;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)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};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}}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.length-offset),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.length-offset),buf,offset,length,2);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;if(length<0||offset<0||offset>this.length)throw new RangeError("attempt to write outside buffer bounds");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]<=127){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]&127)}return ret}function binarySlice(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 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;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}}if(newBuf.length)newBuf.parent=this.parent||this;return newBuf};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.readUIntLE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;return val};Buffer.prototype.readUIntBE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256))val+=this[offset+--byteLength]*mul;return val};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]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256))val+=this[offset+--i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-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&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760: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 RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range")}Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,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=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<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,65535,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,65535,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=4294967295+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&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,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,4294967295,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.writeIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=0;var mul=1;var sub=value<0?1:0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=byteLength-1;var mul=1;var sub=value<0?1:0;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+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,32767,-32768);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,32767,-32768);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,2147483647,-2147483648); 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,2147483647,-2147483648);if(value<0)value=4294967295+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 RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range");if(offset<0)throw new RangeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);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.7976931348623157e308,-1.7976931348623157e308);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)};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.length)target_start=target.length;if(!target_start)target_start=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||source.length===0)return 0;if(target_start<0)throw new RangeError("targetStart out of bounds");if(start<0||start>=source.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");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<1e3||!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)}return len};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 RangeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new RangeError("start out of bounds");if(end<0||end>this.length)throw new RangeError("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};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")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;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.readUIntLE=BP.readUIntLE;arr.readUIntBE=BP.readUIntBE;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readIntLE=BP.readIntLE;arr.readIntBE=BP.readIntBE;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.writeUIntLE=BP.writeUIntLE;arr.writeUIntBE=BP.writeUIntBE;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeIntLE=BP.writeIntLE;arr.writeIntBE=BP.writeIntBE;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){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";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(string,units){var codePoint,length=string.length;var leadSurrogate=null;units=units||Infinity;var bytes=[];var i=0;for(;i<length;i++){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(leadSurrogate){if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}else{codePoint=leadSurrogate-55296<<10|codePoint-56320|65536;leadSurrogate=null}}else{if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}else{leadSurrogate=codePoint;continue}}}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=null}if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<2097152){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length,unitSize){if(unitSize)length-=length%unitSize;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(65533)}}},{"base64-js":124,ieee754:125,"is-array":126}],124:[function(require,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);var PLUS_URL_SAFE="-".charCodeAt(0);var SLASH_URL_SAFE="_".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS||code===PLUS_URL_SAFE)return 62;if(code===SLASH||code===SLASH_URL_SAFE)return 63;if(code<NUMBER)return-1;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")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);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&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}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&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}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)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],125:[function(require,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&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],126:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],127:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;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:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],128:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],129:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],130:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){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(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};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();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)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};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("/"))};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){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];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}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,require("_process"))},{_process:131}],131:[function(require,module,exports){var process=module.exports={};var queue=[];var draining=false;function drainQueue(){if(draining){return}draining=true;var currentQueue;var len=queue.length;while(len){currentQueue=queue;queue=[];var i=-1;while(++i<len){currentQueue[i]()}len=queue.length}draining=false}process.nextTick=function(fun){queue.push(fun);if(!draining){setTimeout(drainQueue,0)}};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";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}},{}],132:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":133}],133:[function(require,module,exports){(function(process){module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);forEach(objectKeys(Writable.prototype),function(method){if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]});function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}}).call(this,require("_process"))},{"./_stream_readable":135,"./_stream_writable":137,_process:131,"core-util-is":138,inherits:128}],134:[function(require,module,exports){module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":136,"core-util-is":138,inherits:128}],135:[function(require,module,exports){(function(process){module.exports=Readable;var isArray=require("isarray");var Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;if(!EE.listenerCount)EE.listenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream=require("stream");var util=require("core-util-is");util.inherits=require("inherits");var StringDecoder;util.inherits(Readable,Stream);function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!options.objectMode;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(typeof chunk==="string"&&!state.objectMode){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null||chunk===undefined){state.reading=false;if(!state.ended)onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);state.length+=state.objectMode?1:chunk.length;if(addToFront){state.buffer.unshift(chunk)}else{state.reading=false;state.buffer.push(chunk)}if(state.needReadable)emitReadable(stream);maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc};var MAX_HWM=8388608;function roundUpToNextPowerOf2(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=roundUpToNextPowerOf2(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else return state.length}return n}Readable.prototype.read=function(n){var state=this._readableState;state.calledRead=true;var nOrig=n;var ret;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){ret=null;if(state.length>0&&state.decoder){ret=fromList(n,state);state.length-=ret.length}if(state.length===0)endReadable(this);return ret}var doRead=state.needReadable;if(state.length-n<=state.highWaterMark)doRead=true;if(state.ended||state.reading)doRead=false;if(doRead){state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(state.ended&&!state.endEmitted&&state.length===0)endReadable(this);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.length>0)emitReadable(stream);else endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(state.emittedReadable)return;state.emittedReadable=true;if(state.sync)process.nextTick(function(){emitReadable_(stream)});else emitReadable_(stream)}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(function(){maybeReadMore_(stream,state)})}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);break}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){if(readable!==src)return;cleanup()}function onend(){dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);function cleanup(){dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);if(!dest._writableState||dest._writableState.needDrain)ondrain()}function onerror(er){unpipe();dest.removeListener("error",onerror);if(EE.listenerCount(dest,"error")===0)dest.emit("error",er)}if(!dest._events||!dest._events.error)dest.on("error",onerror);else if(isArray(dest._events.error))dest._events.error.unshift(onerror);else dest._events.error=[onerror,dest._events.error];function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){this.on("readable",pipeOnReadable);state.flowing=true;process.nextTick(function(){flow(src)})}return dest};function pipeOnDrain(src){return function(){var dest=this;var state=src._readableState;state.awaitDrain--;if(state.awaitDrain===0)flow(src)}}function flow(src){var state=src._readableState;var chunk;state.awaitDrain=0;function write(dest,i,list){var written=dest.write(chunk);if(false===written){state.awaitDrain++}}while(state.pipesCount&&null!==(chunk=src.read())){if(state.pipesCount===1)write(state.pipes,0,null);else forEach(state.pipes,write);src.emit("data",chunk);if(state.awaitDrain>0)return}if(state.pipesCount===0){state.flowing=false;if(EE.listenerCount(src,"data")>0)emitDataEvents(src);return}state.ranOut=true}function pipeOnReadable(){if(this._readableState.ranOut){this._readableState.ranOut=false;flow(this)}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);if(i===-1)return this;state.pipes.splice(i,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"&&!this._readableState.flowing)emitDataEvents(this);if(ev==="readable"&&this.readable){var state=this._readableState;if(!state.readableListening){state.readableListening=true;state.emittedReadable=false;state.needReadable=true;if(!state.reading){this.read(0)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.resume=function(){emitDataEvents(this);this.read(0);this.emit("resume")};Readable.prototype.pause=function(){emitDataEvents(this,true);this.emit("pause") };function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing){throw new Error("Cannot switch to old mode now.")}var paused=startPaused||false;var readable=false;stream.readable=true;stream.pipe=Stream.prototype.pipe;stream.on=stream.addListener=Stream.prototype.on;stream.on("readable",function(){readable=true;var c;while(!paused&&null!==(c=stream.read()))stream.emit("data",c);if(c===null){readable=false;stream._readableState.needReadable=true}});stream.pause=function(){paused=true;this.emit("pause")};stream.resume=function(){paused=false;if(readable)process.nextTick(function(){stream.emit("readable")});else this.read(0);this.emit("resume")};stream.emit("readable")}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(typeof stream[i]==="function"&&typeof this[i]==="undefined"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){var list=state.buffer;var length=state.length;var stringMode=!!state.decoder;var objectMode=!!state.objectMode;var ret;if(list.length===0)return null;if(length===0)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length){if(stringMode)ret=list.join("");else ret=Buffer.concat(list,length);list.length=0}else{if(n<list[0].length){var buf=list[0];ret=buf.slice(0,n);list[0]=buf.slice(n)}else if(n===list[0].length){ret=list.shift()}else{if(stringMode)ret="";else ret=new Buffer(n);var c=0;for(var i=0,l=list.length;i<l&&c<n;i++){var buf=list[0];var cpy=Math.min(n-c,buf.length);if(stringMode)ret+=buf.slice(0,cpy);else buf.copy(ret,c,0,cpy);if(cpy<buf.length)list[0]=buf.slice(cpy);else list.shift();c+=cpy}}}return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error("endReadable called on non-empty stream");if(!state.endEmitted&&state.calledRead){state.ended=true;process.nextTick(function(){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}})}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{_process:131,buffer:123,"core-util-is":138,events:127,inherits:128,isarray:129,stream:143,"string_decoder/":144}],136:[function(require,module,exports){module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);if(cb)cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);var ts=this._transformState=new TransformState(options,this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(er){done(stream,er)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er){if(er)return stream.emit("error",er);var ws=stream._writableState;var rs=stream._readableState;var ts=stream._transformState;if(ws.length)throw new Error("calling transform done when ws.length != 0");if(ts.transforming)throw new Error("calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":133,"core-util-is":138,inherits:128}],137:[function(require,module,exports){(function(process){module.exports=Writable;var Buffer=require("buffer").Buffer;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream=require("stream");util.inherits(Writable,Stream);function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb}function WritableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.objectMode=!!options.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function Writable(options){var Duplex=require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function writeAfterEnd(stream,state,cb){var er=new Error("write after end");stream.emit("error",er);process.nextTick(function(){cb(er)})}function validChunk(stream,state,chunk,cb){var valid=true;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){var er=new TypeError("Invalid non-string/buffer chunk");stream.emit("error",er);process.nextTick(function(){cb(er)});valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=function(){};if(state.ended)writeAfterEnd(this,state,cb);else if(validChunk(this,state,chunk,cb))ret=writeOrBuffer(this,state,chunk,encoding,cb);return ret};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=new Buffer(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing)state.buffer.push(new WriteReq(chunk,encoding,cb));else doWrite(stream,state,len,chunk,encoding,cb);return ret}function doWrite(stream,state,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){if(sync)process.nextTick(function(){cb(er)});else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(stream,state);if(!finished&&!state.bufferProcessing&&state.buffer.length)clearBuffer(stream,state);if(sync){process.nextTick(function(){afterWrite(stream,state,finished,cb)})}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);cb();if(finished)finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;for(var c=0;c<state.buffer.length;c++){var entry=state.buffer[c];var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,len,chunk,encoding,cb);if(state.writing){c++;break}}state.bufferProcessing=false;if(c<state.buffer.length)state.buffer=state.buffer.slice(c);else state.buffer.length=0}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))};Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(typeof chunk!=="undefined"&&chunk!==null)this.write(chunk,encoding);if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(stream,state){return state.ending&&state.length===0&&!state.finished&&!state.writing}function finishMaybe(stream,state){var need=needFinish(stream,state);if(need){state.finished=true;stream.emit("finish")}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)process.nextTick(cb);else stream.once("finish",cb)}state.ended=true}}).call(this,require("_process"))},{"./_stream_duplex":133,_process:131,buffer:123,"core-util-is":138,inherits:128,stream:143}],138:[function(require,module,exports){(function(Buffer){function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;function isBuffer(arg){return Buffer.isBuffer(arg)}exports.isBuffer=isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,require("buffer").Buffer)},{buffer:123}],139:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":134}],140:[function(require,module,exports){var Stream=require("stream");exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=Stream;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":133,"./lib/_stream_passthrough.js":134,"./lib/_stream_readable.js":135,"./lib/_stream_transform.js":136,"./lib/_stream_writable.js":137,stream:143}],141:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":136}],142:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":137}],143:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:127,inherits:128,"readable-stream/duplex.js":132,"readable-stream/passthrough.js":139,"readable-stream/readable.js":140,"readable-stream/transform.js":141,"readable-stream/writable.js":142}],144:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.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 true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:123}],145:[function(require,module,exports){exports.isatty=function(){return false};function ReadStream(){throw new Error("tty.ReadStream is not implemented")}exports.ReadStream=ReadStream;function WriteStream(){throw new Error("tty.ReadStream is not implemented")}exports.WriteStream=WriteStream},{}],146:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],147:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":146,_process:131,inherits:128}],148:[function(require,module,exports){"use strict";var escapeStringRegexp=require("escape-string-regexp");var ansiStyles=require("ansi-styles");var stripAnsi=require("strip-ansi");var hasAnsi=require("has-ansi");var supportsColor=require("supports-color");var defineProps=Object.defineProperties;var chalk=module.exports;function build(_styles){var builder=function builder(){return applyStyle.apply(builder,arguments)};builder._styles=_styles;builder.__proto__=proto;return builder}var styles=function(){var ret={};ansiStyles.grey=ansiStyles.gray;Object.keys(ansiStyles).forEach(function(key){ansiStyles[key].closeRe=new RegExp(escapeStringRegexp(ansiStyles[key].close),"g");ret[key]={get:function(){return build(this._styles.concat(key))}}});return ret}();var proto=defineProps(function chalk(){},styles);function applyStyle(){var args=arguments;var argsLen=args.length;var str=argsLen!==0&&String(arguments[0]);if(argsLen>1){for(var a=1;a<argsLen;a++){str+=" "+args[a]}}if(!chalk.enabled||!str){return str}var nestedStyles=this._styles;for(var i=0;i<nestedStyles.length;i++){var code=ansiStyles[nestedStyles[i]];str=code.open+str.replace(code.closeRe,code.open)+code.close}return str}function init(){var ret={};Object.keys(styles).forEach(function(name){ret[name]={get:function(){return build([name])}}});return ret}defineProps(chalk,init());chalk.styles=ansiStyles;chalk.hasColor=hasAnsi;chalk.stripColor=stripAnsi;chalk.supportsColor=supportsColor;if(chalk.enabled===undefined){chalk.enabled=chalk.supportsColor}},{"ansi-styles":149,"escape-string-regexp":150,"has-ansi":151,"strip-ansi":153,"supports-color":155}],149:[function(require,module,exports){"use strict";var styles=module.exports;var codes={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]};Object.keys(codes).forEach(function(key){var val=codes[key];var style=styles[key]={};style.open="["+val[0]+"m";style.close="["+val[1]+"m"})},{}],150:[function(require,module,exports){"use strict";var matchOperatorsRe=/[|\\{}()[\]^$+*?.]/g;module.exports=function(str){if(typeof str!=="string"){throw new TypeError("Expected a string")}return str.replace(matchOperatorsRe,"\\$&")}},{}],151:[function(require,module,exports){"use strict";var ansiRegex=require("ansi-regex");var re=new RegExp(ansiRegex().source);module.exports=re.test.bind(re)},{"ansi-regex":152}],152:[function(require,module,exports){"use strict";module.exports=function(){return/\u001b\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]/g}},{}],153:[function(require,module,exports){"use strict";var ansiRegex=require("ansi-regex")();module.exports=function(str){return typeof str==="string"?str.replace(ansiRegex,""):str}},{"ansi-regex":154}],154:[function(require,module,exports){arguments[4][152][0].apply(exports,arguments)},{dup:152}],155:[function(require,module,exports){(function(process){"use strict";module.exports=function(){if(process.argv.indexOf("--no-color")!==-1){return false}if(process.argv.indexOf("--color")!==-1){return true}if(process.stdout&&!process.stdout.isTTY){return false}if(process.platform==="win32"){return true}if("COLORTERM"in process.env){return true}if(process.env.TERM==="dumb"){return false}if(/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)){return true}return false}()}).call(this,require("_process"))},{_process:131}],156:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT="."; function isObject(it){return it!=null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var buildIn={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return it==undefined?it===undefined?"Undefined":"Null":toString.call(it).slice(8,-1)}function classof(it){var klass=cof(it),tag;return klass==OBJECT&&(tag=it[SYMBOL_TAG])?has(buildIn,tag)?"~"+tag:tag:klass}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}function construct(target,argumentsList){var proto=assertFunction(arguments.length<3?target:arguments[2])[PROTOTYPE],instance=create(isObject(proto)?proto:ObjectProto),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,isFrozen=Object.isFrozen,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict;function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=toObject(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},DOT,ObjectProto)}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_SPECIES=getWellKnownSymbol("species");function setSpecies(C){if(framework||!isNative(C))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}$define(GLOBAL+FORCED,{global:global});!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description);AllSymbols[tag]=true;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return set(create(Symbol[PROTOTYPE]),TAG,tag)};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(key);return result}})}(safeSymbol("tag"),{},{},true);!function(RegExpProto,isFinite,tmp,NAME){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(x){return(x=+x)==0||x!=x?x:x<0?-1:1},E=Math.E,pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,fcc=String.fromCharCode,at=createPointAt(true);var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt});$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fcc(code):fcc(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}});defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)});$define(STATIC,ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapfn=arguments[1],that=arguments[2],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,that,2):undefined,index=0,length;if(isIterable(O))for(var iter=getIterator(O),step;!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(length=toLength(O.length);length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length)return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];setToStringTag(global.JSON,"JSON",true);function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames");if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});NAME in FunctionProto||defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}});if(DESC&&!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){var _RegExp=RegExp;RegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};forEach.call(getNames(_RegExp),function(key){key in RegExp||defineProperty(RegExp,key,{configurable:true,get:function(){return _RegExp[key]},set:function(it){_RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=RegExp;RegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,RegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")});forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}setSpecies(RegExp);setSpecies(Array)}(RegExp[PROTOTYPE],isFinite,{},"name");isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(part.call(run,id),0)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&&notify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&DEF in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),O1=safeSymbol("O1"),WEAK=safeSymbol("weak"),LEAK=safeSymbol("leak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0,tmp={};function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];if(framework)proto[key]=function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result}}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,FOR_EACH)&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,O1,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto;if(framework)proto[CONSTRUCTOR]=C}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){return iter.o=undefined,iterResult(1)}if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,UID)){if(!create)return"E";hidden(it,UID,++uid)}return"O"+it[UID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}function def(that,key,value){var entry=getEntry(that,key),prev,index;if(entry)entry.v=value;else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that}var collectionMethods={clear:function(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;entry.p=entry.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return!!getEntry(this,key)}};Map=getCollection(Map,MAP,{get:function(key){var entry=getEntry(this,key);return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function defWeak(that,key,value){if(isFrozen(assertObject(key)))leakStore(that).set(key,value);else{has(key,WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value}return that}function leakStore(that){return that[LEAK]||hidden(that,LEAK,new Map)[LEAK]}var weakMethods={"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return has(key,WEAK)&&has(key[WEAK],this[UID])&&delete key[WEAK][this[UID]]},has:function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);return has(key,WEAK)&&has(key[WEAK],this[UID])}};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[UID]]}},set:function(key,value){return defWeak(this,key,value)}},weakMethods,true,true);if(framework&&DESC&&new WeakMap([[Object.freeze(tmp),7]]).get(tmp)!=7){forEach.call(array("delete,has,get,set"),function(key){var method=WeakMap[PROTOTYPE][key];WeakMap[PROTOTYPE][key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result}return method.call(this,a,b)}})}WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return defWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return desc.get?desc.get.call(receiver):desc.value;return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc){if(desc.writable===false)return false;if(desc.set)return desc.set.call(receiver,V),true}if(isObject(proto=getPrototypeOf(target)))return reflectSet(proto,propertyKey,V,receiver);desc=getOwnDescriptor(receiver,propertyKey)||descriptor(0);desc.value=V;return defineProperty(receiver,propertyKey,desc),true}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet}; if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList);!function(DICT){Dict=function(iterable){var dict=create(null);if(iterable!=undefined){if(isIterable(iterable)){for(var iter=getIterator(iterable),step,value;!(step=iter.next()).done;){value=step.value;dict[value[0]]=value[1]}}else assign(dict,iterable)}return dict};Dict[PROTOTYPE]=null;function DictIterator(iterated,kind){set(this,ITER,{o:toObject(iterated),a:getKeys(iterated),i:0,k:kind})}createIterator(DictIterator,DICT,function(){var iter=this[ITER],O=iter.o,keys=iter.a,kind=iter.k,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!has(O,key=keys[iter.i++]));if(kind==KEY)return iterResult(0,key);if(kind==VALUE)return iterResult(0,O[key]);return iterResult(0,[key,O[key]])});function createDictIter(kind){return function(it){return new DictIterator(it,kind)}}function createDictMethod(type){var isMap=type==1,isEvery=type==4;return function(object,callbackfn,that){var f=ctx(callbackfn,that,3),O=toObject(object),result=isMap||type==7||type==2?new(generic(this,Dict)):undefined,key,val,res;for(key in O)if(has(O,key)){val=O[key];res=f(val,key,object);if(type){if(isMap)result[key]=res;else if(res)switch(type){case 2:result[key]=val;break;case 3:return true;case 5:return val;case 6:return key;case 7:result[res[0]]=res[1]}else if(isEvery)return false}}return type==3||isEvery?isEvery:result}}function createDictReduce(isTurn){return function(object,mapfn,init){assertFunction(mapfn);var O=toObject(object),keys=getKeys(O),length=keys.length,i=0,memo,key,result;if(isTurn)memo=init==undefined?new(generic(this,Dict)):Object(init);else if(arguments.length<3){assert(length,REDUCE_ERROR);memo=O[keys[i++]]}else memo=Object(init);while(length>i)if(has(O,key=keys[i++])){result=mapfn(memo,O[key],key,object);if(isTurn){if(result===false)break}else memo=result}return memo}}var findKey=createDictMethod(6);function includes(object,el){return(el==el?keyOf(object,el):findKey(object,sameNaN))!==undefined}var dictMethods={keys:createDictIter(KEY),values:createDictIter(VALUE),entries:createDictIter(KEY+VALUE),forEach:createDictMethod(0),map:createDictMethod(1),filter:createDictMethod(2),some:createDictMethod(3),every:createDictMethod(4),find:createDictMethod(5),findKey:findKey,mapPairs:createDictMethod(7),reduce:createDictReduce(false),turn:createDictReduce(true),keyOf:keyOf,includes:includes,has:has,get:get,set:createDefiner(0),isDict:function(it){return isObject(it)&&getPrototypeOf(it)===Dict[PROTOTYPE]}};if(REFERENCE_GET)for(var key in dictMethods)!function(fn){function method(){for(var args=[this],i=0;i<arguments.length;)args.push(arguments[i++]);return invoke(fn,args)}fn[REFERENCE_GET]=function(){return method}}(dictMethods[key]);$define(GLOBAL+FORCED,{Dict:assignHidden(Dict,dictMethods)})}("Dict");!function(ENTRIES,FN){function $for(iterable,entries){if(!(this instanceof $for))return new $for(iterable,entries);this[ITER]=getIterator(iterable);this[ENTRIES]=!!entries}createIterator($for,"Wrapper",function(){return this[ITER].next()});var $forProto=$for[PROTOTYPE];setIterator($forProto,function(){return this[ITER]});function createChainIterator(next){function Iter(I,fn,that){this[ITER]=getIterator(I);this[ENTRIES]=I[ENTRIES];this[FN]=ctx(fn,that,I[ENTRIES]?2:1)}createIterator(Iter,"Chain",next,$forProto);setIterator(Iter[PROTOTYPE],returnThis);return Iter}var MapIter=createChainIterator(function(){var step=this[ITER].next();return step.done?step:iterResult(0,stepCall(this[FN],step.value,this[ENTRIES]))});var FilterIter=createChainIterator(function(){for(;;){var step=this[ITER].next();if(step.done||stepCall(this[FN],step.value,this[ENTRIES]))return step}});assignHidden($forProto,{of:function(fn,that){forOf(this,this[ENTRIES],fn,that)},array:function(fn,that){var result=[];forOf(fn!=undefined?this.map(fn,that):this,false,push,result);return result},filter:function(fn,that){return new FilterIter(this,fn,that)},map:function(fn,that){return new MapIter(this,fn,that)}});$for.isIterable=isIterable;$for.getIterator=getIterator;$define(GLOBAL+FORCED,{$for:$for})}("entries",safeSymbol("fn"));!function(_,toLocaleString){core._=path._=path._||{};$define(PROTO+FORCED,FUNCTION,{part:part,only:function(numberArguments,that){var fn=assertFunction(this),n=toLength(numberArguments),isThat=arguments.length>1;return function(){var length=min(n,arguments.length),args=Array(length),i=0;while(length>i)args[i]=arguments[i++];return invoke(fn,args,isThat?that:this)}}});function tie(key){var that=this,bound={};return hidden(that,_,function(key){if(key===undefined||!(key in that))return toLocaleString.call(that);return has(bound,key)?bound[key]:bound[key]=ctx(that[key],that,-1)})[_](key)}hidden(path._,TO_STRING,function(){return _});hidden(ObjectProto,_,tie);DESC||hidden(ArrayProto,_,tie)}(DESC?uid("tie"):TO_LOCALE,ObjectProto[TO_LOCALE]);!function(){function define(target,mixin){var keys=ownKeys(toObject(mixin)),length=keys.length,i=0,key;while(length>i)defineProperty(target,key=keys[i++],getOwnDescriptor(mixin,key));return target}$define(STATIC+FORCED,OBJECT,{isObject:isObject,classof:classof,define:define,make:function(proto,mixin){return define(create(proto),mixin)}})}();$define(PROTO+FORCED,ARRAY,{turn:function(fn,target){assertFunction(fn);var memo=target==undefined?[]:Object(target),O=ES5Object(this),length=toLength(O.length),index=0;while(length>index)if(fn(memo,O[index],index++,this)===false)break;return memo}});if(framework)ArrayUnscopables.turn=true;!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({});!function(numberMethods){function NumberIterator(iterated){set(this,ITER,{l:toLength(iterated),i:0})}createIterator(NumberIterator,NUMBER,function(){var iter=this[ITER],i=iter.i++;return i<iter.l?iterResult(0,i):iterResult(1)});defineIterator(Number,NUMBER,function(){return new NumberIterator(this)});numberMethods.random=function(lim){var a=+this,b=lim==undefined?0:+lim,m=min(a,b);return random()*(max(a,b)-m)+m};forEach.call(array("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,"+"acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc"),function(key){var fn=Math[key];if(fn)numberMethods[key]=function(){var args=[+this],i=0;while(arguments.length>i)args.push(arguments[i++]);return invoke(fn,args)}});$define(PROTO+FORCED,NUMBER,numberMethods)}({});!function(){var escapeHTMLDict={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"},unescapeHTMLDict={},key;for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]]=key;$define(PROTO+FORCED,STRING,{escapeHTML:createReplacer(/[&<>"']/g,escapeHTMLDict),unescapeHTML:createReplacer(/&(?:amp|lt|gt|quot|apos);/g,unescapeHTMLDict)})}();!function(formatRegExp,flexioRegExp,locales,current,SECONDS,MINUTES,HOURS,MONTH,YEAR){function createFormat(prefix){return function(template,locale){var that=this,dict=locales[has(locales,locale)?locale:current];function get(unit){return that[prefix+unit]()}return String(template).replace(formatRegExp,function(part){switch(part){case"s":return get(SECONDS);case"ss":return lz(get(SECONDS));case"m":return get(MINUTES);case"mm":return lz(get(MINUTES));case"h":return get(HOURS);case"hh":return lz(get(HOURS));case"D":return get(DATE);case"DD":return lz(get(DATE));case"W":return dict[0][get("Day")];case"N":return get(MONTH)+1;case"NN":return lz(get(MONTH)+1);case"M":return dict[2][get(MONTH)];case"MM":return dict[1][get(MONTH)];case"Y":return get(YEAR);case"YY":return lz(get(YEAR)%100)}return part})}}function lz(num){return num>9?num:"0"+num}function addLocale(lang,locale){function split(index){var result=[];forEach.call(array(locale.months),function(it){result.push(it.replace(flexioRegExp,"$"+index))});return result}locales[lang]=[array(locale.weekdays),split(1),split(2)];return core}$define(PROTO+FORCED,DATE,{format:createFormat("get"),formatUTC:createFormat("getUTC")});addLocale(current,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"});addLocale("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,"+"Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"});core.locale=function(locale){return has(locales,locale)?current=locale:current};core.addLocale=addLocale}(/\b\w\w?\b/g,/:(.*)\|(.*)$/,{},"en","Seconds","Minutes","Hours","Month","FullYear")}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),false)},{}],157:[function(require,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i<len;i++){if(!split[i])continue;namespaces=split[i].replace(/\*/g,".*?");if(namespaces[0]==="-"){exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$"))}else{exports.names.push(new RegExp("^"+namespaces+"$"))}}}function disable(){exports.enable("")}function enabled(name){var i,len;for(i=0,len=exports.skips.length;i<len;i++){if(exports.skips[i].test(name)){return false}}for(i=0,len=exports.names.length;i<len;i++){if(exports.names[i].test(name)){return true}}return false}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{ms:159}],158:[function(require,module,exports){(function(process){var tty=require("tty");var util=require("util");exports=module.exports=require("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=[6,2,3,4,5,1];var fd=parseInt(process.env.DEBUG_FD,10)||2;var stream=1===fd?process.stdout:2===fd?process.stderr:createWritableStdioStream(fd);function useColors(){var debugColors=(process.env.DEBUG_COLORS||"").trim().toLowerCase();if(0===debugColors.length){return tty.isatty(fd)}else{return"0"!==debugColors&&"no"!==debugColors&&"false"!==debugColors&&"disabled"!==debugColors}}var inspect=4===util.inspect.length?function(v,colors){return util.inspect(v,void 0,void 0,colors)}:function(v,colors){return util.inspect(v,{colors:colors})};exports.formatters.o=function(v){return inspect(v,this.useColors).replace(/\s*\n\s*/g," ")};function formatArgs(){var args=arguments;var useColors=this.useColors;var name=this.namespace;if(useColors){var c=this.color;args[0]=" [9"+c+"m"+name+" "+""+args[0]+"[3"+c+"m"+" +"+exports.humanize(this.diff)+""}else{args[0]=(new Date).toUTCString()+" "+name+" "+args[0]}return args}function log(){return stream.write(util.format.apply(this,arguments)+"\n")}function save(namespaces){if(null==namespaces){delete process.env.DEBUG}else{process.env.DEBUG=namespaces}}function load(){return process.env.DEBUG}function createWritableStdioStream(fd){var stream;var tty_wrap=process.binding("tty_wrap");switch(tty_wrap.guessHandleType(fd)){case"TTY":stream=new tty.WriteStream(fd);stream._type="tty";if(stream._handle&&stream._handle.unref){stream._handle.unref()}break;case"FILE":var fs=require("fs");stream=new fs.SyncWriteStream(fd,{autoClose:false});stream._type="fs";break;case"PIPE":case"TCP":var net=require("net");stream=new net.Socket({fd:fd,readable:false,writable:true});stream.readable=false;stream.read=null;stream._type="pipe";if(stream._handle&&stream._handle.unref){stream._handle.unref()}break;default:throw new Error("Implement me. Unknown stream file type!")}stream.fd=fd;stream._isStdio=true;return stream}exports.enable(load())}).call(this,require("_process"))},{"./debug":157,_process:131,fs:121,net:121,tty:145,util:147}],159:[function(require,module,exports){var s=1e3;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if("string"==typeof val)return parse(val);return options.long?long(val):short(val)};function parse(str){var match=/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"h":return n*h;case"minutes":case"minute":case"m":return n*m;case"seconds":case"second":case"s":return n*s;case"ms":return n}}function short(ms){if(ms>=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms<n)return;if(ms<n*1.5)return Math.floor(ms/n)+" "+name;return Math.ceil(ms/n)+" "+name+"s"}},{}],160:[function(require,module,exports){"use strict";var repeating=require("repeating");var INDENT_RE=/^(?:( )+|\t+)/;function getMostUsed(indents){var result=0;var maxUsed=0;var maxWeight=0;for(var n in indents){var indent=indents[n];var u=indent[0];var w=indent[1];if(u>maxUsed||u===maxUsed&&w>maxWeight){maxUsed=u;maxWeight=w;result=+n}}return result}module.exports=function(str){if(typeof str!=="string"){throw new TypeError("Expected a string")}var tabs=0;var spaces=0;var prev=0;var indents={};var current;var isIndent;str.split(/\n/g).forEach(function(line){if(!line){return}var indent;var matches=line.match(INDENT_RE);if(!matches){indent=0}else{indent=matches[0].length;if(matches[1]){spaces++}else{tabs++}}var diff=indent-prev;prev=indent;if(diff){isIndent=diff>0;current=indents[isIndent?diff:-diff];if(current){current[0]++}else{current=indents[diff]=[1,0]}}else if(current){current[1]+=+isIndent}});var amount=getMostUsed(indents);var type;var actual;if(!amount){type=null;actual=""}else if(spaces>=tabs){type="space";actual=repeating(" ",amount)}else{type="tab";actual=repeating(" ",amount)}return{amount:amount,type:type,indent:actual}}},{repeating:161}],161:[function(require,module,exports){"use strict";var isFinite=require("is-finite");module.exports=function(str,n){if(typeof str!=="string"){throw new TypeError("Expected a string as the first argument")}if(n<0||!isFinite(n)){throw new TypeError("Expected a finite positive number")}var ret="";do{if(n&1){ret+=str}str+=str}while(n=n>>1);return ret}},{"is-finite":162}],162:[function(require,module,exports){"use strict";module.exports=Number.isFinite||function(val){if(typeof val!=="number"||val!==val||val===Infinity||val===-Infinity){return false}return true}},{}],163:[function(require,module,exports){(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{factory(root.estraverse={})}})(this,function clone(exports){"use strict";var Syntax,isArray,VisitorOption,VisitorKeys,objectCreate,objectKeys,BREAK,SKIP,REMOVE;function ignoreJSHintError(){}isArray=Array.isArray;if(!isArray){isArray=function isArray(array){return Object.prototype.toString.call(array)==="[object Array]"}}function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function shallowCopy(obj){var ret={},key;for(key in obj){if(obj.hasOwnProperty(key)){ret[key]=obj[key]}}return ret}ignoreJSHintError(shallowCopy);function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}function lowerBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){i=current+1;len-=diff+1}else{len=diff}}return i}ignoreJSHintError(lowerBound);objectCreate=Object.create||function(){function F(){}return function(o){F.prototype=o;return new F}}();objectKeys=Object.keys||function(o){var keys=[],key;for(key in o){keys.push(key)}return keys};function extend(to,from){objectKeys(from).forEach(function(key){to[key]=from[key]});return to}Syntax={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",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"};VisitorKeys={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=visitor.fallback==="iteration";this.__keys=VisitorKeys;if(visitor.keys){this.__keys=extend(objectCreate(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break }if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.version="1.8.1-dev";exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller;exports.cloneEnvironment=function(){return clone({})};return exports})},{}],164:[function(require,module,exports){(function(){"use strict";function isExpression(node){if(node==null){return false}switch(node.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return true}return false}function isIterationStatement(node){if(node==null){return false}switch(node.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function isStatement(node){if(node==null){return false}switch(node.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return true}return false}function isSourceElement(node){return isStatement(node)||node!=null&&node.type==="FunctionDeclaration"}function trailingStatement(node){switch(node.type){case"IfStatement":if(node.alternate!=null){return node.alternate}return node.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return node.body}return null}function isProblematicIfStatement(node){var current;if(node.type!=="IfStatement"){return false}if(node.alternate==null){return false}current=node.consequent;do{if(current.type==="IfStatement"){if(current.alternate==null){return true}}current=trailingStatement(current)}while(current);return false}module.exports={isExpression:isExpression,isStatement:isStatement,isIterationStatement:isIterationStatement,isSourceElement:isSourceElement,isProblematicIfStatement:isProblematicIfStatement,trailingStatement:trailingStatement}})()},{}],165:[function(require,module,exports){(function(){"use strict";var Regex,NON_ASCII_WHITESPACES;Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")};function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return isDecimalDigit(ch)||97<=ch&&ch<=102||65<=ch&&ch<=70}function isOctalDigit(ch){return ch>=48&&ch<=55}NON_ASCII_WHITESPACES=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&NON_ASCII_WHITESPACES.indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch>=48&&ch<=57||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}module.exports={isDecimalDigit:isDecimalDigit,isHexDigit:isHexDigit,isOctalDigit:isOctalDigit,isWhiteSpace:isWhiteSpace,isLineTerminator:isLineTerminator,isIdentifierStart:isIdentifierStart,isIdentifierPart:isIdentifierPart}})()},{}],166:[function(require,module,exports){(function(){"use strict";var code=require("./code");function isStrictModeReservedWordES6(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function isKeywordES5(id,strict){if(!strict&&id==="yield"){return false}return isKeywordES6(id,strict)}function isKeywordES6(id,strict){if(strict&&isStrictModeReservedWordES6(id)){return true}switch(id.length){case 2:return id==="if"||id==="in"||id==="do";case 3:return id==="var"||id==="for"||id==="new"||id==="try";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}}function isReservedWordES5(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES5(id,strict)}function isReservedWordES6(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES6(id,strict)}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isIdentifierName(id){var i,iz,ch;if(id.length===0){return false}ch=id.charCodeAt(0);if(!code.isIdentifierStart(ch)||ch===92){return false}for(i=1,iz=id.length;i<iz;++i){ch=id.charCodeAt(i);if(!code.isIdentifierPart(ch)||ch===92){return false}}return true}function isIdentifierES5(id,strict){return isIdentifierName(id)&&!isReservedWordES5(id,strict)}function isIdentifierES6(id,strict){return isIdentifierName(id)&&!isReservedWordES6(id,strict)}module.exports={isKeywordES5:isKeywordES5,isKeywordES6:isKeywordES6,isReservedWordES5:isReservedWordES5,isReservedWordES6:isReservedWordES6,isRestrictedWord:isRestrictedWord,isIdentifierName:isIdentifierName,isIdentifierES5:isIdentifierES5,isIdentifierES6:isIdentifierES6}})()},{"./code":165}],167:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":164,"./code":165,"./keyword":166}],168:[function(require,module,exports){module.exports={builtin:{Array:false,ArrayBuffer:false,Boolean:false,constructor:false,Date:false,decodeURI:false,decodeURIComponent:false,encodeURI:false,encodeURIComponent:false,Error:false,eval:false,EvalError:false,Float32Array:false,Float64Array:false,Function:false,hasOwnProperty:false,Infinity:false,Int16Array:false,Int32Array:false,Int8Array:false,isFinite:false,isNaN:false,isPrototypeOf:false,JSON:false,Map:false,Math:false,NaN:false,Number:false,Object:false,parseFloat:false,parseInt:false,Promise:false,propertyIsEnumerable:false,Proxy:false,RangeError:false,ReferenceError:false,Reflect:false,RegExp:false,Set:false,String:false,Symbol:false,SyntaxError:false,System:false,toLocaleString:false,toString:false,TypeError:false,Uint16Array:false,Uint32Array:false,Uint8Array:false,Uint8ClampedArray:false,undefined:false,URIError:false,valueOf:false,WeakMap:false,WeakSet:false},nonstandard:{escape:false,unescape:false},browser:{addEventListener:false,alert:false,applicationCache:false,atob:false,Audio:false,Blob:false,blur:false,btoa:false,cancelAnimationFrame:false,CanvasGradient:false,CanvasPattern:false,CanvasRenderingContext2D:false,clearInterval:false,clearTimeout:false,close:false,closed:false,confirm:false,console:false,crypto:false,CSS:false,CustomEvent:false,DataView:false,Debug:false,defaultStatus:false,devicePixelRatio:false,dispatchEvent:false,document:false,DOMParser:false,Element:false,ElementTimeControl:false,Event:false,event:false,FileReader:false,find:false,focus:false,FormData:false,frameElement:false,frames:false,getComputedStyle:false,getSelection:false,history:false,HTMLAnchorElement:false,HTMLBaseElement:false,HTMLBlockquoteElement:false,HTMLBodyElement:false,HTMLBRElement:false,HTMLButtonElement:false,HTMLCanvasElement:false,HTMLDirectoryElement:false,HTMLDivElement:false,HTMLDListElement:false,HTMLElement:false,HTMLFieldSetElement:false,HTMLFontElement:false,HTMLFormElement:false,HTMLFrameElement:false,HTMLFrameSetElement:false,HTMLHeadElement:false,HTMLHeadingElement:false,HTMLHRElement:false,HTMLHtmlElement:false,HTMLIFrameElement:false,HTMLImageElement:false,HTMLInputElement:false,HTMLIsIndexElement:false,HTMLLabelElement:false,HTMLLayerElement:false,HTMLLegendElement:false,HTMLLIElement:false,HTMLLinkElement:false,HTMLMapElement:false,HTMLMenuElement:false,HTMLMetaElement:false,HTMLModElement:false,HTMLObjectElement:false,HTMLOListElement:false,HTMLOptGroupElement:false,HTMLOptionElement:false,HTMLParagraphElement:false,HTMLParamElement:false,HTMLPreElement:false,HTMLQuoteElement:false,HTMLScriptElement:false,HTMLSelectElement:false,HTMLStyleElement:false,HTMLTableCaptionElement:false,HTMLTableCellElement:false,HTMLTableColElement:false,HTMLTableElement:false,HTMLTableRowElement:false,HTMLTableSectionElement:false,HTMLTextAreaElement:false,HTMLTitleElement:false,HTMLUListElement:false,HTMLVideoElement:false,IDBCursor:false,IDBCursorWithValue:false,IDBDatabase:false,IDBEnvironment:false,IDBFactory:false,IDBIndex:false,IDBKeyRange:false,IDBObjectStore:false,IDBOpenDBRequest:false,IDBRequest:false,IDBTransaction:false,Image:false,indexedDB:false,innerHeight:false,innerWidth:false,Intl:false,length:false,localStorage:false,location:false,matchMedia:false,MessageChannel:false,MessageEvent:false,MessagePort:false,MouseEvent:false,moveBy:false,moveTo:false,MutationObserver:false,name:false,navigator:false,Node:false,NodeFilter:false,NodeList:false,onbeforeunload:true,onblur:true,onerror:true,onfocus:true,onload:true,onresize:true,onunload:true,open:false,openDatabase:false,opener:false,opera:false,Option:false,outerHeight:false,outerWidth:false,pageXOffset:false,pageYOffset:false,parent:false,postMessage:false,print:false,prompt:false,removeEventListener:false,requestAnimationFrame:false,resizeBy:false,resizeTo:false,screen:false,screenX:false,screenY:false,scroll:false,scrollbars:false,scrollBy:false,scrollTo:false,scrollX:false,scrollY:false,self:false,sessionStorage:false,setInterval:false,setTimeout:false,SharedWorker:false,showModalDialog:false,status:false,stop:false,SVGAElement:false,SVGAltGlyphDefElement:false,SVGAltGlyphElement:false,SVGAltGlyphItemElement:false,SVGAngle:false,SVGAnimateColorElement:false,SVGAnimatedAngle:false,SVGAnimatedBoolean:false,SVGAnimatedEnumeration:false,SVGAnimatedInteger:false,SVGAnimatedLength:false,SVGAnimatedLengthList:false,SVGAnimatedNumber:false,SVGAnimatedNumberList:false,SVGAnimatedPathData:false,SVGAnimatedPoints:false,SVGAnimatedPreserveAspectRatio:false,SVGAnimatedRect:false,SVGAnimatedString:false,SVGAnimatedTransformList:false,SVGAnimateElement:false,SVGAnimateMotionElement:false,SVGAnimateTransformElement:false,SVGAnimationElement:false,SVGCircleElement:false,SVGClipPathElement:false,SVGColor:false,SVGColorProfileElement:false,SVGColorProfileRule:false,SVGComponentTransferFunctionElement:false,SVGCSSRule:false,SVGCursorElement:false,SVGDefsElement:false,SVGDescElement:false,SVGDocument:false,SVGElement:false,SVGElementInstance:false,SVGElementInstanceList:false,SVGEllipseElement:false,SVGExternalResourcesRequired:false,SVGFEBlendElement:false,SVGFEColorMatrixElement:false,SVGFEComponentTransferElement:false,SVGFECompositeElement:false,SVGFEConvolveMatrixElement:false,SVGFEDiffuseLightingElement:false,SVGFEDisplacementMapElement:false,SVGFEDistantLightElement:false,SVGFEFloodElement:false,SVGFEFuncAElement:false,SVGFEFuncBElement:false,SVGFEFuncGElement:false,SVGFEFuncRElement:false,SVGFEGaussianBlurElement:false,SVGFEImageElement:false,SVGFEMergeElement:false,SVGFEMergeNodeElement:false,SVGFEMorphologyElement:false,SVGFEOffsetElement:false,SVGFEPointLightElement:false,SVGFESpecularLightingElement:false,SVGFESpotLightElement:false,SVGFETileElement:false,SVGFETurbulenceElement:false,SVGFilterElement:false,SVGFilterPrimitiveStandardAttributes:false,SVGFitToViewBox:false,SVGFontElement:false,SVGFontFaceElement:false,SVGFontFaceFormatElement:false,SVGFontFaceNameElement:false,SVGFontFaceSrcElement:false,SVGFontFaceUriElement:false,SVGForeignObjectElement:false,SVGGElement:false,SVGGlyphElement:false,SVGGlyphRefElement:false,SVGGradientElement:false,SVGHKernElement:false,SVGICCColor:false,SVGImageElement:false,SVGLangSpace:false,SVGLength:false,SVGLengthList:false,SVGLinearGradientElement:false,SVGLineElement:false,SVGLocatable:false,SVGMarkerElement:false,SVGMaskElement:false,SVGMatrix:false,SVGMetadataElement:false,SVGMissingGlyphElement:false,SVGMPathElement:false,SVGNumber:false,SVGNumberList:false,SVGPaint:false,SVGPathElement:false,SVGPathSeg:false,SVGPathSegArcAbs:false,SVGPathSegArcRel:false,SVGPathSegClosePath:false,SVGPathSegCurvetoCubicAbs:false,SVGPathSegCurvetoCubicRel:false,SVGPathSegCurvetoCubicSmoothAbs:false,SVGPathSegCurvetoCubicSmoothRel:false,SVGPathSegCurvetoQuadraticAbs:false,SVGPathSegCurvetoQuadraticRel:false,SVGPathSegCurvetoQuadraticSmoothAbs:false,SVGPathSegCurvetoQuadraticSmoothRel:false,SVGPathSegLinetoAbs:false,SVGPathSegLinetoHorizontalAbs:false,SVGPathSegLinetoHorizontalRel:false,SVGPathSegLinetoRel:false,SVGPathSegLinetoVerticalAbs:false,SVGPathSegLinetoVerticalRel:false,SVGPathSegList:false,SVGPathSegMovetoAbs:false,SVGPathSegMovetoRel:false,SVGPatternElement:false,SVGPoint:false,SVGPointList:false,SVGPolygonElement:false,SVGPolylineElement:false,SVGPreserveAspectRatio:false,SVGRadialGradientElement:false,SVGRect:false,SVGRectElement:false,SVGRenderingIntent:false,SVGScriptElement:false,SVGSetElement:false,SVGStopElement:false,SVGStringList:false,SVGStylable:false,SVGStyleElement:false,SVGSVGElement:false,SVGSwitchElement:false,SVGSymbolElement:false,SVGTests:false,SVGTextContentElement:false,SVGTextElement:false,SVGTextPathElement:false,SVGTextPositioningElement:false,SVGTitleElement:false,SVGTransform:false,SVGTransformable:false,SVGTransformList:false,SVGTRefElement:false,SVGTSpanElement:false,SVGUnitTypes:false,SVGURIReference:false,SVGUseElement:false,SVGViewElement:false,SVGViewSpec:false,SVGVKernElement:false,SVGZoomAndPan:false,TextDecoder:false,TextEncoder:false,TimeEvent:false,top:false,URL:false,WebGLActiveInfo:false,WebGLBuffer:false,WebGLContextEvent:false,WebGLFramebuffer:false,WebGLProgram:false,WebGLRenderbuffer:false,WebGLRenderingContext:false,WebGLShader:false,WebGLShaderPrecisionFormat:false,WebGLTexture:false,WebGLUniformLocation:false,WebSocket:false,window:false,Worker:false,XDomainRequest:false,XMLHttpRequest:false,XMLSerializer:false,XPathEvaluator:false,XPathException:false,XPathExpression:false,XPathNamespace:false,XPathNSResolver:false,XPathResult:false},worker:{importScripts:true,postMessage:true,self:true},node:{__filename:false,__dirname:false,arguments:false,Buffer:false,DataView:false,console:false,exports:true,GLOBAL:false,global:false,module:false,process:false,require:false,setTimeout:false,clearTimeout:false,setInterval:false,clearInterval:false,setImmediate:false,clearImmediate:false},amd:{require:false,define:false},mocha:{describe:false,it:false,before:false,after:false,beforeEach:false,afterEach:false,suite:false,test:false,setup:false,teardown:false,suiteSetup:false,suiteTeardown:false},jasmine:{afterAll:false,afterEach:false,beforeAll:false,beforeEach:false,describe:false,expect:false,fail:false,fdescribe:false,fit:false,it:false,jasmine:false,pending:false,spyOn:false,waits:false,waitsFor:false,xdescribe:false,xit:false},qunit:{asyncTest:false,deepEqual:false,equal:false,expect:false,module:false,notDeepEqual:false,notEqual:false,notPropEqual:false,notStrictEqual:false,ok:false,propEqual:false,QUnit:false,raises:false,start:false,stop:false,strictEqual:false,test:false,"throws":false},phantom:{phantom:true,require:true,WebPage:true,console:true,exports:true},couch:{require:false,respond:false,getRow:false,emit:false,send:false,start:false,sum:false,log:false,exports:false,module:false,provides:false},rhino:{defineClass:false,deserialize:false,gc:false,help:false,importPackage:false,java:false,load:false,loadClass:false,print:false,quit:false,readFile:false,readUrl:false,runCommand:false,seal:false,serialize:false,spawn:false,sync:false,toint32:false,version:false},wsh:{ActiveXObject:true,Enumerator:true,GetObject:true,ScriptEngine:true,ScriptEngineBuildVersion:true,ScriptEngineMajorVersion:true,ScriptEngineMinorVersion:true,VBArray:true,WSH:true,WScript:true,XDomainRequest:true},jquery:{$:false,jQuery:false},yui:{YUI:false,Y:false,YUI_config:false},shelljs:{target:false,echo:false,exit:false,cd:false,pwd:false,ls:false,find:false,cp:false,rm:false,mv:false,mkdir:false,test:false,cat:false,sed:false,grep:false,which:false,dirs:false,pushd:false,popd:false,env:false,exec:false,chmod:false,config:false,error:false,tempdir:false},prototypejs:{$:false,$$:false,$A:false,$F:false,$H:false,$R:false,$break:false,$continue:false,$w:false,Abstract:false,Ajax:false,Class:false,Enumerable:false,Element:false,Event:false,Field:false,Form:false,Hash:false,Insertion:false,ObjectRange:false,PeriodicalExecuter:false,Position:false,Prototype:false,Selector:false,Template:false,Toggle:false,Try:false,Autocompleter:false,Builder:false,Control:false,Draggable:false,Draggables:false,Droppables:false,Effect:false,Sortable:false,SortableObserver:false,Sound:false,Scriptaculous:false}}},{}],169:[function(require,module,exports){module.exports=require("./globals.json")},{"./globals.json":168}],170:[function(require,module,exports){function combine(){return new RegExp("("+[].slice.call(arguments).map(function(e){var e=e.toString();return"(?:"+e.substring(1,e.length-1)+")"}).join("|")+")")}function makeTester(rx){var s=rx.toString();return new RegExp("^"+s.substring(1,s.length-1)+"$")}var pattern={string1:/"(?:(?:\\\n|\\"|[^"\n]))*?"/,string2:/'(?:(?:\\\n|\\'|[^'\n]))*?'/,comment1:/\/\*[\s\S]*?\*\//,comment2:/\/\/.*?\n/,whitespace:/\s+/,keyword:/\b(?:var|let|for|if|else|in|class|function|return|with|case|break|switch|export|new|while|do|throw|catch)\b/,regexp:/\/(?:(?:\\\/|[^\n\/]))*?\//,name:/[a-zA-Z_\$][a-zA-Z_\$0-9]*/,number:/\d+(?:\.\d+)?(?:e[+-]?\d+)?/,parens:/[\(\)]/,curly:/[{}]/,square:/[\[\]]/,punct:/[;.:\?\^%<>=!&|+\-,~]/};var match=combine(pattern.string1,pattern.string2,pattern.comment1,pattern.comment2,pattern.regexp,pattern.whitespace,pattern.name,pattern.number,pattern.parens,pattern.curly,pattern.square,pattern.punct);var tester={};for(var k in pattern){tester[k]=makeTester(pattern[k])}module.exports=function(str,doNotThrow){return str.split(match).filter(function(e,i){if(i%2)return true;if(e!==""){if(!doNotThrow)throw new Error("invalid token:"+JSON.stringify(e));return true}})};module.exports.type=function(e){for(var type in pattern)if(tester[type].test(e))return type;return"invalid"}},{}],171:[function(require,module,exports){function compact(array){var index=-1,length=array?array.length:0,resIndex=-1,result=[];while(++index<length){var value=array[index];if(value){result[++resIndex]=value}}return result}module.exports=compact},{}],172:[function(require,module,exports){var baseFlatten=require("../internal/baseFlatten"),isIterateeCall=require("../internal/isIterateeCall");function flatten(array,isDeep,guard){var length=array?array.length:0;if(guard&&isIterateeCall(array,isDeep,guard)){isDeep=false}return length?baseFlatten(array,isDeep):[]}module.exports=flatten},{"../internal/baseFlatten":196,"../internal/isIterateeCall":232}],173:[function(require,module,exports){function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}module.exports=last},{}],174:[function(require,module,exports){var baseIndexOf=require("../internal/baseIndexOf");var arrayProto=Array.prototype;var splice=arrayProto.splice;function pull(){var array=arguments[0];if(!(array&&array.length)){return array}var index=0,indexOf=baseIndexOf,length=arguments.length;while(++index<length){var fromIndex=0,value=arguments[index];while((fromIndex=indexOf(array,value,fromIndex))>-1){splice.call(array,fromIndex,1)}}return array}module.exports=pull},{"../internal/baseIndexOf":200}],175:[function(require,module,exports){var baseCallback=require("../internal/baseCallback"),baseUniq=require("../internal/baseUniq"),isIterateeCall=require("../internal/isIterateeCall"),sortedUniq=require("../internal/sortedUniq");function uniq(array,isSorted,iteratee,thisArg){var length=array?array.length:0;if(!length){return[]}if(typeof isSorted!="boolean"&&isSorted!=null){thisArg=iteratee;iteratee=isIterateeCall(array,isSorted,thisArg)?null:isSorted;isSorted=false}iteratee=iteratee==null?iteratee:baseCallback(iteratee,thisArg,3);return isSorted?sortedUniq(array,iteratee):baseUniq(array,iteratee)}module.exports=uniq},{"../internal/baseCallback":191,"../internal/baseUniq":213,"../internal/isIterateeCall":232,"../internal/sortedUniq":239}],176:[function(require,module,exports){module.exports=require("./includes")},{"./includes":180}],177:[function(require,module,exports){module.exports=require("./forEach")},{"./forEach":178}],178:[function(require,module,exports){var arrayEach=require("../internal/arrayEach"),baseEach=require("../internal/baseEach"),bindCallback=require("../internal/bindCallback"),isArray=require("../lang/isArray");function forEach(collection,iteratee,thisArg){return typeof iteratee=="function"&&typeof thisArg=="undefined"&&isArray(collection)?arrayEach(collection,iteratee):baseEach(collection,bindCallback(iteratee,thisArg,3))}module.exports=forEach},{"../internal/arrayEach":186,"../internal/baseEach":195,"../internal/bindCallback":215,"../lang/isArray":244}],179:[function(require,module,exports){var createAggregator=require("../internal/createAggregator");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value)}else{result[key]=[value]}});module.exports=groupBy},{"../internal/createAggregator":220}],180:[function(require,module,exports){var baseIndexOf=require("../internal/baseIndexOf"),isArray=require("../lang/isArray"),isLength=require("../internal/isLength"),isString=require("../lang/isString"),values=require("../object/values");var nativeMax=Math.max;function includes(collection,target,fromIndex){var length=collection?collection.length:0;if(!isLength(length)){collection=values(collection);length=collection.length}if(!length){return false}if(typeof fromIndex=="number"){fromIndex=fromIndex<0?nativeMax(length+fromIndex,0):fromIndex||0}else{fromIndex=0}return typeof collection=="string"||!isArray(collection)&&isString(collection)?fromIndex<length&&collection.indexOf(target,fromIndex)>-1:baseIndexOf(collection,target,fromIndex)>-1}module.exports=includes},{"../internal/baseIndexOf":200,"../internal/isLength":233,"../lang/isArray":244,"../lang/isString":253,"../object/values":263}],181:[function(require,module,exports){var arrayMap=require("../internal/arrayMap"),baseCallback=require("../internal/baseCallback"),baseMap=require("../internal/baseMap"),isArray=require("../lang/isArray");function map(collection,iteratee,thisArg){var func=isArray(collection)?arrayMap:baseMap;iteratee=baseCallback(iteratee,thisArg,3);return func(collection,iteratee)}module.exports=map},{"../internal/arrayMap":187,"../internal/baseCallback":191,"../internal/baseMap":204,"../lang/isArray":244}],182:[function(require,module,exports){var arraySome=require("../internal/arraySome"),baseCallback=require("../internal/baseCallback"),baseSome=require("../internal/baseSome"),isArray=require("../lang/isArray");function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;if(typeof predicate!="function"||typeof thisArg!="undefined"){predicate=baseCallback(predicate,thisArg,3)}return func(collection,predicate)}module.exports=some},{"../internal/arraySome":188,"../internal/baseCallback":191,"../internal/baseSome":210,"../lang/isArray":244}],183:[function(require,module,exports){var baseCallback=require("../internal/baseCallback"),baseEach=require("../internal/baseEach"),baseSortBy=require("../internal/baseSortBy"),compareAscending=require("../internal/compareAscending"),isIterateeCall=require("../internal/isIterateeCall"),isLength=require("../internal/isLength");function sortBy(collection,iteratee,thisArg){var index=-1,length=collection?collection.length:0,result=isLength(length)?Array(length):[];if(thisArg&&isIterateeCall(collection,iteratee,thisArg)){iteratee=null}iteratee=baseCallback(iteratee,thisArg,3);baseEach(collection,function(value,key,collection){result[++index]={criteria:iteratee(value,key,collection),index:index,value:value}});return baseSortBy(result,compareAscending)}module.exports=sortBy},{"../internal/baseCallback":191,"../internal/baseEach":195,"../internal/baseSortBy":211,"../internal/compareAscending":219,"../internal/isIterateeCall":232,"../internal/isLength":233}],184:[function(require,module,exports){(function(global){var cachePush=require("./cachePush"),isNative=require("../lang/isNative");var Set=isNative(Set=global.Set)&&Set;var nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate;function SetCache(values){var length=values?values.length:0;this.data={hash:nativeCreate(null),set:new Set};while(length--){this.push(values[length])}}SetCache.prototype.push=cachePush;module.exports=SetCache}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../lang/isNative":248,"./cachePush":218}],185:[function(require,module,exports){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},{}],186:[function(require,module,exports){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},{}],187:[function(require,module,exports){function arrayMap(array,iteratee){var index=-1,length=array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array)}return result}module.exports=arrayMap},{}],188:[function(require,module,exports){function arraySome(array,predicate){var index=-1,length=array.length;while(++index<length){if(predicate(array[index],index,array)){return true}}return false}module.exports=arraySome},{}],189:[function(require,module,exports){function assignDefaults(objectValue,sourceValue){return typeof objectValue=="undefined"?sourceValue:objectValue}module.exports=assignDefaults},{}],190:[function(require,module,exports){var baseCopy=require("./baseCopy"),keys=require("../object/keys");function baseAssign(object,source,customizer){var props=keys(source);if(!customizer){return baseCopy(source,object,props)}var index=-1,length=props.length;while(++index<length){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);if((result===result?result!==value:value===value)||typeof value=="undefined"&&!(key in object)){object[key]=result}}return object}module.exports=baseAssign},{"../object/keys":260,"./baseCopy":194}],191:[function(require,module,exports){var baseMatches=require("./baseMatches"),baseProperty=require("./baseProperty"),baseToString=require("./baseToString"),bindCallback=require("./bindCallback"),identity=require("../utility/identity"),isBindable=require("./isBindable");function baseCallback(func,thisArg,argCount){var type=typeof func;if(type=="function"){return typeof thisArg!="undefined"&&isBindable(func)?bindCallback(func,thisArg,argCount):func}if(func==null){return identity}return type=="object"?baseMatches(func,!argCount):baseProperty(argCount?baseToString(func):func)}module.exports=baseCallback},{"../utility/identity":267,"./baseMatches":205,"./baseProperty":208,"./baseToString":212,"./bindCallback":215,"./isBindable":230}],192:[function(require,module,exports){var arrayCopy=require("./arrayCopy"),arrayEach=require("./arrayEach"),baseCopy=require("./baseCopy"),baseForOwn=require("./baseForOwn"),initCloneArray=require("./initCloneArray"),initCloneByTag=require("./initCloneByTag"),initCloneObject=require("./initCloneObject"),isArray=require("../lang/isArray"),isObject=require("../lang/isObject"),keys=require("../object/keys");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]";var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=false;var objectProto=Object.prototype;var objToString=objectProto.toString;function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer){result=object?customizer(value,key,object):customizer(value)}if(typeof result!="undefined"){return result}if(!isObject(value)){return value}var isArr=isArray(value); if(isArr){result=initCloneArray(value);if(!isDeep){return arrayCopy(value,result)}}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag==objectTag||tag==argsTag||isFunc&&!object){result=initCloneObject(isFunc?{}:value);if(!isDeep){return baseCopy(value,result,keys(value))}}else{return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{}}}stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==value){return stackB[length]}}stackA.push(value);stackB.push(result);(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)});return result}module.exports=baseClone},{"../lang/isArray":244,"../lang/isObject":250,"../object/keys":260,"./arrayCopy":185,"./arrayEach":186,"./baseCopy":194,"./baseForOwn":199,"./initCloneArray":227,"./initCloneByTag":228,"./initCloneObject":229}],193:[function(require,module,exports){function baseCompareAscending(value,other){if(value!==other){var valIsReflexive=value===value,othIsReflexive=other===other;if(value>other||!valIsReflexive||typeof value=="undefined"&&othIsReflexive){return 1}if(value<other||!othIsReflexive||typeof other=="undefined"&&valIsReflexive){return-1}}return 0}module.exports=baseCompareAscending},{}],194:[function(require,module,exports){function baseCopy(source,object,props){if(!props){props=object;object={}}var index=-1,length=props.length;while(++index<length){var key=props[index];object[key]=source[key]}return object}module.exports=baseCopy},{}],195:[function(require,module,exports){var baseForOwn=require("./baseForOwn"),isLength=require("./isLength"),toObject=require("./toObject");function baseEach(collection,iteratee){var length=collection?collection.length:0;if(!isLength(length)){return baseForOwn(collection,iteratee)}var index=-1,iterable=toObject(collection);while(++index<length){if(iteratee(iterable[index],index,iterable)===false){break}}return collection}module.exports=baseEach},{"./baseForOwn":199,"./isLength":233,"./toObject":240}],196:[function(require,module,exports){var isArguments=require("../lang/isArguments"),isArray=require("../lang/isArray"),isLength=require("./isLength"),isObjectLike=require("./isObjectLike");function baseFlatten(array,isDeep,isStrict,fromIndex){var index=(fromIndex||0)-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index];if(isObjectLike(value)&&isLength(value.length)&&(isArray(value)||isArguments(value))){if(isDeep){value=baseFlatten(value,isDeep,isStrict)}var valIndex=-1,valLength=value.length;result.length+=valLength;while(++valIndex<valLength){result[++resIndex]=value[valIndex]}}else if(!isStrict){result[++resIndex]=value}}return result}module.exports=baseFlatten},{"../lang/isArguments":243,"../lang/isArray":244,"./isLength":233,"./isObjectLike":234}],197:[function(require,module,exports){var toObject=require("./toObject");function baseFor(object,iteratee,keysFunc){var index=-1,iterable=toObject(object),props=keysFunc(object),length=props.length;while(++index<length){var key=props[index];if(iteratee(iterable[key],key,iterable)===false){break}}return object}module.exports=baseFor},{"./toObject":240}],198:[function(require,module,exports){var baseFor=require("./baseFor"),keysIn=require("../object/keysIn");function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}module.exports=baseForIn},{"../object/keysIn":261,"./baseFor":197}],199:[function(require,module,exports){var baseFor=require("./baseFor"),keys=require("../object/keys");function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}module.exports=baseForOwn},{"../object/keys":260,"./baseFor":197}],200:[function(require,module,exports){var indexOfNaN=require("./indexOfNaN");function baseIndexOf(array,value,fromIndex){if(value!==value){return indexOfNaN(array,fromIndex)}var index=(fromIndex||0)-1,length=array.length;while(++index<length){if(array[index]===value){return index}}return-1}module.exports=baseIndexOf},{"./indexOfNaN":226}],201:[function(require,module,exports){var baseIsEqualDeep=require("./baseIsEqualDeep");function baseIsEqual(value,other,customizer,isWhere,stackA,stackB){if(value===other){return value!==0||1/value==1/other}var valType=typeof value,othType=typeof other;if(valType!="function"&&valType!="object"&&othType!="function"&&othType!="object"||value==null||other==null){return value!==value&&other!==other}return baseIsEqualDeep(value,other,baseIsEqual,customizer,isWhere,stackA,stackB)}module.exports=baseIsEqual},{"./baseIsEqualDeep":202}],202:[function(require,module,exports){var equalArrays=require("./equalArrays"),equalByTag=require("./equalByTag"),equalObjects=require("./equalObjects"),isArray=require("../lang/isArray"),isTypedArray=require("../lang/isTypedArray");var argsTag="[object Arguments]",arrayTag="[object Array]",objectTag="[object Object]";var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var objToString=objectProto.toString;function baseIsEqualDeep(object,other,equalFunc,customizer,isWhere,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;if(!objIsArr){objTag=objToString.call(object);if(objTag==argsTag){objTag=objectTag}else if(objTag!=objectTag){objIsArr=isTypedArray(object)}}if(!othIsArr){othTag=objToString.call(other);if(othTag==argsTag){othTag=objectTag}else if(othTag!=objectTag){othIsArr=isTypedArray(other)}}var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!(objIsArr||objIsObj)){return equalByTag(object,other,objTag)}var valWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(valWrapped||othWrapped){return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isWhere,stackA,stackB)}if(!isSameTag){return false}stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==object){return stackB[length]==other}}stackA.push(object);stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isWhere,stackA,stackB);stackA.pop();stackB.pop();return result}module.exports=baseIsEqualDeep},{"../lang/isArray":244,"../lang/isTypedArray":254,"./equalArrays":223,"./equalByTag":224,"./equalObjects":225}],203:[function(require,module,exports){var baseIsEqual=require("./baseIsEqual");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function baseIsMatch(object,props,values,strictCompareFlags,customizer){var length=props.length;if(object==null){return!length}var index=-1,noCustomizer=!customizer;while(++index<length){if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!hasOwnProperty.call(object,props[index])){return false}}index=-1;while(++index<length){var key=props[index];if(noCustomizer&&strictCompareFlags[index]){var result=hasOwnProperty.call(object,key)}else{var objValue=object[key],srcValue=values[index];result=customizer?customizer(objValue,srcValue,key):undefined;if(typeof result=="undefined"){result=baseIsEqual(srcValue,objValue,customizer,true)}}if(!result){return false}}return true}module.exports=baseIsMatch},{"./baseIsEqual":201}],204:[function(require,module,exports){var baseEach=require("./baseEach");function baseMap(collection,iteratee){var result=[];baseEach(collection,function(value,key,collection){result.push(iteratee(value,key,collection))});return result}module.exports=baseMap},{"./baseEach":195}],205:[function(require,module,exports){var baseClone=require("./baseClone"),baseIsMatch=require("./baseIsMatch"),isStrictComparable=require("./isStrictComparable"),keys=require("../object/keys");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function baseMatches(source,isCloned){var props=keys(source),length=props.length;if(length==1){var key=props[0],value=source[key];if(isStrictComparable(value)){return function(object){return object!=null&&value===object[key]&&hasOwnProperty.call(object,key)}}}if(isCloned){source=baseClone(source,true)}var values=Array(length),strictCompareFlags=Array(length);while(length--){value=source[props[length]];values[length]=value;strictCompareFlags[length]=isStrictComparable(value)}return function(object){return baseIsMatch(object,props,values,strictCompareFlags)}}module.exports=baseMatches},{"../object/keys":260,"./baseClone":192,"./baseIsMatch":203,"./isStrictComparable":235}],206:[function(require,module,exports){var arrayEach=require("./arrayEach"),baseForOwn=require("./baseForOwn"),baseMergeDeep=require("./baseMergeDeep"),isArray=require("../lang/isArray"),isLength=require("./isLength"),isObjectLike=require("./isObjectLike"),isTypedArray=require("../lang/isTypedArray");function baseMerge(object,source,customizer,stackA,stackB){var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));(isSrcArr?arrayEach:baseForOwn)(source,function(srcValue,key,source){if(isObjectLike(srcValue)){stackA||(stackA=[]);stackB||(stackB=[]);return baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB)}var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=typeof result=="undefined";if(isCommon){result=srcValue}if((isSrcArr||typeof result!="undefined")&&(isCommon||(result===result?result!==value:value===value))){object[key]=result}});return object}module.exports=baseMerge},{"../lang/isArray":244,"../lang/isTypedArray":254,"./arrayEach":186,"./baseForOwn":199,"./baseMergeDeep":207,"./isLength":233,"./isObjectLike":234}],207:[function(require,module,exports){var arrayCopy=require("./arrayCopy"),isArguments=require("../lang/isArguments"),isArray=require("../lang/isArray"),isLength=require("./isLength"),isPlainObject=require("../lang/isPlainObject"),isTypedArray=require("../lang/isTypedArray"),toPlainObject=require("../lang/toPlainObject");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=typeof result=="undefined";if(isCommon){result=srcValue;if(isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))){result=isArray(value)?value:value?arrayCopy(value):[]}else if(isPlainObject(srcValue)||isArguments(srcValue)){result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}}}stackA.push(srcValue);stackB.push(result);if(isCommon){object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB)}else if(result===result?result!==value:value===value){object[key]=result}}module.exports=baseMergeDeep},{"../lang/isArguments":243,"../lang/isArray":244,"../lang/isPlainObject":251,"../lang/isTypedArray":254,"../lang/toPlainObject":255,"./arrayCopy":185,"./isLength":233}],208:[function(require,module,exports){function baseProperty(key){return function(object){return object==null?undefined:object[key]}}module.exports=baseProperty},{}],209:[function(require,module,exports){var identity=require("../utility/identity"),metaMap=require("./metaMap");var baseSetData=!metaMap?identity:function(func,data){metaMap.set(func,data);return func};module.exports=baseSetData},{"../utility/identity":267,"./metaMap":236}],210:[function(require,module,exports){var baseEach=require("./baseEach");function baseSome(collection,predicate){var result;baseEach(collection,function(value,index,collection){result=predicate(value,index,collection);return!result});return!!result}module.exports=baseSome},{"./baseEach":195}],211:[function(require,module,exports){function baseSortBy(array,comparer){var length=array.length;array.sort(comparer);while(length--){array[length]=array[length].value}return array}module.exports=baseSortBy},{}],212:[function(require,module,exports){function baseToString(value){if(typeof value=="string"){return value}return value==null?"":value+""}module.exports=baseToString},{}],213:[function(require,module,exports){var baseIndexOf=require("./baseIndexOf"),cacheIndexOf=require("./cacheIndexOf"),createCache=require("./createCache");function baseUniq(array,iteratee){var index=-1,indexOf=baseIndexOf,length=array.length,isCommon=true,isLarge=isCommon&&length>=200,seen=isLarge&&createCache(),result=[];if(seen){indexOf=cacheIndexOf;isCommon=false}else{isLarge=false;seen=iteratee?[]:result}outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value,index,array):value;if(isCommon&&value===value){var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===computed){continue outer}}if(iteratee){seen.push(computed)}result.push(value)}else if(indexOf(seen,computed)<0){if(iteratee||isLarge){seen.push(computed)}result.push(value)}}return result}module.exports=baseUniq},{"./baseIndexOf":200,"./cacheIndexOf":217,"./createCache":222}],214:[function(require,module,exports){function baseValues(object,props){var index=-1,length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}module.exports=baseValues},{}],215:[function(require,module,exports){var identity=require("../utility/identity");function bindCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(typeof 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":267}],216:[function(require,module,exports){(function(global){var constant=require("../utility/constant"),isNative=require("../lang/isNative");var ArrayBuffer=isNative(ArrayBuffer=global.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,Uint8Array=isNative(Uint8Array=global.Uint8Array)&&Uint8Array;var Float64Array=function(){try{var func=isNative(func=global.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}();var FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0;function bufferClone(buffer){return bufferSlice.call(buffer,0)}if(!bufferSlice){bufferClone=!(ArrayBuffer&&Uint8Array)?constant(null):function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}if(byteLength!=offset){view=new Uint8Array(result,offset);view.set(new Uint8Array(buffer,offset))}return result}}module.exports=bufferClone}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../lang/isNative":248,"../utility/constant":266}],217:[function(require,module,exports){var isObject=require("../lang/isObject");function cacheIndexOf(cache,value){var data=cache.data,result=typeof value=="string"||isObject(value)?data.set.has(value):data.hash[value];return result?0:-1}module.exports=cacheIndexOf},{"../lang/isObject":250}],218:[function(require,module,exports){var isObject=require("../lang/isObject");function cachePush(value){var data=this.data;if(typeof value=="string"||isObject(value)){data.set.add(value)}else{data.hash[value]=true}}module.exports=cachePush},{"../lang/isObject":250}],219:[function(require,module,exports){var baseCompareAscending=require("./baseCompareAscending");function compareAscending(object,other){return baseCompareAscending(object.criteria,other.criteria)||object.index-other.index}module.exports=compareAscending},{"./baseCompareAscending":193}],220:[function(require,module,exports){var baseCallback=require("./baseCallback"),baseEach=require("./baseEach"),isArray=require("../lang/isArray");function createAggregator(setter,initializer){return function(collection,iteratee,thisArg){var result=initializer?initializer():{};iteratee=baseCallback(iteratee,thisArg,3);if(isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];setter(result,value,iteratee(value,index,collection),collection)}}else{baseEach(collection,function(value,key,collection){setter(result,value,iteratee(value,key,collection),collection)})}return result}}module.exports=createAggregator},{"../lang/isArray":244,"./baseCallback":191,"./baseEach":195}],221:[function(require,module,exports){var bindCallback=require("./bindCallback"),isIterateeCall=require("./isIterateeCall");function createAssigner(assigner){return function(){var length=arguments.length,object=arguments[0];if(length<2||object==null){return object}if(length>3&&isIterateeCall(arguments[1],arguments[2],arguments[3])){length=2}if(length>3&&typeof arguments[length-2]=="function"){var customizer=bindCallback(arguments[--length-1],arguments[length--],5)}else if(length>2&&typeof arguments[length-1]=="function"){customizer=arguments[--length]}var index=0;while(++index<length){var source=arguments[index];if(source){assigner(object,source,customizer)}}return object}}module.exports=createAssigner},{"./bindCallback":215,"./isIterateeCall":232}],222:[function(require,module,exports){(function(global){var SetCache=require("./SetCache"),constant=require("../utility/constant"),isNative=require("../lang/isNative");var Set=isNative(Set=global.Set)&&Set;var nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate;var createCache=!(nativeCreate&&Set)?constant(null):function(values){return new SetCache(values)};module.exports=createCache}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../lang/isNative":248,"../utility/constant":266,"./SetCache":184}],223:[function(require,module,exports){function equalArrays(array,other,equalFunc,customizer,isWhere,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=true;if(arrLength!=othLength&&!(isWhere&&othLength>arrLength)){return false}while(result&&++index<arrLength){var arrValue=array[index],othValue=other[index];result=undefined;if(customizer){result=isWhere?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)}if(typeof result=="undefined"){if(isWhere){var othIndex=othLength;while(othIndex--){othValue=other[othIndex];result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isWhere,stackA,stackB);if(result){break}}}else{result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isWhere,stackA,stackB)}}}return!!result}module.exports=equalArrays},{}],224:[function(require,module,exports){var baseToString=require("./baseToString");var boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",numberTag="[object Number]",regexpTag="[object RegExp]",stringTag="[object String]";function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:object==0?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==baseToString(other)}return false}module.exports=equalByTag},{"./baseToString":212}],225:[function(require,module,exports){var keys=require("../object/keys");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function equalObjects(object,other,equalFunc,customizer,isWhere,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isWhere){return false}var hasCtor,index=-1;while(++index<objLength){var key=objProps[index],result=hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined;if(customizer){result=isWhere?customizer(othValue,objValue,key):customizer(objValue,othValue,key)}if(typeof result=="undefined"){result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isWhere,stackA,stackB)}}if(!result){return false}hasCtor||(hasCtor=key=="constructor")}if(!hasCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&("constructor"in object&&"constructor"in other)&&!(typeof objCtor=="function"&&objCtor instanceof objCtor&&typeof othCtor=="function"&&othCtor instanceof othCtor)){return false}}return true}module.exports=equalObjects},{"../object/keys":260}],226:[function(require,module,exports){function indexOfNaN(array,fromIndex,fromRight){var length=array.length,index=fromRight?fromIndex||length:(fromIndex||0)-1;while(fromRight?index--:++index<length){var other=array[index];if(other!==other){return index}}return-1}module.exports=indexOfNaN},{}],227:[function(require,module,exports){var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function initCloneArray(array){var length=array.length,result=new array.constructor(length);if(length&&typeof array[0]=="string"&&hasOwnProperty.call(array,"index")){result.index=array.index;result.input=array.input}return result}module.exports=initCloneArray},{}],228:[function(require,module,exports){var bufferClone=require("./bufferClone");var boolTag="[object Boolean]",dateTag="[object Date]",numberTag="[object Number]",regexpTag="[object RegExp]",stringTag="[object String]";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]";var reFlags=/\w*$/;function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}module.exports=initCloneByTag},{"./bufferClone":216}],229:[function(require,module,exports){function initCloneObject(object){var Ctor=object.constructor;if(!(typeof Ctor=="function"&&Ctor instanceof Ctor)){Ctor=Object}return new Ctor}module.exports=initCloneObject},{}],230:[function(require,module,exports){var baseSetData=require("./baseSetData"),isNative=require("../lang/isNative"),support=require("../support");var reFuncName=/^\s*function[ \n\r\t]+\w/;var reThis=/\bthis\b/;var fnToString=Function.prototype.toString;function isBindable(func){var result=!(support.funcNames?func.name:support.funcDecomp);if(!result){var source=fnToString.call(func);if(!support.funcNames){result=!reFuncName.test(source)}if(!result){result=reThis.test(source)||isNative(func);baseSetData(func,result)}}return result}module.exports=isBindable},{"../lang/isNative":248,"../support":265,"./baseSetData":209}],231:[function(require,module,exports){var MAX_SAFE_INTEGER=Math.pow(2,53)-1;function isIndex(value,length){value=+value;length=length==null?MAX_SAFE_INTEGER:length;return value>-1&&value%1==0&&value<length}module.exports=isIndex},{}],232:[function(require,module,exports){var isIndex=require("./isIndex"),isLength=require("./isLength"),isObject=require("../lang/isObject");function isIterateeCall(value,index,object){if(!isObject(object)){return false}var type=typeof index;if(type=="number"){var length=object.length,prereq=isLength(length)&&isIndex(index,length)}else{prereq=type=="string"&&index in value}return prereq&&object[index]===value}module.exports=isIterateeCall},{"../lang/isObject":250,"./isIndex":231,"./isLength":233}],233:[function(require,module,exports){var MAX_SAFE_INTEGER=Math.pow(2,53)-1;function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}module.exports=isLength},{}],234:[function(require,module,exports){function isObjectLike(value){return value&&typeof value=="object"||false}module.exports=isObjectLike},{}],235:[function(require,module,exports){var isObject=require("../lang/isObject");function isStrictComparable(value){return value===value&&(value===0?1/value>0:!isObject(value))}module.exports=isStrictComparable},{"../lang/isObject":250}],236:[function(require,module,exports){(function(global){var isNative=require("../lang/isNative");var WeakMap=isNative(WeakMap=global.WeakMap)&&WeakMap;var metaMap=WeakMap&&new WeakMap;module.exports=metaMap}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../lang/isNative":248}],237:[function(require,module,exports){var baseForIn=require("./baseForIn"),isObjectLike=require("./isObjectLike");var objectTag="[object Object]";var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var objToString=objectProto.toString;function shimIsPlainObject(value){var Ctor;if(!(isObjectLike(value)&&objToString.call(value)==objectTag)||!hasOwnProperty.call(value,"constructor")&&(Ctor=value.constructor,typeof Ctor=="function"&&!(Ctor instanceof Ctor))){return false}var result;baseForIn(value,function(subValue,key){result=key});return typeof result=="undefined"||hasOwnProperty.call(value,result)}module.exports=shimIsPlainObject},{"./baseForIn":198,"./isObjectLike":234}],238:[function(require,module,exports){var isArguments=require("../lang/isArguments"),isArray=require("../lang/isArray"),isIndex=require("./isIndex"),isLength=require("./isLength"),keysIn=require("../object/keysIn"),support=require("../support");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function shimKeys(object){var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length;var allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(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":243,"../lang/isArray":244,"../object/keysIn":261,"../support":265,"./isIndex":231,"./isLength":233}],239:[function(require,module,exports){function sortedUniq(array,iteratee){var seen,index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index],computed=iteratee?iteratee(value,index,array):value;if(!index||seen!==computed){seen=computed;result[++resIndex]=value}}return result}module.exports=sortedUniq},{}],240:[function(require,module,exports){var isObject=require("../lang/isObject");function toObject(value){return isObject(value)?value:Object(value)}module.exports=toObject},{"../lang/isObject":250}],241:[function(require,module,exports){var baseClone=require("../internal/baseClone"),bindCallback=require("../internal/bindCallback"),isIterateeCall=require("../internal/isIterateeCall");function clone(value,isDeep,customizer,thisArg){if(typeof isDeep!="boolean"&&isDeep!=null){thisArg=customizer;customizer=isIterateeCall(value,isDeep,thisArg)?null:isDeep;isDeep=false}customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,1);return baseClone(value,isDeep,customizer)}module.exports=clone},{"../internal/baseClone":192,"../internal/bindCallback":215,"../internal/isIterateeCall":232}],242:[function(require,module,exports){var baseClone=require("../internal/baseClone"),bindCallback=require("../internal/bindCallback");function cloneDeep(value,customizer,thisArg){customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,1);return baseClone(value,true,customizer)}module.exports=cloneDeep},{"../internal/baseClone":192,"../internal/bindCallback":215}],243:[function(require,module,exports){var isLength=require("../internal/isLength"),isObjectLike=require("../internal/isObjectLike");var argsTag="[object Arguments]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag||false}module.exports=isArguments},{"../internal/isLength":233,"../internal/isObjectLike":234}],244:[function(require,module,exports){var isLength=require("../internal/isLength"),isNative=require("./isNative"),isObjectLike=require("../internal/isObjectLike");var arrayTag="[object Array]";var objectProto=Object.prototype;var objToString=objectProto.toString;var nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray;var isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag||false};module.exports=isArray},{"../internal/isLength":233,"../internal/isObjectLike":234,"./isNative":248}],245:[function(require,module,exports){var isObjectLike=require("../internal/isObjectLike");var boolTag="[object Boolean]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isBoolean(value){return value===true||value===false||isObjectLike(value)&&objToString.call(value)==boolTag||false}module.exports=isBoolean},{"../internal/isObjectLike":234}],246:[function(require,module,exports){var isArguments=require("./isArguments"),isArray=require("./isArray"),isFunction=require("./isFunction"),isLength=require("../internal/isLength"),isObjectLike=require("../internal/isObjectLike"),isString=require("./isString"),keys=require("../object/keys");function isEmpty(value){if(value==null){return true}var length=value.length;if(isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))){return!length}return!keys(value).length}module.exports=isEmpty},{"../internal/isLength":233,"../internal/isObjectLike":234,"../object/keys":260,"./isArguments":243,"./isArray":244,"./isFunction":247,"./isString":253}],247:[function(require,module,exports){(function(global){var isNative=require("./isNative");var funcTag="[object Function]";var objectProto=Object.prototype;var objToString=objectProto.toString;var Uint8Array=isNative(Uint8Array=global.Uint8Array)&&Uint8Array;function isFunction(value){return typeof value=="function"||false}if(isFunction(/x/)||Uint8Array&&!isFunction(Uint8Array)){isFunction=function(value){return objToString.call(value)==funcTag}}module.exports=isFunction}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./isNative":248}],248:[function(require,module,exports){var escapeRegExp=require("../string/escapeRegExp"),isObjectLike=require("../internal/isObjectLike");var funcTag="[object Function]";var reHostCtor=/^\[object .+?Constructor\]$/;var objectProto=Object.prototype;var fnToString=Function.prototype.toString;var objToString=objectProto.toString;var reNative=RegExp("^"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function isNative(value){if(value==null){return false}if(objToString.call(value)==funcTag){return reNative.test(fnToString.call(value))}return isObjectLike(value)&&reHostCtor.test(value)||false}module.exports=isNative},{"../internal/isObjectLike":234,"../string/escapeRegExp":264}],249:[function(require,module,exports){var isObjectLike=require("../internal/isObjectLike"); var numberTag="[object Number]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isNumber(value){return typeof value=="number"||isObjectLike(value)&&objToString.call(value)==numberTag||false}module.exports=isNumber},{"../internal/isObjectLike":234}],250:[function(require,module,exports){function isObject(value){var type=typeof value;return type=="function"||value&&type=="object"||false}module.exports=isObject},{}],251:[function(require,module,exports){var isNative=require("./isNative"),shimIsPlainObject=require("../internal/shimIsPlainObject");var objectTag="[object Object]";var objectProto=Object.prototype;var objToString=objectProto.toString;var getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf;var isPlainObject=!getPrototypeOf?shimIsPlainObject:function(value){if(!(value&&objToString.call(value)==objectTag)){return false}var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)};module.exports=isPlainObject},{"../internal/shimIsPlainObject":237,"./isNative":248}],252:[function(require,module,exports){var isObjectLike=require("../internal/isObjectLike");var regexpTag="[object RegExp]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isRegExp(value){return isObjectLike(value)&&objToString.call(value)==regexpTag||false}module.exports=isRegExp},{"../internal/isObjectLike":234}],253:[function(require,module,exports){var isObjectLike=require("../internal/isObjectLike");var stringTag="[object String]";var objectProto=Object.prototype;var objToString=objectProto.toString;function isString(value){return typeof value=="string"||isObjectLike(value)&&objToString.call(value)==stringTag||false}module.exports=isString},{"../internal/isObjectLike":234}],254:[function(require,module,exports){var isLength=require("../internal/isLength"),isObjectLike=require("../internal/isObjectLike");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]";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;var objectProto=Object.prototype;var objToString=objectProto.toString;function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&typedArrayTags[objToString.call(value)]||false}module.exports=isTypedArray},{"../internal/isLength":233,"../internal/isObjectLike":234}],255:[function(require,module,exports){var baseCopy=require("../internal/baseCopy"),keysIn=require("../object/keysIn");function toPlainObject(value){return baseCopy(value,keysIn(value))}module.exports=toPlainObject},{"../internal/baseCopy":194,"../object/keysIn":261}],256:[function(require,module,exports){var baseAssign=require("../internal/baseAssign"),createAssigner=require("../internal/createAssigner");var assign=createAssigner(baseAssign);module.exports=assign},{"../internal/baseAssign":190,"../internal/createAssigner":221}],257:[function(require,module,exports){var arrayCopy=require("../internal/arrayCopy"),assign=require("./assign"),assignDefaults=require("../internal/assignDefaults");function defaults(object){if(object==null){return object}var args=arrayCopy(arguments);args.push(assignDefaults);return assign.apply(undefined,args)}module.exports=defaults},{"../internal/arrayCopy":185,"../internal/assignDefaults":189,"./assign":256}],258:[function(require,module,exports){module.exports=require("./assign")},{"./assign":256}],259:[function(require,module,exports){var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function has(object,key){return object?hasOwnProperty.call(object,key):false}module.exports=has},{}],260:[function(require,module,exports){var isLength=require("../internal/isLength"),isNative=require("../lang/isNative"),isObject=require("../lang/isObject"),shimKeys=require("../internal/shimKeys");var nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys;var keys=!nativeKeys?shimKeys:function(object){if(object){var Ctor=object.constructor,length=object.length}if(typeof Ctor=="function"&&Ctor.prototype===object||typeof object!="function"&&(length&&isLength(length))){return shimKeys(object)}return isObject(object)?nativeKeys(object):[]};module.exports=keys},{"../internal/isLength":233,"../internal/shimKeys":238,"../lang/isNative":248,"../lang/isObject":250}],261:[function(require,module,exports){var isArguments=require("../lang/isArguments"),isArray=require("../lang/isArray"),isIndex=require("../internal/isIndex"),isLength=require("../internal/isLength"),isObject=require("../lang/isObject"),support=require("../support");var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;function keysIn(object){if(object==null){return[]}if(!isObject(object)){object=Object(object)}var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;var Ctor=object.constructor,index=-1,isProto=typeof Ctor=="function"&&Ctor.prototype==object,result=Array(length),skipIndexes=length>0;while(++index<length){result[index]=index+""}for(var key in object){if(!(skipIndexes&&isIndex(key,length))&&!(key=="constructor"&&(isProto||!hasOwnProperty.call(object,key)))){result.push(key)}}return result}module.exports=keysIn},{"../internal/isIndex":231,"../internal/isLength":233,"../lang/isArguments":243,"../lang/isArray":244,"../lang/isObject":250,"../support":265}],262:[function(require,module,exports){var baseMerge=require("../internal/baseMerge"),createAssigner=require("../internal/createAssigner");var merge=createAssigner(baseMerge);module.exports=merge},{"../internal/baseMerge":206,"../internal/createAssigner":221}],263:[function(require,module,exports){var baseValues=require("../internal/baseValues"),keys=require("./keys");function values(object){return baseValues(object,keys(object))}module.exports=values},{"../internal/baseValues":214,"./keys":260}],264:[function(require,module,exports){var baseToString=require("../internal/baseToString");var reRegExpChars=/[.*+?^${}()|[\]\/\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source);function escapeRegExp(string){string=baseToString(string);return string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,"\\$&"):string}module.exports=escapeRegExp},{"../internal/baseToString":212}],265:[function(require,module,exports){(function(global){var isNative=require("./lang/isNative");var reThis=/\bthis\b/;var objectProto=Object.prototype;var document=(document=global.window)&&document.document;var propertyIsEnumerable=objectProto.propertyIsEnumerable;var support={};(function(x){support.funcDecomp=!isNative(global.WinRTError)&&reThis.test(function(){return this});support.funcNames=typeof Function.name=="string";try{support.dom=document.createDocumentFragment().nodeType===11}catch(e){support.dom=false}try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=true}})(0,0);module.exports=support}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./lang/isNative":248}],266:[function(require,module,exports){function constant(value){return function(){return value}}module.exports=constant},{}],267:[function(require,module,exports){function identity(value){return value}module.exports=identity},{}],268:[function(require,module,exports){"use strict";var originalObject=Object;var originalDefProp=Object.defineProperty;var originalCreate=Object.create;function defProp(obj,name,value){if(originalDefProp)try{originalDefProp.call(originalObject,obj,name,{value:value})}catch(definePropertyIsBrokenInIE8){obj[name]=value}else{obj[name]=value}}function makeSafeToCall(fun){if(fun){defProp(fun,"call",fun.call);defProp(fun,"apply",fun.apply)}return fun}makeSafeToCall(originalDefProp);makeSafeToCall(originalCreate);var hasOwn=makeSafeToCall(Object.prototype.hasOwnProperty);var numToStr=makeSafeToCall(Number.prototype.toString);var strSlice=makeSafeToCall(String.prototype.slice);var cloner=function(){};function create(prototype){if(originalCreate){return originalCreate.call(originalObject,prototype)}cloner.prototype=prototype||null;return new cloner}var rand=Math.random;var uniqueKeys=create(null);function makeUniqueKey(){do var uniqueKey=internString(strSlice.call(numToStr.call(rand(),36),2));while(hasOwn.call(uniqueKeys,uniqueKey));return uniqueKeys[uniqueKey]=uniqueKey}function internString(str){var obj={};obj[str]=true;return Object.keys(obj)[0]}defProp(exports,"makeUniqueKey",makeUniqueKey);var originalGetOPNs=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function getOwnPropertyNames(object){for(var names=originalGetOPNs(object),src=0,dst=0,len=names.length;src<len;++src){if(!hasOwn.call(uniqueKeys,names[src])){if(src>dst){names[dst]=names[src]}++dst}}names.length=dst;return names};function defaultCreatorFn(object){return create(null)}function makeAccessor(secretCreatorFn){var brand=makeUniqueKey();var passkey=create(null);secretCreatorFn=secretCreatorFn||defaultCreatorFn;function register(object){var secret;function vault(key,forget){if(key===passkey){return forget?secret=null:secret||(secret=secretCreatorFn(object))}}defProp(object,brand,vault)}function accessor(object){if(!hasOwn.call(object,brand))register(object);return object[brand](passkey)}accessor.forget=function(object){if(hasOwn.call(object,brand))object[brand](passkey,true)};return accessor}defProp(exports,"makeAccessor",makeAccessor)},{}],269:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var isArray=types.builtInTypes.array;var b=types.builders;var n=types.namedTypes;var leap=require("./leap");var meta=require("./meta");var util=require("./util");var hasOwn=Object.prototype.hasOwnProperty;function Emitter(contextId){assert.ok(this instanceof Emitter);n.Identifier.assert(contextId);Object.defineProperties(this,{contextId:{value:contextId},listing:{value:[]},marked:{value:[true]},finalLoc:{value:loc()},tryEntries:{value:[]}});Object.defineProperties(this,{leapManager:{value:new leap.LeapManager(this)}})}var Ep=Emitter.prototype;exports.Emitter=Emitter;function loc(){return b.literal(-1)}Ep.mark=function(loc){n.Literal.assert(loc);var index=this.listing.length;if(loc.value===-1){loc.value=index}else{assert.strictEqual(loc.value,index)}this.marked[index]=true;return loc};Ep.emit=function(node){if(n.Expression.check(node))node=b.expressionStatement(node);n.Statement.assert(node);this.listing.push(node)};Ep.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Ep.assign=function(lhs,rhs){return b.expressionStatement(b.assignmentExpression("=",lhs,rhs))};Ep.contextProperty=function(name,computed){return b.memberExpression(this.contextId,computed?b.literal(name):b.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Ep.isVolatileContextProperty=function(expr){if(n.MemberExpression.check(expr)){if(expr.computed){return true}if(n.Identifier.check(expr.object)&&n.Identifier.check(expr.property)&&expr.object.name===this.contextId.name&&hasOwn.call(volatileContextPropertyNames,expr.property.name)){return true}}return false};Ep.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Ep.setReturnValue=function(valuePath){n.Expression.assert(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Ep.clearPendingException=function(tryLoc,assignee){n.Literal.assert(tryLoc);var catchCall=b.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Ep.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(b.breakStatement())};Ep.jumpIf=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);this.emit(b.ifStatement(test,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};Ep.jumpIfNot=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);var negatedTest;if(n.UnaryExpression.check(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=b.unaryExpression("!",test)}this.emit(b.ifStatement(negatedTest,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};var nextTempId=0;Ep.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Ep.getContextFunction=function(id){var func=b.functionExpression(id||null,[this.contextId],b.blockStatement([this.getDispatchLoop()]),false,false);func._aliasFunction=true;return func};Ep.getDispatchLoop=function(){var self=this;var cases=[];var current;var alreadyEnded=false;self.listing.forEach(function(stmt,i){if(self.marked.hasOwnProperty(i)){cases.push(b.switchCase(b.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(b.switchCase(this.finalLoc,[]),b.switchCase(b.literal("end"),[b.returnStatement(b.callExpression(this.contextProperty("stop"),[]))]));return b.whileStatement(b.literal(1),b.switchStatement(b.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return n.BreakStatement.check(stmt)||n.ContinueStatement.check(stmt)||n.ReturnStatement.check(stmt)||n.ThrowStatement.check(stmt)}Ep.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return b.arrayExpression(this.tryEntries.map(function(tryEntry){var thisLocValue=tryEntry.firstLoc.value;assert.ok(thisLocValue>=lastLocValue,"try entries out of order");lastLocValue=thisLocValue;var ce=tryEntry.catchEntry;var fe=tryEntry.finallyEntry;var triple=[tryEntry.firstLoc,ce?ce.firstLoc:null];if(fe){triple[2]=fe.firstLoc}return b.arrayExpression(triple)}))};Ep.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.assert(node);if(n.Statement.check(node))return self.explodeStatement(path);if(n.Expression.check(node))return self.explodeExpression(path,ignoreResult);if(n.Declaration.check(node))throw getDeclError(node);switch(node.type){case"Program":return path.get("body").map(self.explodeStatement,self);case"VariableDeclarator":throw getDeclError(node);case"Property":case"SwitchCase":case"CatchClause":throw new Error(node.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(node.type))}};function getDeclError(node){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(node))}Ep.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;n.Statement.assert(stmt);if(labelId){n.Identifier.assert(labelId)}else{labelId=null}if(n.BlockStatement.check(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}switch(stmt.type){case"ExpressionStatement":self.explodeExpression(path.get("expression"),true);break;case"LabeledStatement":var after=loc();self.leapManager.withEntry(new leap.LabeledEntry(after,stmt.label),function(){self.explodeStatement(path.get("body"),stmt.label)});self.mark(after);break;case"WhileStatement":var before=loc();var after=loc();self.mark(before);self.jumpIfNot(self.explodeExpression(path.get("test")),after);self.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(before);self.mark(after);break;case"DoWhileStatement":var first=loc();var test=loc();var after=loc();self.mark(first);self.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){self.explode(path.get("body"))});self.mark(test);self.jumpIf(self.explodeExpression(path.get("test")),first);self.mark(after);break;case"ForStatement":var head=loc();var update=loc();var after=loc();if(stmt.init){self.explode(path.get("init"),true)}self.mark(head);if(stmt.test){self.jumpIfNot(self.explodeExpression(path.get("test")),after)}else{}self.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){self.explodeStatement(path.get("body"))});self.mark(update);if(stmt.update){self.explode(path.get("update"),true)}self.jump(head);self.mark(after);break;case"ForInStatement":n.Identifier.assert(stmt.left);var head=loc();var after=loc();var keyIterNextFn=self.makeTempVar();self.emitAssign(keyIterNextFn,b.callExpression(util.runtimeProperty("keys"),[self.explodeExpression(path.get("right"))]));self.mark(head);var keyInfoTmpVar=self.makeTempVar();self.jumpIf(b.memberExpression(b.assignmentExpression("=",keyInfoTmpVar,b.callExpression(keyIterNextFn,[])),b.identifier("done"),false),after);self.emitAssign(stmt.left,b.memberExpression(keyInfoTmpVar,b.identifier("value"),false));self.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(head);self.mark(after);break;case"BreakStatement":self.emitAbruptCompletion({type:"break",target:self.leapManager.getBreakLoc(stmt.label)});break;case"ContinueStatement":self.emitAbruptCompletion({type:"continue",target:self.leapManager.getContinueLoc(stmt.label)});break;case"SwitchStatement":var disc=self.emitAssign(self.makeTempVar(),self.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];n.SwitchCase.assert(c);if(c.test){condition=b.conditionalExpression(b.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}self.jump(self.explodeExpression(new types.NodePath(condition,path,"discriminant")));self.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var c=casePath.value;var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});self.mark(after);if(defaultLoc.value===-1){self.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}break;case"IfStatement":var elseLoc=stmt.alternate&&loc();var after=loc();self.jumpIfNot(self.explodeExpression(path.get("test")),elseLoc||after);self.explodeStatement(path.get("consequent"));if(elseLoc){self.jump(after);self.mark(elseLoc);self.explodeStatement(path.get("alternate"))}self.mark(after);break;case"ReturnStatement":self.emitAbruptCompletion({type:"return",value:self.explodeExpression(path.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var after=loc();var handler=stmt.handler;if(!handler&&stmt.handlers){handler=stmt.handlers[0]||null}var catchLoc=handler&&loc();var catchEntry=catchLoc&&new leap.CatchEntry(catchLoc,handler.param);var finallyLoc=stmt.finalizer&&loc();var finallyEntry=finallyLoc&&new leap.FinallyEntry(finallyLoc);var tryEntry=new leap.TryEntry(self.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);self.tryEntries.push(tryEntry);self.updateContextPrevLoc(tryEntry.firstLoc);self.leapManager.withEntry(tryEntry,function(){self.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){self.jump(finallyLoc)}else{self.jump(after)}self.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=self.makeTempVar();self.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;n.CatchClause.assert(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(util.isReference(path,catchParamName)&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)},visitFunction:function(path){if(path.scope.declares(catchParamName)){return false}this.traverse(path)}});self.leapManager.withEntry(catchEntry,function(){self.explodeStatement(bodyPath)})}if(finallyLoc){self.updateContextPrevLoc(self.mark(finallyLoc));self.leapManager.withEntry(finallyEntry,function(){self.explodeStatement(path.get("finalizer"))});self.emit(b.callExpression(self.contextProperty("finish"),[finallyEntry.firstLoc]))}});self.mark(after);break;case"ThrowStatement":self.emit(b.throwStatement(self.explodeExpression(path.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Ep.emitAbruptCompletion=function(record){if(!isValidCompletion(record)){assert.ok(false,"invalid completion record: "+JSON.stringify(record))}assert.notStrictEqual(record.type,"normal","normal completions are not abrupt");var abruptArgs=[b.literal(record.type)];if(record.type==="break"||record.type==="continue"){n.Literal.assert(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){n.Expression.assert(record.value);abruptArgs[1]=record.value}}this.emit(b.returnStatement(b.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!hasOwn.call(record,"target")}if(type==="break"||type==="continue"){return!hasOwn.call(record,"value")&&n.Literal.check(record.target)}if(type==="return"||type==="throw"){return hasOwn.call(record,"value")&&!hasOwn.call(record,"target")}return false}Ep.getUnmarkedCurrentLoc=function(){return b.literal(this.listing.length)};Ep.updateContextPrevLoc=function(loc){if(loc){n.Literal.assert(loc);if(loc.value===-1){loc.value=this.listing.length}else{assert.strictEqual(loc.value,this.listing.length)}}else{loc=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),loc)};Ep.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){n.Expression.assert(expr)}else{return expr}var self=this;var result;function finish(expr){n.Expression.assert(expr);if(ignoreResult){self.emit(expr)}else{return expr}}if(!meta.containsLeap(expr)){return finish(expr)}var hasLeapingChildren=meta.containsLeap.onlyChildren(expr);function explodeViaTempVar(tempVar,childPath,ignoreChildResult){assert.ok(childPath instanceof types.NodePath);assert.ok(!ignoreChildResult||!tempVar,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var result=self.explodeExpression(childPath,ignoreChildResult);if(ignoreChildResult){}else if(tempVar||hasLeapingChildren&&(self.isVolatileContextProperty(result)||meta.hasSideEffects(result))){result=self.emitAssign(tempVar||self.makeTempVar(),result)}return result}switch(expr.type){case"MemberExpression":return finish(b.memberExpression(self.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed));case"CallExpression":var oldCalleePath=path.get("callee");var newCallee=self.explodeExpression(oldCalleePath);if(!n.MemberExpression.check(oldCalleePath.node)&&n.MemberExpression.check(newCallee)){newCallee=b.sequenceExpression([b.literal(0),newCallee])}return finish(b.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"NewExpression":return finish(b.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"ObjectExpression":return finish(b.objectExpression(path.get("properties").map(function(propPath){return b.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})));case"ArrayExpression":return finish(b.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})));case"SequenceExpression":var lastIndex=expr.expressions.length-1;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result;case"LogicalExpression":var after=loc();if(!ignoreResult){result=self.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){self.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");self.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);self.mark(after);return result;case"ConditionalExpression":var elseLoc=loc();var after=loc();var test=self.explodeExpression(path.get("test"));self.jumpIfNot(test,elseLoc);if(!ignoreResult){result=self.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);self.jump(after);self.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);self.mark(after);return result;case"UnaryExpression":return finish(b.unaryExpression(expr.operator,self.explodeExpression(path.get("argument")),!!expr.prefix));case"BinaryExpression":return finish(b.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))));case"AssignmentExpression":return finish(b.assignmentExpression(expr.operator,self.explodeExpression(path.get("left")),self.explodeExpression(path.get("right"))));case"UpdateExpression":return finish(b.updateExpression(expr.operator,self.explodeExpression(path.get("argument")),expr.prefix));case"YieldExpression":var after=loc();var arg=expr.argument&&self.explodeExpression(path.get("argument"));if(arg&&expr.delegate){var result=self.makeTempVar();self.emit(b.returnStatement(b.callExpression(self.contextProperty("delegateYield"),[arg,b.literal(result.property.name),after])));self.mark(after);return result}self.emitAssign(self.contextProperty("next"),after);self.emit(b.returnStatement(arg||null));self.mark(after);return self.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"./leap":271,"./meta":272,"./util":273,assert:122,"ast-types":120}],270:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);n.Function.assert(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){n.VariableDeclaration.assert(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(b.assignmentExpression("=",dec.id,dec.init))}else if(includeIdentifiers){exprs.push(dec.id)}});if(exprs.length===0)return null;if(exprs.length===1)return exprs[0];return b.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return b.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(n.VariableDeclaration.check(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(n.VariableDeclaration.check(left)){path.get("left").replace(varDeclToExpr(left,true))}this.traverse(path)},visitFunctionDeclaration:function(path){var node=path.value;vars[node.id.name]=node.id;var parentNode=path.parent.node;var assignment=b.expressionStatement(b.assignmentExpression("=",node.id,b.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(n.BlockStatement.check(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(path){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(n.Identifier.check(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!hasOwn.call(paramNames,name)){declarations.push(b.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return b.variableDeclaration("var",declarations)}},{assert:122,"ast-types":120}],271:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var inherits=require("util").inherits;var hasOwn=Object.prototype.hasOwnProperty;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);n.Literal.assert(returnLoc);this.returnLoc=returnLoc}inherits(FunctionEntry,Entry);exports.FunctionEntry=FunctionEntry;function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Literal.assert(continueLoc);if(label){n.Identifier.assert(label)}else{label=null}this.breakLoc=breakLoc;this.continueLoc=continueLoc;this.label=label}inherits(LoopEntry,Entry);exports.LoopEntry=LoopEntry;function SwitchEntry(breakLoc){Entry.call(this);n.Literal.assert(breakLoc);this.breakLoc=breakLoc}inherits(SwitchEntry,Entry);exports.SwitchEntry=SwitchEntry;function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);n.Literal.assert(firstLoc);if(catchEntry){assert.ok(catchEntry instanceof CatchEntry)}else{catchEntry=null}if(finallyEntry){assert.ok(finallyEntry instanceof FinallyEntry)}else{finallyEntry=null}assert.ok(catchEntry||finallyEntry);this.firstLoc=firstLoc;this.catchEntry=catchEntry;this.finallyEntry=finallyEntry}inherits(TryEntry,Entry);exports.TryEntry=TryEntry;function CatchEntry(firstLoc,paramId){Entry.call(this);n.Literal.assert(firstLoc);n.Identifier.assert(paramId);this.firstLoc=firstLoc;this.paramId=paramId}inherits(CatchEntry,Entry);exports.CatchEntry=CatchEntry;function FinallyEntry(firstLoc){Entry.call(this);n.Literal.assert(firstLoc);this.firstLoc=firstLoc}inherits(FinallyEntry,Entry);exports.FinallyEntry=FinallyEntry;function LabeledEntry(breakLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Identifier.assert(label);this.breakLoc=breakLoc;this.label=label}inherits(LabeledEntry,Entry);exports.LabeledEntry=LabeledEntry;function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);this.emitter=emitter;this.entryStack=[new FunctionEntry(emitter.finalLoc)]}var LMp=LeapManager.prototype;exports.LeapManager=LeapManager;LMp.withEntry=function(entry,callback){assert.ok(entry instanceof Entry);this.entryStack.push(entry);try{callback.call(this.emitter)}finally{var popped=this.entryStack.pop();assert.strictEqual(popped,entry)}};LMp._findLeapLocation=function(property,label){for(var i=this.entryStack.length-1;i>=0;--i){var entry=this.entryStack[i];var loc=entry[property];if(loc){if(label){if(entry.label&&entry.label.name===label.name){return loc}}else if(entry instanceof LabeledEntry){}else{return loc }}}return null};LMp.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LMp.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"./emit":269,assert:122,"ast-types":120,util:147}],272:[function(require,module,exports){var assert=require("assert");var m=require("private").makeAccessor();var types=require("ast-types");var isArray=types.builtInTypes.array;var n=types.namedTypes;var hasOwn=Object.prototype.hasOwnProperty;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.assert(node);var result=false;function check(child){if(result){}else if(isArray.check(child)){child.some(check)}else if(n.Node.check(child)){assert.strictEqual(result,false);result=predicate(child)}return result}types.eachField(node,function(name,child){check(child)});return result}function predicate(node){n.Node.assert(node);var meta=m(node);if(hasOwn.call(meta,propertyName))return meta[propertyName];if(hasOwn.call(opaqueTypes,node.type))return meta[propertyName]=false;if(hasOwn.call(knownTypes,node.type))return meta[propertyName]=true;return meta[propertyName]=onlyChildren(node)}predicate.onlyChildren=onlyChildren;return predicate}var opaqueTypes={FunctionExpression:true};var sideEffectTypes={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var leapTypes={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var type in leapTypes){if(hasOwn.call(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:122,"ast-types":120,"private":268}],273:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.defaults=function(obj){var len=arguments.length;var extension;for(var i=1;i<len;++i){if(extension=arguments[i]){for(var key in extension){if(hasOwn.call(extension,key)&&!hasOwn.call(obj,key)){obj[key]=extension[key]}}}}return obj};exports.runtimeProperty=function(name){return b.memberExpression(b.identifier("regeneratorRuntime"),b.identifier(name),false)};exports.isReference=function(path,name){var node=path.value;if(!n.Identifier.check(node)){return false}if(name&&node.name!==name){return false}var parent=path.parent.value;switch(parent.type){case"VariableDeclarator":return path.name==="init";case"MemberExpression":return path.name==="object"||parent.computed&&path.name==="property";case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":if(path.name==="id"){return false}if(parent.params===path.parentPath&&parent.params[path.name]===node){return false}return true;case"ClassDeclaration":case"ClassExpression":return path.name!=="id";case"CatchClause":return path.name!=="param";case"Property":case"MethodDefinition":return path.name!=="key";case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"LabeledStatement":return false;default:return true}}},{assert:122,"ast-types":120}],274:[function(require,module,exports){var assert=require("assert");var fs=require("fs");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var NodePath=types.NodePath;var hoist=require("./hoist").hoist;var Emitter=require("./emit").Emitter;var runtimeProperty=require("./util").runtimeProperty;exports.transform=function transform(node,options){options=options||{};var path=node instanceof NodePath?node:new NodePath(node);visitor.visit(path,options);node=path.value;options.madeChanges=visitor.wasChangeReported();return node};var visitor=types.PathVisitor.fromMethodsObject({reset:function(node,options){this.options=options},visitFunction:function(path){this.traverse(path);var node=path.value;var shouldTransformAsync=node.async&&!this.options.disableAsync;if(!node.generator&&!shouldTransformAsync){return}this.reportChanged();node.generator=false;if(node.expression){node.expression=false;node.body=b.blockStatement([b.returnStatement(node.body)])}if(shouldTransformAsync){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=path.scope.parent.declareTemporary("callee$"));var outerBody=[];var bodyBlock=path.value.body;bodyBlock.body=bodyBlock.body.filter(function(node){if(node&&node._blockHoist!=null){outerBody.push(node);return false}else{return true}});var innerFnId=b.identifier(node.id.name+"$");var contextId=path.scope.declareTemporary("context$");var vars=hoist(path);var emitter=new Emitter(contextId);emitter.explode(path.get("body"));if(vars&&vars.declarations.length>0){outerBody.push(vars)}var wrapArgs=[emitter.getContextFunction(innerFnId),shouldTransformAsync?b.literal(null):outerFnId,b.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=b.callExpression(shouldTransformAsync?runtimeProperty("async"):runtimeProperty("wrap"),wrapArgs);outerBody.push(b.returnStatement(wrapCall));node.body=b.blockStatement(outerBody);if(shouldTransformAsync){node.async=false;return}if(n.FunctionDeclaration.check(node)){var pp=path.parent;while(pp&&!(n.BlockStatement.check(pp.value)||n.Program.check(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=b.variableDeclaration("var",[b.variableDeclarator(node.id,b.callExpression(runtimeProperty("mark"),[node]))]);if(node.comments){varDecl.leadingComments=node.leadingComments;varDecl.trailingComments=node.trailingComments;node.leadingComments=null;node.trailingComments=null}varDecl._blockHoist=3;var bodyPath=pp.get("body");var bodyLen=bodyPath.value.length;bodyPath.push(varDecl)}else{n.FunctionExpression.assert(node);return b.callExpression(runtimeProperty("mark"),[node])}}});function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;n.Statement.assert(value);if(n.ExpressionStatement.check(value)&&n.Literal.check(value.expression)&&value.expression.value==="use strict"){return true}if(n.VariableDeclaration.check(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(n.CallExpression.check(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeProperty("mark"))){return true}}}return false}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(path){return false},visitAwaitExpression:function(path){return b.yieldExpression(path.value.argument,false)}})},{"./emit":269,"./hoist":270,"./util":273,assert:122,"ast-types":120,fs:121}],275:[function(require,module,exports){(function(__dirname){var assert=require("assert");var path=require("path");var fs=require("fs");var through=require("through");var transform=require("./lib/visit").transform;var utils=require("./lib/util");var types=require("ast-types");var genOrAsyncFunExp=/\bfunction\s*\*|\basync\b/;var blockBindingExp=/\b(let|const)\s+/;function exports(file,options){var data=[];return through(write,end);function write(buf){data.push(buf)}function end(){this.queue(compile(data.join(""),options).code);this.queue(null)}}module.exports=exports;function runtime(){require("./runtime")}exports.runtime=runtime;runtime.path=path.join(__dirname,"runtime.js");exports.transform=transform}).call(this,"/node_modules/regenerator-6to5")},{"./lib/util":273,"./lib/visit":274,"./runtime":277,assert:122,"ast-types":120,fs:121,path:130,through:276}],276:[function(require,module,exports){(function(process){var Stream=require("stream");exports=module.exports=through;through.through=through;function through(write,end,opts){write=write||function(data){this.queue(data)};end=end||function(){this.queue(null)};var ended=false,destroyed=false,buffer=[],_ended=false;var stream=new Stream;stream.readable=stream.writable=true;stream.paused=false;stream.autoDestroy=!(opts&&opts.autoDestroy===false);stream.write=function(data){write.call(this,data);return!stream.paused};function drain(){while(buffer.length&&!stream.paused){var data=buffer.shift();if(null===data)return stream.emit("end");else stream.emit("data",data)}}stream.queue=stream.push=function(data){if(_ended)return stream;if(data==null)_ended=true;buffer.push(data);drain();return stream};stream.on("end",function(){stream.readable=false;if(!stream.writable&&stream.autoDestroy)process.nextTick(function(){stream.destroy()})});function _end(){stream.writable=false;end.call(stream);if(!stream.readable&&stream.autoDestroy)stream.destroy()}stream.end=function(data){if(ended)return;ended=true;if(arguments.length)stream.write(data);_end();return stream};stream.destroy=function(){if(destroyed)return;destroyed=true;ended=true;buffer.length=0;stream.writable=stream.readable=false;stream.emit("close");return stream};stream.pause=function(){if(stream.paused)return;stream.paused=true;return stream};stream.resume=function(){if(stream.paused){stream.paused=false;stream.emit("resume")}drain();if(!stream.paused)stream.emit("drain");return stream};return stream}}).call(this,require("_process"))},{_process:131,stream:143}],277:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],278:[function(require,module,exports){var regenerate=require("regenerate");exports.REGULAR={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,65535),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};exports.UNICODE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};exports.UNICODE_IGNORE_CASE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:280}],279:[function(require,module,exports){module.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871}},{}],280:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var ERRORS={rangeOrder:"A range’s `stop` value must be greater than or equal "+"to the `start` value.",codePointRange:"Invalid code point value. Code points range from "+"U+000000 to U+10FFFF."};var HIGH_SURROGATE_MIN=55296;var HIGH_SURROGATE_MAX=56319;var LOW_SURROGATE_MIN=56320;var LOW_SURROGATE_MAX=57343;var regexNull=/\\x00([^0123456789]|$)/g;var object={};var hasOwnProperty=object.hasOwnProperty;var extend=function(destination,source){var key;for(key in source){if(hasOwnProperty.call(source,key)){destination[key]=source[key]}}return destination};var forEach=function(array,callback){var index=-1;var length=array.length;while(++index<length){callback(array[index],index)}};var toString=object.toString;var isArray=function(value){return toString.call(value)=="[object Array]"};var isNumber=function(value){return typeof value=="number"||toString.call(value)=="[object Number]"};var zeroes="0000";var pad=function(number,totalCharacters){var string=String(number);return string.length<totalCharacters?(zeroes+string).slice(-totalCharacters):string};var hex=function(number){return Number(number).toString(16).toUpperCase()};var slice=[].slice;var dataFromCodePoints=function(codePoints){var index=-1;var length=codePoints.length;var max=length-1;var result=[];var isStart=true;var tmp;var previous=0;while(++index<length){tmp=codePoints[index];if(isStart){result.push(tmp);previous=tmp;isStart=false}else{if(tmp==previous+1){if(index!=max){previous=tmp;continue}else{isStart=true;result.push(tmp+1)}}else{result.push(previous+1,tmp);previous=tmp}}}if(!isStart){result.push(tmp+1)}return result};var dataRemove=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){if(codePoint==start){if(end==start+1){data.splice(index,2);return data}else{data[index]=codePoint+1;return data}}else if(codePoint==end-1){data[index+1]=codePoint;return data}else{data.splice(index,2,start,codePoint,codePoint+1,end);return data}}index+=2}return data};var dataRemoveRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}var index=0;var start;var end;while(index<data.length){start=data[index];end=data[index+1]-1;if(start>rangeEnd){return data}if(rangeStart<=start&&rangeEnd>=end){data.splice(index,2);continue}if(rangeStart>=start&&rangeEnd<end){if(rangeStart==start){data[index]=rangeEnd+1;data[index+1]=end+1;return data}data.splice(index,2,start,rangeStart,rangeEnd+1,end+1);return data}if(rangeStart>=start&&rangeStart<=end){data[index+1]=rangeStart}else if(rangeEnd>=start&&rangeEnd<=end){data[index]=rangeEnd+1;return data}index+=2}return data};var dataAdd=function(data,codePoint){var index=0;var start;var end;var lastIndex=null;var length=data.length;if(codePoint<0||codePoint>1114111){throw RangeError(ERRORS.codePointRange)}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return data}if(codePoint==start-1){data[index]=codePoint;return data}if(start>codePoint){data.splice(lastIndex!=null?lastIndex+2:0,0,codePoint,codePoint+1);return data}if(codePoint==end){if(codePoint+1==data[index+2]){data.splice(index,4,start,data[index+3]);return data}data[index+1]=codePoint+1;return data}lastIndex=index;index+=2}data.push(codePoint,codePoint+1);return data};var dataAddData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataAdd(data,start)}else{data=dataAddRange(data,start,end)}index+=2}return data};var dataRemoveData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataRemove(data,start)}else{data=dataRemoveRange(data,start,end)}index+=2}return data};var dataAddRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}if(rangeStart<0||rangeStart>1114111||rangeEnd<0||rangeEnd>1114111){throw RangeError(ERRORS.codePointRange)}var index=0;var start;var end;var added=false;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(added){if(start==rangeEnd+1){data.splice(index-1,2);return data}if(start>rangeEnd){return data}if(start>=rangeStart&&start<=rangeEnd){if(end>rangeStart&&end-1<=rangeEnd){data.splice(index,2);index-=2}else{data.splice(index-1,2);index-=2}}}else if(start==rangeEnd+1){data[index]=rangeStart;return data}else if(start>rangeEnd){data.splice(index,0,rangeStart,rangeEnd+1);return data}else if(rangeStart>=start&&rangeStart<end&&rangeEnd+1<=end){return data}else if(rangeStart>=start&&rangeStart<end||end==rangeStart){data[index+1]=rangeEnd+1;added=true}else if(rangeStart<=start&&rangeEnd+1>=end){data[index]=rangeStart;data[index+1]=rangeEnd+1;added=true}index+=2}if(!added){data.push(rangeStart,rangeEnd+1)}return data};var dataContains=function(data,codePoint){var index=0;var length=data.length;var start=data[index];var end=data[length-1];if(length>=2){if(codePoint<start||codePoint>end){return false}}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return true}index+=2}return false};var dataIntersection=function(data,codePoints){var index=0;var length=codePoints.length;var codePoint;var result=[];while(index<length){codePoint=codePoints[index];if(dataContains(data,codePoint)){result.push(codePoint)}++index}return dataFromCodePoints(result)};var dataIsEmpty=function(data){return!data.length};var dataIsSingleton=function(data){return data.length==2&&data[0]+1==data[1]};var dataToArray=function(data){var index=0;var start;var end;var result=[];var length=data.length;while(index<length){start=data[index];end=data[index+1];while(start<end){result.push(start);++start}index+=2}return result};var floor=Math.floor;var highSurrogate=function(codePoint){return parseInt(floor((codePoint-65536)/1024)+HIGH_SURROGATE_MIN,10)};var lowSurrogate=function(codePoint){return parseInt((codePoint-65536)%1024+LOW_SURROGATE_MIN,10)};var stringFromCharCode=String.fromCharCode;var codePointToString=function(codePoint){var string;if(codePoint==9){string="\\t"}else if(codePoint==10){string="\\n"}else if(codePoint==12){string="\\f"}else if(codePoint==13){string="\\r"}else if(codePoint==92){string="\\\\"}else if(codePoint==36||codePoint>=40&&codePoint<=43||codePoint==45||codePoint==46||codePoint==63||codePoint>=91&&codePoint<=94||codePoint>=123&&codePoint<=125){string="\\"+stringFromCharCode(codePoint)}else if(codePoint>=32&&codePoint<=126){string=stringFromCharCode(codePoint)}else if(codePoint<=255){string="\\x"+pad(hex(codePoint),2)}else{string="\\u"+pad(hex(codePoint),4)}return string};var symbolToCodePoint=function(symbol){var length=symbol.length;var first=symbol.charCodeAt(0);var second;if(first>=HIGH_SURROGATE_MIN&&first<=HIGH_SURROGATE_MAX&&length>1){second=symbol.charCodeAt(1);return(first-HIGH_SURROGATE_MIN)*1024+second-LOW_SURROGATE_MIN+65536}return first};var createBMPCharacterClasses=function(data){var result="";var index=0;var start;var end;var length=data.length;if(dataIsSingleton(data)){return codePointToString(data[0])}while(index<length){start=data[index];end=data[index+1]-1;if(start==end){result+=codePointToString(start)}else if(start+1==end){result+=codePointToString(start)+codePointToString(end)}else{result+=codePointToString(start)+"-"+codePointToString(end)}index+=2}return"["+result+"]"};var splitAtBMP=function(data){var loneHighSurrogates=[];var loneLowSurrogates=[];var bmp=[];var astral=[];var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1]-1;if(start<HIGH_SURROGATE_MIN){if(end<HIGH_SURROGATE_MIN){bmp.push(start,end+1)}if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,end+1)}if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,end+1)}if(end>LOW_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,end+1)}if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,end+1)}if(end>LOW_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>=LOW_SURROGATE_MIN&&start<=LOW_SURROGATE_MAX){if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){loneLowSurrogates.push(start,end+1)}if(end>LOW_SURROGATE_MAX){loneLowSurrogates.push(start,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>LOW_SURROGATE_MAX&&start<=65535){if(end<=65535){bmp.push(start,end+1)}else{bmp.push(start,65535+1);astral.push(65535+1,end+1)}}else{astral.push(start,end+1)}index+=2}return{loneHighSurrogates:loneHighSurrogates,loneLowSurrogates:loneLowSurrogates,bmp:bmp,astral:astral}};var optimizeSurrogateMappings=function(surrogateMappings){var result=[];var tmpLow=[];var addLow=false;var mapping;var nextMapping;var highSurrogates;var lowSurrogates;var nextHighSurrogates;var nextLowSurrogates;var index=-1;var length=surrogateMappings.length;while(++index<length){mapping=surrogateMappings[index];nextMapping=surrogateMappings[index+1];if(!nextMapping){result.push(mapping);continue}highSurrogates=mapping[0];lowSurrogates=mapping[1];nextHighSurrogates=nextMapping[0];nextLowSurrogates=nextMapping[1];tmpLow=lowSurrogates;while(nextHighSurrogates&&highSurrogates[0]==nextHighSurrogates[0]&&highSurrogates[1]==nextHighSurrogates[1]){if(dataIsSingleton(nextLowSurrogates)){tmpLow=dataAdd(tmpLow,nextLowSurrogates[0])}else{tmpLow=dataAddRange(tmpLow,nextLowSurrogates[0],nextLowSurrogates[1]-1)}++index;mapping=surrogateMappings[index];highSurrogates=mapping[0]; lowSurrogates=mapping[1];nextMapping=surrogateMappings[index+1];nextHighSurrogates=nextMapping&&nextMapping[0];nextLowSurrogates=nextMapping&&nextMapping[1];addLow=true}result.push([highSurrogates,addLow?tmpLow:lowSurrogates]);addLow=false}return optimizeByLowSurrogates(result)};var optimizeByLowSurrogates=function(surrogateMappings){if(surrogateMappings.length==1){return surrogateMappings}var index=-1;var innerIndex=-1;while(++index<surrogateMappings.length){var mapping=surrogateMappings[index];var lowSurrogates=mapping[1];var lowSurrogateStart=lowSurrogates[0];var lowSurrogateEnd=lowSurrogates[1];innerIndex=index;while(++innerIndex<surrogateMappings.length){var otherMapping=surrogateMappings[innerIndex];var otherLowSurrogates=otherMapping[1];var otherLowSurrogateStart=otherLowSurrogates[0];var otherLowSurrogateEnd=otherLowSurrogates[1];if(lowSurrogateStart==otherLowSurrogateStart&&lowSurrogateEnd==otherLowSurrogateEnd){if(dataIsSingleton(otherMapping[0])){mapping[0]=dataAdd(mapping[0],otherMapping[0][0])}else{mapping[0]=dataAddRange(mapping[0],otherMapping[0][0],otherMapping[0][1]-1)}surrogateMappings.splice(innerIndex,1);--innerIndex}}}return surrogateMappings};var surrogateSet=function(data){if(!data.length){return[]}var index=0;var start;var end;var startHigh;var startLow;var prevStartHigh=0;var prevEndHigh=0;var tmpLow=[];var endHigh;var endLow;var surrogateMappings=[];var length=data.length;var dataHigh=[];while(index<length){start=data[index];end=data[index+1]-1;startHigh=highSurrogate(start);startLow=lowSurrogate(start);endHigh=highSurrogate(end);endLow=lowSurrogate(end);var startsWithLowestLowSurrogate=startLow==LOW_SURROGATE_MIN;var endsWithHighestLowSurrogate=endLow==LOW_SURROGATE_MAX;var complete=false;if(startHigh==endHigh||startsWithLowestLowSurrogate&&endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh,endHigh+1],[startLow,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh,startHigh+1],[startLow,LOW_SURROGATE_MAX+1]])}if(!complete&&startHigh+1<endHigh){if(endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh+1,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh+1,endHigh],[LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1]])}}if(!complete){surrogateMappings.push([[endHigh,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]])}prevStartHigh=startHigh;prevEndHigh=endHigh;index+=2}return optimizeSurrogateMappings(surrogateMappings)};var createSurrogateCharacterClasses=function(surrogateMappings){var result=[];forEach(surrogateMappings,function(surrogateMapping){var highSurrogates=surrogateMapping[0];var lowSurrogates=surrogateMapping[1];result.push(createBMPCharacterClasses(highSurrogates)+createBMPCharacterClasses(lowSurrogates))});return result.join("|")};var createCharacterClassesFromData=function(data,bmpOnly){var result=[];var parts=splitAtBMP(data);var loneHighSurrogates=parts.loneHighSurrogates;var loneLowSurrogates=parts.loneLowSurrogates;var bmp=parts.bmp;var astral=parts.astral;var hasAstral=!dataIsEmpty(parts.astral);var hasLoneHighSurrogates=!dataIsEmpty(loneHighSurrogates);var hasLoneLowSurrogates=!dataIsEmpty(loneLowSurrogates);var surrogateMappings=surrogateSet(astral);if(bmpOnly){bmp=dataAddData(bmp,loneHighSurrogates);hasLoneHighSurrogates=false;bmp=dataAddData(bmp,loneLowSurrogates);hasLoneLowSurrogates=false}if(!dataIsEmpty(bmp)){result.push(createBMPCharacterClasses(bmp))}if(surrogateMappings.length){result.push(createSurrogateCharacterClasses(surrogateMappings))}if(hasLoneHighSurrogates){result.push(createBMPCharacterClasses(loneHighSurrogates)+"(?![\\uDC00-\\uDFFF])")}if(hasLoneLowSurrogates){result.push("(?:[^\\uD800-\\uDBFF]|^)"+createBMPCharacterClasses(loneLowSurrogates))}return result.join("|")};var regenerate=function(value){if(arguments.length>1){value=slice.call(arguments)}if(this instanceof regenerate){this.data=[];return value?this.add(value):this}return(new regenerate).add(value)};regenerate.version="1.2.0";var proto=regenerate.prototype;extend(proto,{add:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataAddData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.add(item)});return $this}$this.data=dataAdd($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},remove:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataRemoveData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.remove(item)});return $this}$this.data=dataRemove($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},addRange:function(start,end){var $this=this;$this.data=dataAddRange($this.data,isNumber(start)?start:symbolToCodePoint(start),isNumber(end)?end:symbolToCodePoint(end));return $this},removeRange:function(start,end){var $this=this;var startCodePoint=isNumber(start)?start:symbolToCodePoint(start);var endCodePoint=isNumber(end)?end:symbolToCodePoint(end);$this.data=dataRemoveRange($this.data,startCodePoint,endCodePoint);return $this},intersection:function(argument){var $this=this;var array=argument instanceof regenerate?dataToArray(argument.data):argument;$this.data=dataIntersection($this.data,array);return $this},contains:function(codePoint){return dataContains(this.data,isNumber(codePoint)?codePoint:symbolToCodePoint(codePoint))},clone:function(){var set=new regenerate;set.data=this.data.slice(0);return set},toString:function(options){var result=createCharacterClassesFromData(this.data,options?options.bmpOnly:false);return result.replace(regexNull,"\\0$1")},toRegExp:function(flags){return RegExp(this.toString(),flags||"")},valueOf:function(){return dataToArray(this.data)}});proto.toArray=proto.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return regenerate})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=regenerate}else{freeExports.regenerate=regenerate}}else{root.regenerate=regenerate}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],281:[function(require,module,exports){(function(global){(function(){"use strict";var objectTypes={"function":true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var stringFromCharCode=String.fromCharCode;var floor=Math.floor;function fromCodePoint(){var MAX_SIZE=16384;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return""}var result="";while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>1114111||floor(codePoint)!=codePoint){throw RangeError("Invalid code point: "+codePoint)}if(codePoint<=65535){codeUnits.push(codePoint)}else{codePoint-=65536;highSurrogate=(codePoint>>10)+55296;lowSurrogate=codePoint%1024+56320;codeUnits.push(highSurrogate,lowSurrogate)}if(index+1==length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0}}return result}function assertType(type,expected){if(expected.indexOf("|")==-1){if(type==expected){return}throw Error("Invalid node type: "+type)}expected=assertType.hasOwnProperty(expected)?assertType[expected]:assertType[expected]=RegExp("^(?:"+expected+")$");if(expected.test(type)){return}throw Error("Invalid node type: "+type)}function generate(node){var type=node.type;if(generate.hasOwnProperty(type)&&typeof generate[type]=="function"){return generate[type](node)}throw Error("Invalid node type: "+type)}function generateAlternative(node){assertType(node.type,"alternative");var terms=node.body,length=terms?terms.length:0;if(length==1){return generateTerm(terms[0])}else{var i=-1,result="";while(++i<length){result+=generateTerm(terms[i])}return result}}function generateAnchor(node){assertType(node.type,"anchor");switch(node.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function generateAtom(node){assertType(node.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return generate(node)}function generateCharacterClass(node){assertType(node.type,"characterClass");var classRanges=node.body,length=classRanges?classRanges.length:0;var i=-1,result="[";if(node.negative){result+="^"}while(++i<length){result+=generateClassAtom(classRanges[i])}result+="]";return result}function generateCharacterClassEscape(node){assertType(node.type,"characterClassEscape");return"\\"+node.value}function generateCharacterClassRange(node){assertType(node.type,"characterClassRange");var min=node.min,max=node.max;if(min.type=="characterClassRange"||max.type=="characterClassRange"){throw Error("Invalid character class range")}return generateClassAtom(min)+"-"+generateClassAtom(max)}function generateClassAtom(node){assertType(node.type,"anchor|characterClassEscape|characterClassRange|dot|value");return generate(node)}function generateDisjunction(node){assertType(node.type,"disjunction");var body=node.body,length=body?body.length:0;if(length==0){throw Error("No body")}else if(length==1){return generate(body[0])}else{var i=-1,result="";while(++i<length){if(i!=0){result+="|"}result+=generate(body[i])}return result}}function generateDot(node){assertType(node.type,"dot");return"."}function generateGroup(node){assertType(node.type,"group");var result="(";switch(node.behavior){case"normal":break;case"ignore":result+="?:";break;case"lookahead":result+="?=";break;case"negativeLookahead":result+="?!";break;default:throw Error("Invalid behaviour: "+node.behaviour)}var body=node.body,length=body?body.length:0;if(length==1){result+=generate(body[0])}else{var i=-1;while(++i<length){result+=generate(body[i])}}result+=")";return result}function generateQuantifier(node){assertType(node.type,"quantifier");var quantifier="",min=node.min,max=node.max;switch(max){case undefined:case null:switch(min){case 0:quantifier="*";break;case 1:quantifier="+";break;default:quantifier="{"+min+",}";break}break;default:if(min==max){quantifier="{"+min+"}"}else if(min==0&&max==1){quantifier="?"}else{quantifier="{"+min+","+max+"}"}break}if(!node.greedy){quantifier+="?"}return generateAtom(node.body[0])+quantifier}function generateReference(node){assertType(node.type,"reference");return"\\"+node.matchIndex}function generateTerm(node){assertType(node.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return generate(node)}function generateValue(node){assertType(node.type,"value");var kind=node.kind,codePoint=node.codePoint;switch(kind){case"controlLetter":return"\\c"+fromCodePoint(codePoint+64);case"hexadecimalEscape":return"\\x"+("00"+codePoint.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+fromCodePoint(codePoint);case"null":return"\\"+codePoint;case"octal":return"\\"+codePoint.toString(8);case"singleEscape":switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+codePoint)}case"symbol":return fromCodePoint(codePoint);case"unicodeEscape":return"\\u"+("0000"+codePoint.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+codePoint.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+kind)}}generate.alternative=generateAlternative;generate.anchor=generateAnchor;generate.characterClass=generateCharacterClass;generate.characterClassEscape=generateCharacterClassEscape;generate.characterClassRange=generateCharacterClassRange;generate.disjunction=generateDisjunction;generate.dot=generateDot;generate.group=generateGroup;generate.quantifier=generateQuantifier;generate.reference=generateReference;generate.value=generateValue;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:generate}})}else if(freeExports&&freeModule){freeExports.generate=generate}else{root.regjsgen={generate:generate}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],282:[function(require,module,exports){(function(){function parse(str,flags){var hasUnicodeFlag=(flags||"").indexOf("u")!==-1;var pos=0;var closedCaptureCounter=0;function addRaw(node){node.raw=str.substring(node.range[0],node.range[1]);return node}function updateRawStart(node,start){node.range[0]=start;return addRaw(node)}function createAnchor(kind,rawLength){return addRaw({type:"anchor",kind:kind,range:[pos-rawLength,pos]})}function createValue(kind,codePoint,from,to){return addRaw({type:"value",kind:kind,codePoint:codePoint,range:[from,to]})}function createEscaped(kind,codePoint,value,fromOffset){fromOffset=fromOffset||0;return createValue(kind,codePoint,pos-(value.length+fromOffset),pos)}function createCharacter(matches){var _char=matches[0];var first=_char.charCodeAt(0);if(hasUnicodeFlag){var second;if(_char.length===1&&first>=55296&&first<=56319){second=lookahead().charCodeAt(0);if(second>=56320&&second<=57343){pos++;return createValue("symbol",(first-55296)*1024+second-56320+65536,pos-2,pos)}}}return createValue("symbol",first,pos-1,pos)}function createDisjunction(alternatives,from,to){return addRaw({type:"disjunction",body:alternatives,range:[from,to]})}function createDot(){return addRaw({type:"dot",range:[pos-1,pos]})}function createCharacterClassEscape(value){return addRaw({type:"characterClassEscape",value:value,range:[pos-2,pos]})}function createReference(matchIndex){return addRaw({type:"reference",matchIndex:parseInt(matchIndex,10),range:[pos-1-matchIndex.length,pos]})}function createGroup(behavior,disjunction,from,to){return addRaw({type:"group",behavior:behavior,body:disjunction,range:[from,to]})}function createQuantifier(min,max,from,to){if(to==null){from=pos-1;to=pos}return addRaw({type:"quantifier",min:min,max:max,greedy:true,body:null,range:[from,to]})}function createAlternative(terms,from,to){return addRaw({type:"alternative",body:terms,range:[from,to]})}function createCharacterClass(classRanges,negative,from,to){return addRaw({type:"characterClass",body:classRanges,negative:negative,range:[from,to]})}function createClassRange(min,max,from,to){if(min.codePoint>max.codePoint){throw SyntaxError("invalid range in character class")}return addRaw({type:"characterClassRange",min:min,max:max,range:[from,to]})}function flattenBody(body){if(body.type==="alternative"){return body.body}else{return[body]}}function isEmpty(obj){return obj.type==="empty"}function incr(amount){amount=amount||1;var res=str.substring(pos,pos+amount);pos+=amount||1;return res}function skip(value){if(!match(value)){throw SyntaxError("character: "+value)}}function match(value){if(str.indexOf(value,pos)===pos){return incr(value.length)}}function lookahead(){return str[pos]}function current(value){return str.indexOf(value,pos)===pos}function next(value){return str[pos+1]===value}function matchReg(regExp){var subStr=str.substring(pos);var res=subStr.match(regExp);if(res){res.range=[];res.range[0]=pos;incr(res[0].length);res.range[1]=pos}return res}function parseDisjunction(){var res=[],from=pos;res.push(parseAlternative());while(match("|")){res.push(parseAlternative())}if(res.length===1){return res[0]}return createDisjunction(res,from,pos)}function parseAlternative(){var res=[],from=pos;var term;while(term=parseTerm()){res.push(term)}if(res.length===1){return res[0]}return createAlternative(res,from,pos)}function parseTerm(){if(pos>=str.length||current("|")||current(")")){return null}var anchor=parseAnchor();if(anchor){return anchor}var atom=parseAtom();if(!atom){throw SyntaxError("Expected atom")}var quantifier=parseQuantifier()||false;if(quantifier){quantifier.body=flattenBody(atom);updateRawStart(quantifier,atom.range[0]);return quantifier}return atom}function parseGroup(matchA,typeA,matchB,typeB){var type=null,from=pos;if(match(matchA)){type=typeA}else if(match(matchB)){type=typeB}else{return false}var body=parseDisjunction();if(!body){throw SyntaxError("Expected disjunction")}skip(")");var group=createGroup(type,flattenBody(body),from,pos);if(type=="normal"){closedCaptureCounter++}return group}function parseAnchor(){var res,from=pos;if(match("^")){return createAnchor("start",1)}else if(match("$")){return createAnchor("end",1)}else if(match("\\b")){return createAnchor("boundary",2)}else if(match("\\B")){return createAnchor("not-boundary",2)}else{return parseGroup("(?=","lookahead","(?!","negativeLookahead")}}function parseQuantifier(){var res;var quantifier;var min,max;if(match("*")){quantifier=createQuantifier(0)}else if(match("+")){quantifier=createQuantifier(1)}else if(match("?")){quantifier=createQuantifier(0,1)}else if(res=matchReg(/^\{([0-9]+)\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,min,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,undefined,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),([0-9]+)\}/)){min=parseInt(res[1],10);max=parseInt(res[2],10);if(min>max){throw SyntaxError("numbers out of order in {} quantifier")}quantifier=createQuantifier(min,max,res.range[0],res.range[1])}if(quantifier){if(match("?")){quantifier.greedy=false;quantifier.range[1]+=1}}return quantifier}function parseAtom(){var res;if(res=matchReg(/^[^^$\\.*+?(){[|]/)){return createCharacter(res)}else if(match(".")){return createDot()}else if(match("\\")){res=parseAtomEscape();if(!res){throw SyntaxError("atomEscape")}return res}else if(res=parseCharacterClass()){return res}else{return parseGroup("(?:","ignore","(","normal")}}function parseUnicodeSurrogatePairEscape(firstEscape){if(hasUnicodeFlag){var first,second;if(firstEscape.kind=="unicodeEscape"&&(first=firstEscape.codePoint)>=55296&&first<=56319&&current("\\")&&next("u")){var prevPos=pos;pos++;var secondEscape=parseClassEscape();if(secondEscape.kind=="unicodeEscape"&&(second=secondEscape.codePoint)>=56320&&second<=57343){firstEscape.range[1]=secondEscape.range[1];firstEscape.codePoint=(first-55296)*1024+second-56320+65536;firstEscape.type="value";firstEscape.kind="unicodeCodePointEscape";addRaw(firstEscape)}else{pos=prevPos}}}return firstEscape}function parseClassEscape(){return parseAtomEscape(true)}function parseAtomEscape(insideCharacterClass){var res;res=parseDecimalEscape();if(res){return res}if(insideCharacterClass){if(match("b")){return createEscaped("singleEscape",8,"\\b")}else if(match("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}res=parseCharacterEscape();return res}function parseDecimalEscape(){var res,match;if(res=matchReg(/^(?!0)\d+/)){match=res[0];var refIdx=parseInt(res[0],10);if(refIdx<=closedCaptureCounter){return createReference(res[0])}else{incr(-res[0].length);if(res=matchReg(/^[0-7]{1,3}/)){return createEscaped("octal",parseInt(res[0],8),res[0],1)}else{res=createCharacter(matchReg(/^[89]/));return updateRawStart(res,res.range[0]-1)}}}else if(res=matchReg(/^[0-7]{1,3}/)){match=res[0];if(/^0{1,3}$/.test(match)){return createEscaped("null",0,"0",match.length+1)}else{return createEscaped("octal",parseInt(match,8),match,1)}}else if(res=matchReg(/^[dDsSwW]/)){return createCharacterClassEscape(res[0])}return false}function parseCharacterEscape(){var res;if(res=matchReg(/^[fnrtv]/)){var codePoint=0;switch(res[0]){case"t":codePoint=9;break;case"n":codePoint=10;break;case"v":codePoint=11;break;case"f":codePoint=12;break;case"r":codePoint=13;break}return createEscaped("singleEscape",codePoint,"\\"+res[0])}else if(res=matchReg(/^c([a-zA-Z])/)){return createEscaped("controlLetter",res[1].charCodeAt(0)%32,res[1],2)}else if(res=matchReg(/^x([0-9a-fA-F]{2})/)){return createEscaped("hexadecimalEscape",parseInt(res[1],16),res[1],2)}else if(res=matchReg(/^u([0-9a-fA-F]{4})/)){return parseUnicodeSurrogatePairEscape(createEscaped("unicodeEscape",parseInt(res[1],16),res[1],2))}else if(hasUnicodeFlag&&(res=matchReg(/^u\{([0-9a-fA-F]{1,})\}/))){return createEscaped("unicodeCodePointEscape",parseInt(res[1],16),res[1],4)}else{return parseIdentityEscape()}}function isIdentifierPart(ch){var NonAsciiIdentifierPart=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function parseIdentityEscape(){var ZWJ="‌";var ZWNJ="‍";var res;var tmp;if(!isIdentifierPart(lookahead())){tmp=incr();return createEscaped("identifier",tmp.charCodeAt(0),tmp,1)}if(match(ZWJ)){return createEscaped("identifier",8204,ZWJ)}else if(match(ZWNJ)){return createEscaped("identifier",8205,ZWNJ)}return null}function parseCharacterClass(){var res,from=pos;if(res=matchReg(/^\[\^/)){res=parseClassRanges();skip("]");return createCharacterClass(res,true,from,pos)}else if(match("[")){res=parseClassRanges();skip("]");return createCharacterClass(res,false,from,pos)}return null}function parseClassRanges(){var res;if(current("]")){return[]}else{res=parseNonemptyClassRanges();if(!res){throw SyntaxError("nonEmptyClassRanges")}return res}}function parseHelperClassRanges(atom){var from,to,res;if(current("-")&&!next("]")){skip("-");res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}to=pos;var classRanges=parseClassRanges();if(!classRanges){throw SyntaxError("classRanges")}from=atom.range[0];if(classRanges.type==="empty"){return[createClassRange(atom,res,from,to)]}return[createClassRange(atom,res,from,to)].concat(classRanges)}res=parseNonemptyClassRangesNoDash();if(!res){throw SyntaxError("nonEmptyClassRangesNoDash")}return[atom].concat(res)}function parseNonemptyClassRanges(){var atom=parseClassAtom();if(!atom){throw SyntaxError("classAtom")}if(current("]")){return[atom]}return parseHelperClassRanges(atom)}function parseNonemptyClassRangesNoDash(){var res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}if(current("]")){return res}return parseHelperClassRanges(res)}function parseClassAtom(){if(match("-")){return createCharacter("-")}else{return parseClassAtomNoDash()}}function parseClassAtomNoDash(){var res;if(res=matchReg(/^[^\\\]-]/)){return createCharacter(res[0])}else if(match("\\")){res=parseClassEscape();if(!res){throw SyntaxError("classEscape")}return parseUnicodeSurrogatePairEscape(res)}}str=String(str);if(str===""){str="(?:)"}var result=parseDisjunction();if(result.range[1]!==str.length){throw SyntaxError("Could not parse entire input - got stuck: "+str)}return result}var regjsparser={parse:parse};if(typeof module!=="undefined"&&module.exports){module.exports=regjsparser}else{window.regjsparser=regjsparser}})()},{}],283:[function(require,module,exports){var generate=require("regjsgen").generate;var parse=require("regjsparser").parse;var regenerate=require("regenerate");var iuMappings=require("./data/iu-mappings.json");var ESCAPE_SETS=require("./data/character-class-escape-sets.js");function getCharacterClassEscapeSet(character){if(unicode){if(ignoreCase){return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]}return ESCAPE_SETS.UNICODE[character]}return ESCAPE_SETS.REGULAR[character]}var object={};var hasOwnProperty=object.hasOwnProperty;function has(object,property){return hasOwnProperty.call(object,property)}var UNICODE_SET=regenerate().addRange(0,1114111);var BMP_SET=regenerate().addRange(0,65535);var DOT_SET_UNICODE=UNICODE_SET.clone().remove(10,13,8232,8233);var DOT_SET=DOT_SET_UNICODE.clone().intersection(BMP_SET);regenerate.prototype.iuAddRange=function(min,max){var $this=this;do{var folded=caseFold(min);if(folded){$this.add(folded)}}while(++min<=max);return $this};function assign(target,source){for(var key in source){target[key]=source[key]}}function update(item,pattern){var tree=parse(pattern,"");switch(tree.type){case"characterClass":case"group":case"value":break;default:tree=wrap(tree,pattern)}assign(item,tree)}function wrap(tree,pattern){return{type:"group",behavior:"ignore",body:[tree],raw:"(?:"+pattern+")"}}function caseFold(codePoint){return has(iuMappings,codePoint)?iuMappings[codePoint]:false}var ignoreCase=false;var unicode=false;function processCharacterClass(characterClassItem){var set=regenerate();var body=characterClassItem.body.forEach(function(item){switch(item.type){case"value":set.add(item.codePoint);if(ignoreCase&&unicode){var folded=caseFold(item.codePoint);if(folded){set.add(folded)}}break;case"characterClassRange":var min=item.min.codePoint;var max=item.max.codePoint;set.addRange(min,max);if(ignoreCase&&unicode){set.iuAddRange(min,max)}break;case"characterClassEscape":set.add(getCharacterClassEscapeSet(item.value));break;default:throw Error("Unknown term type: "+item.type)}});if(characterClassItem.negative){set=(unicode?UNICODE_SET:BMP_SET).clone().remove(set)}update(characterClassItem,set.toString());return characterClassItem}function processTerm(item){switch(item.type){case"dot":update(item,(unicode?DOT_SET_UNICODE:DOT_SET).toString());break;case"characterClass":item=processCharacterClass(item);break;case"characterClassEscape":update(item,getCharacterClassEscapeSet(item.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":item.body=item.body.map(processTerm);break;case"value":var codePoint=item.codePoint;var set=regenerate(codePoint);if(ignoreCase&&unicode){var folded=caseFold(codePoint);if(folded){set.add(folded)}}update(item,set.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+item.type)}return item}module.exports=function(pattern,flags){var tree=parse(pattern,flags);ignoreCase=flags?flags.indexOf("i")>-1:false;unicode=flags?flags.indexOf("u")>-1:false;assign(tree,processTerm(tree));return generate(tree)}},{"./data/character-class-escape-sets.js":278,"./data/iu-mappings.json":279,regenerate:280,regjsgen:281,regjsparser:282}],284:[function(require,module,exports){exports.SourceMapGenerator=require("./source-map/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./source-map/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":290,"./source-map/source-map-generator":291,"./source-map/source-node":292}],285:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function ArraySet(){this._array=[];this._set={}}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};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}};ArraySet.prototype.has=function ArraySet_has(aStr){return Object.prototype.hasOwnProperty.call(this._set,util.toSetString(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.')};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)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet})},{"./util":293,amdefine:294}],286:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}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){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aOutParam){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);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aStr.slice(i)}})},{"./base64":287,amdefine:294}],287:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var charToIntMap={};var intToCharMap={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(ch,index){charToIntMap[ch]=index;intToCharMap[index]=ch});exports.encode=function base64_encode(aNumber){if(aNumber in intToCharMap){return intToCharMap[aNumber]}throw new TypeError("Must be between 0 and 63: "+aNumber)};exports.decode=function base64_decode(aChar){if(aChar in charToIntMap){return charToIntMap[aChar]}throw new TypeError("Not a valid base 64 digit: "+aChar)}})},{amdefine:294}],288:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return mid}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare)}return mid}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare)}return aLow<0?-1:aLow}}exports.search=function search(aNeedle,aHaystack,aCompare){if(aHaystack.length===0){return-1}return recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare)}})},{amdefine:294}],289:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function generatedPositionAfter(mappingA,mappingB){var lineA=mappingA.generatedLine; var lineB=mappingB.generatedLine;var columnA=mappingA.generatedColumn;var columnB=mappingB.generatedColumn;return lineB>lineA||lineB==lineA&&columnB>=columnA||util.compareByGeneratedPositions(mappingA,mappingB)<=0}function MappingList(){this._array=[];this._sorted=true;this._last={generatedLine:-1,generatedColumn:0}}MappingList.prototype.unsortedForEach=function MappingList_forEach(aCallback,aThisArg){this._array.forEach(aCallback,aThisArg)};MappingList.prototype.add=function MappingList_add(aMapping){var mapping;if(generatedPositionAfter(this._last,aMapping)){this._last=aMapping;this._array.push(aMapping)}else{this._sorted=false;this._array.push(aMapping)}};MappingList.prototype.toArray=function MappingList_toArray(){if(!this._sorted){this._array.sort(util.compareByGeneratedPositions);this._sorted=true}return this._array};exports.MappingList=MappingList})},{"./util":293,amdefine:294}],290:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");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");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);if(version!=this._version){throw new Error("Unsupported version: "+version)}sources=sources.map(util.normalize);this._names=ArraySet.fromArray(names,true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}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.toArray().slice();smc.__originalMappings=aSourceMap._mappings.toArray().slice().sort(util.compareByOriginalPositions);return smc};SourceMapConsumer.prototype._version=3;Object.defineProperty(SourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});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}});SourceMapConsumer.prototype._nextCharIsMappingSeparator=function SourceMapConsumer_nextCharIsMappingSeparator(aStr){var c=aStr.charAt(0);return c===";"||c===","};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 str=aStr;var temp={};var mapping;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;base64VLQ.decode(str,temp);mapping.generatedColumn=previousGeneratedColumn+temp.value;previousGeneratedColumn=mapping.generatedColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.source=this._sources.at(previousSource+temp.value);previousSource+=temp.value;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source, but no line and column")}base64VLQ.decode(str,temp);mapping.originalLine=previousOriginalLine+temp.value;previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source and line, but no column")}base64VLQ.decode(str,temp);mapping.originalColumn=previousOriginalColumn+temp.value;previousOriginalColumn=mapping.originalColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);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.__generatedMappings.sort(util.compareByGeneratedPositions);this.__originalMappings.sort(util.compareByOriginalPositions)};SourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator){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)};SourceMapConsumer.prototype.computeColumnSpans=function SourceMapConsumer_computeColumnSpans(){for(var index=0;index<this._generatedMappings.length;++index){var mapping=this._generatedMappings[index];if(index+1<this._generatedMappings.length){var nextMapping=this._generatedMappings[index+1];if(mapping.generatedLine===nextMapping.generatedLine){mapping.lastGeneratedColumn=nextMapping.generatedColumn-1;continue}}mapping.lastGeneratedColumn=Infinity}};SourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var index=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositions);if(index>=0){var mapping=this._generatedMappings[index];if(mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!=null&&this.sourceRoot!=null){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}};SourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){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.')};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!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(index>=0){var mapping=this._originalMappings[index];return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};SourceMapConsumer.prototype.allGeneratedPositionsFor=function SourceMapConsumer_allGeneratedPositionsFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:Infinity};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var mappings=[];var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(index>=0){var mapping=this._originalMappings[index];while(mapping&&mapping.originalLine===needle.originalLine){mappings.push({line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)});mapping=this._originalMappings[--index]}}return mappings.reverse()};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;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!=null&&sourceRoot!=null){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":285,"./base64-vlq":286,"./binary-search":288,"./util":293,amdefine:294}],291:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;var MappingList=require("./mapping-list").MappingList;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._skipValidation=util.getArg(aArgs,"skipValidation",false);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=new MappingList;this._sourcesContents=null}SourceMapGenerator.prototype._version=3;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!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};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);if(!this._skipValidation){this._validateMapping(generated,original,source,name)}if(source!=null&&!this._sources.has(source)){this._sources.add(source)}if(name!=null&&!this._names.has(name)){this._names.add(name)}this._mappings.add({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.unsortedForEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};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){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){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};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;var mappings=this._mappings.toArray();for(var i=0,len=mappings.length;i<len;i++){mapping=mappings[i];if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){result+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositions(mapping,mappings[i-1])){continue}result+=","}}result+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){result+=base64VLQ.encode(this._sources.indexOf(mapping.source)-previousSource);previousSource=this._sources.indexOf(mapping.source);result+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;result+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){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!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this)};exports.SourceMapGenerator=SourceMapGenerator})},{"./array-set":285,"./base64-vlq":286,"./mapping-list":289,"./util":293,amdefine:294}],292:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var NEWLINE_CODE=10;var isSourceNode="$$$isSourceNode$$$";function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;this[isSourceNode]=true;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var shiftNextLine=function(){var lineContents=remainingLines.shift();var newLine=remainingLines.shift()||"";return lineContents+newLine};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){var code="";addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{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;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());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}lastMapping=mapping},this);if(remainingLines.length>0){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk[isSourceNode]||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};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[isSourceNode]||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};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[isSourceNode]){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};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};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild[isSourceNode]){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};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i][isSourceNode]){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]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};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}for(var idx=0,length=chunk.length;idx<length;idx++){if(chunk.charCodeAt(idx)===NEWLINE_CODE){generated.line++;generated.column=0;if(idx+1===length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column++}}});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode})},{"./source-map-generator":291,"./util":293,amdefine:294}],293:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){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[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";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 normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=path.charAt(0)==="/";var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;function relative(aRoot,aPath){if(aRoot===""){aRoot="."}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 toSetString(aStr){return"$"+aStr}exports.toSetString=toSetString;function fromSetString(aStr){return aStr.substr(1)}exports.fromSetString=fromSetString;function strcmp(aStr1,aStr2){var s1=aStr1||"";var s2=aStr2||"";return(s1>s2)-(s1<s2)}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;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:294}],294:[function(require,module,exports){(function(process,__filename){"use strict";function amdefine(module,requireFn){"use strict";var defineCache={},loaderCache={},alreadyCalled=false,path=require("path"),makeRequire,stringRequire;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]==="..")){break}else if(i>0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName){var baseParts;if(name&&name.charAt(0)==="."){if(baseName){baseParts=baseName.split("/");baseParts=baseParts.slice(0,baseParts.length-1);baseParts=baseParts.concat(name.split("/"));trimDots(baseParts);name=baseParts.join("/")}}return name}function makeNormalize(relName){return function(name){return normalize(name,relName)}}function makeLoad(id){function load(value){loaderCache[id]=value}load.fromText=function(id,text){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"){return stringRequire(systemRequire,exports,module,deps,relId)}else{deps=deps.map(function(depName){return stringRequire(systemRequire,exports,module,depName,relId)});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};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{if(alreadyCalled){throw new Error("amdefine with no module ID cannot be called more than once per file.")}alreadyCalled=true;e=module.exports;m=module;r=makeRequire(requireFn,e,m,module.id)}if(deps){deps=deps.map(function(depName){return r(depName)})}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){var index=id.indexOf("!"),originalId=id,prefix,plugin;if(index===-1){id=normalize(id,relId);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{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{id=normalize(id,relId)}if(loaderCache[id]){return loaderCache[id]}else{plugin.load(id,makeRequire(systemRequire,exports,module,relId),makeLoad(id),{});return loaderCache[id]}}};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"]}if(id){defineCache[id]=[id,deps,factory]}else{runFactory(id,deps,factory)}}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,require("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:131,path:130}],295:[function(require,module,exports){(function(process){"use strict";var argv=process.argv;module.exports=function(){if(argv.indexOf("--no-color")!==-1||argv.indexOf("--no-colors")!==-1||argv.indexOf("--color=false")!==-1){return false }if(argv.indexOf("--color")!==-1||argv.indexOf("--colors")!==-1||argv.indexOf("--color=true")!==-1||argv.indexOf("--color=always")!==-1){return true}if(process.stdout&&!process.stdout.isTTY){return false}if(process.platform==="win32"){return true}if("COLORTERM"in process.env){return true}if(process.env.TERM==="dumb"){return false}if(/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)){return true}return false}()}).call(this,require("_process"))},{_process:131}],296:[function(require,module,exports){module.exports={name:"6to5",description:"Turn ES6 code into readable vanilla ES5 with source maps",version:"3.3.4",author:"Sebastian McKenzie <sebmck@gmail.com>",homepage:"https://6to5.org/",repository:"6to5/6to5",preferGlobal:true,main:"lib/6to5/index.js",bin:{"6to5":"./bin/6to5/index.js","6to5-node":"./bin/6to5-node","6to5-runtime":"./bin/6to5-runtime"},browser:{"./lib/6to5/index.js":"./lib/6to5/browser.js","./lib/6to5/register.js":"./lib/6to5/register-browser.js"},keywords:["harmony","classes","modules","let","const","var","es6","transpile","transpiler","6to5"],scripts:{bench:"make bench",test:"make test"},dependencies:{"acorn-6to5":"0.11.1-25","ast-types":"~0.6.1",chalk:"^0.5.1",chokidar:"0.12.6",commander:"2.6.0","core-js":"^0.4.9",debug:"^2.1.1","detect-indent":"3.0.0",estraverse:"1.9.1",esutils:"1.1.6","fs-readdir-recursive":"0.1.0",globals:"^5.1.0","js-tokenizer":"1.3.3",lodash:"3.0.0","output-file-sync":"1.1.0","private":"0.1.6","regenerator-6to5":"0.8.9-8",regexpu:"1.1.0",roadrunner:"1.0.4","source-map":"0.1.43","source-map-support":"0.2.9","supports-color":"1.2.0",useragent:"^2.1.5"},devDependencies:{browserify:"8.1.1",chai:"1.10.0",esvalid:"1.1.0",istanbul:"0.3.5",jscs:"1.10.0",jshint:"2.6.0","jshint-stylish":"1.0.0",matcha:"0.6.0",mocha:"2.1.0",rimraf:"2.2.8","uglify-js":"2.4.16"},optionalDependencies:{kexec:"1.0.0"}}},{}],297:[function(require,module,exports){module.exports={"abstract-expression-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-delete":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceDelete",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-get":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-set":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceSet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"apply-constructor":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-comprehension-container":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-from":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-push":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STATEMENT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"async-to-generator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"next",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},{type:"Literal",start:null,end:null,loc:null,range:null,value:"throw",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionDeclaration",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"TryStatement",start:null,end:null,loc:null,range:null,block:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},handler:{type:"CatchClause",start:null,end:null,loc:null,range:null,param:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},guard:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},guardedHandlers:[],finalizer:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"then",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},bind:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Function",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},call:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CONTEXT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"corejs-iterator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CORE_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"$for",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getIterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"default-parameter":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"DEFAULT_VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},defaults:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"define-property":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-default-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-module-declaration":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"extends":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"assign",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:1,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:null,update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},get:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"value",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"in",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"has-own":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},inherits:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"Super expression must either be null or a function, not ",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"+",right:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:false,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__proto__",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require-wildcard":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"let-scoping-return":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"v",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"object-without-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"indexOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"property-method-assignment-wrapper":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-identifier":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"require-assign-key":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},require:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},rest:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"START",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"self-global":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"self",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},set:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"set",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"set",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"value",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"in",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"set",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},slice:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"slice",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"sliced-to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},system:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"System",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"register",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_DEPENDENCIES",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXPORT_IDENTIFIER",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setters",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SETTERS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"execute",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXECUTE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-exports":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-module":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"typeof":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Literal",start:null,end:null,loc:null,range:null,value:"symbol",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},alternate:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"umd-runner-body":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"amd",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"AMD_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_TEST",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}} },{}]},{},[1])(1)});
wrappers/toml.js
pcm-ca/pcm-ca.github.io
import React from 'react' import toml from 'toml-js' import Helmet from 'react-helmet' import { config } from 'config' module.exports = React.createClass({ propTypes () { return { route: React.PropTypes.object, } }, render () { const data = this.props.route.page.data return ( <div> <Helmet title={`${config.siteTitle} | ${data.title}`} /> <h1>{data.title}</h1> <p>Raw view of toml file</p> <pre dangerouslySetInnerHTML={{ __html: toml.dump(data) }} /> </div> ) }, })
ajax/libs/rxjs/2.3.19/rx.lite.extras.js
bspaulding/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { 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; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx'], function (Rx, exports) { return factory(root, exports, Rx); }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SerialDisposable = Rx.SerialDisposable, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, noop = helpers.noop, isScheduler = helpers.isScheduler, observableFromPromise = Observable.fromPromise, slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var argumentOutOfRange = 'Argument out of range'; 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 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 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); /** * 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; }); }; /** * 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(); } }); }); }; /** * 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; }; /** * 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); }); }; /** * 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; }); }; /** * 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; }); }; /** * 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(); }); }); }; /** * 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)); }); }; return Rx; }));
app/javascript/mastodon/features/compose/components/upload.js
tootcafe/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; export default class Upload extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { media: ImmutablePropTypes.map.isRequired, onUndo: PropTypes.func.isRequired, onOpenFocalPoint: PropTypes.func.isRequired, }; handleUndoClick = e => { e.stopPropagation(); this.props.onUndo(this.props.media.get('id')); } handleFocalPointClick = e => { e.stopPropagation(); this.props.onOpenFocalPoint(this.props.media.get('id')); } render () { const { media } = this.props; const focusX = media.getIn(['meta', 'focus', 'x']); const focusY = media.getIn(['meta', 'focus', 'y']); const x = ((focusX / 2) + .5) * 100; const y = ((focusY / -2) + .5) * 100; return ( <div className='compose-form__upload' tabIndex='0' role='button'> <Motion defaultStyle={{ scale: 0.8 }} style={{ scale: spring(1, { stiffness: 180, damping: 12 }) }}> {({ scale }) => ( <div className='compose-form__upload-thumbnail' style={{ transform: `scale(${scale})`, backgroundImage: `url(${media.get('preview_url')})`, backgroundPosition: `${x}% ${y}%` }}> <div className={classNames('compose-form__upload__actions', { active: true })}> <button className='icon-button' onClick={this.handleUndoClick}><Icon id='times' /> <FormattedMessage id='upload_form.undo' defaultMessage='Delete' /></button> <button className='icon-button' onClick={this.handleFocalPointClick}><Icon id='pencil' /> <FormattedMessage id='upload_form.edit' defaultMessage='Edit' /></button> </div> </div> )} </Motion> </div> ); } }
tests/react_native_tests/test_data/native_code/ToolbarWithActions/app/icons/FilterIcon/component.js
ibhubs/sketch-components
/* * @flow */ import React from 'react' import Svg, { Defs, Desc, G, Path, Polygon, Title, } from 'react-native-svg' const FilterIcon = (props) => { const {width, height, color='#000', fillColor='#FFF'} = props return ( <Svg height = '24' version = '1.1' viewBox = '0 0 24 24' width = '24' > <Defs></Defs> <G fill='none' fillRule='evenodd' id='Symbols' stroke='none' strokeWidth='1' > <G id='FilterIcon' > <G> <Polygon id='Bounds' points='0 0 24 0 24 24 0 24' ></Polygon> <Path d='M10,18 L14,18 L14,16 L10,16 L10,18 Z M3,6 L3,8 L21,8 L21,6 L3,6 Z M6,13 L18,13 L18,11 L6,11 L6,13 Z' fill='#FFFFFF' id='Shape' ></Path> </G> </G> </G> </Svg> ) } export default FilterIcon
app/main.js
erlswtshrt/react-es6-boilerplate
import React from 'react'; import Router from 'react-router'; import ReactDOM from 'react-dom'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import routes from './routes'; let history = createBrowserHistory(); ReactDOM.render(<Router history={history}>{routes}</Router>, document.getElementById('app'));
public/src/js/components/popups/components/login/index.js
Robertmw/imagistral
/** * * Login popup * @parent Popups * @author Robert P. * */ import React from 'react'; import BaseComponent from '../../../base-component/base-component'; import {branch} from 'baobab-react/higher-order'; import Auth from '../../../../services/facebook-auth'; import Cookie from '../../../../services/cookies'; import * as actions from '../../actions'; class LoginPopup extends BaseComponent { constructor(props) { super(props); this._bind('_authenticate', '_login'); let authConfig = { appId: '999809560057190', xfbml: false, version: 'v2.3', callback: this._login }; this.FbAuth = new Auth(authConfig); this.Cookies = new Cookie(); } _authenticate() { this.FbAuth.authenticate(this._login); } _login(payload) { this.props.actions.authUser(payload); this.props.handleClose(); this.Cookies.createCookie('avatar', payload.avatar, 100, 'Imagistral'); this.Cookies.createCookie('first_name', payload.first_name, 100, 'Imagistral'); this.Cookies.createCookie('last_name', payload.last_name, 100, 'Imagistral'); } render() { return ( <div className="popup bounceIn animated"> <div className="popup__header"> <h3 className="popup__title">Login with</h3> <span className="popup__close icon-cross" onClick={this.props.handleClose} /> </div> <div className="popup__wrapper popup__wrapper--inline"> <div className="btn btn--wide btn--facebook" onClick= {this._authenticate} > <label className="icon-facebook_square" /> <span className="btn__title">Facebook</span> </div> <div className="btn btn--wide btn--google"> <label className="icon-google_square" /> <span className="btn__title">Google Plus</span> </div> </div> <div className="popup__footer"> <p className="popup__sidenote">* Don't worry we won't use your info, yet!</p> </div> </div> ); } } export default branch(LoginPopup, { actions: { authUser: actions.authUser } });
ajax/libs/yui/3.9.0/simpleyui/simpleyui.js
2947721120/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 @main yui @submodule yui-base **/ /*jshint eqeqeq: false*/ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. This is the constructor for all YUI instances. This is a self-instantiable factory function, meaning you don't need to precede it with the `new` operator. You can invoke it directly like this: YUI().use('*', function (Y) { // Y is a new YUI instance. }); But it also works like this: var Y = YUI(); The `YUI` constructor accepts an optional config object, like this: YUI({ debug: true, combine: false }).use('node', function (Y) { // Y.Node is ready to use. }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. If a global `YUI` object is already defined, the existing YUI object will not be overwritten, to ensure that defined namespaces are preserved. Each YUI instance has full custom event support, but only if the event system is available. @class YUI @uses EventTarget @constructor @global @param {Object} [config]* Zero or more optional configuration objects. Config values are stored in the `Y.config` property. See the <a href="config.html">Config</a> docs 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(); /** Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts. @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 }); @property {Object} GlobalConfig @global @static **/ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** Page-level config applied to all YUI instances created on the current page. This is applied after `YUI.GlobalConfig` and before any instance-level configuration. @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 }); @property {Object} YUI_config @global **/ 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/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', 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, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; 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; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); 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.5.0'; // dev time hack for cdn test } proto = { /** Applies a new configuration object to the config of this YUI instance. 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, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** Old way to apply a config to this instance (calls `applyConfig` under the hood). @private @method _config @param {Object} o The config to apply **/ _config: function(o) { this.applyConfig(o); }, /** Initializes this YUI instance. @private @method _init **/ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** The version number of this YUI instance. This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree. @property {String} version **/ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'], loaderExtras: ['loader-rollup', 'loader-yui3'], 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-davglass" 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-davglass/yui-davglass.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(/[^a-z0-9_]+/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 || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win, global: Function('return this')() }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) { YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL); } 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 YUI modules were defined at the time that this instance was created. @method _setup @private **/ _setup: function() { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** Executes the named method on the specified YUI instance if that method is whitelisted. @method applyTo @param {String} id YUI instance id. @param {String} method Name of the method to execute. For example: 'Object.keys'. @param {Array} args Arguments to apply to the method. @return {Mixed} Return value from the applied method, or `null` if the specified instance was not found or the method was not whitelisted. **/ 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 && m.apply(instance, args); } return null; }, /** Registers a YUI module and makes it available for use in a `YUI().use()` call or as a dependency for other modules. The easiest way to create a first-class YUI module is to use <a href="http://yui.github.com/shifter/">Shifter</a>, the YUI component build tool. Shifter will automatically wrap your module code in a `YUI.add()` call along with any configuration info required for the module. @example YUI.add('davglass', function (Y) { Y.davglass = function () { }; }, '3.4.0', { requires: ['harley-davidson', 'mt-dew'] }); @method add @param {String} name Module name. @param {Function} fn Function containing module code. This function will be executed whenever the module is attached to a specific YUI instance. @param {YUI} fn.Y The YUI instance to which this module is attached. @param {String} fn.name Name of the module @param {String} version Module version number. This is currently used only for informational purposes, and is not used internally by YUI. @param {Object} [config] Module config. @param {Array} [config.requires] Array of other module names that must be attached before this module can be attached. @param {Array} [config.optional] Array of optional module names that should be attached before this module is attached if they've already been loaded. If the `loadOptional` YUI option is `true`, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. @param {Array} [config.use] Array of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules. @return {YUI} This YUI instance. **/ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } } return this; }, /** Executes the callback function associated with each required module, attaching the module to this YUI instance. @method _attach @param {Array} r The array of modules to attach @param {Boolean} [moot=false] If `true`, don't throw a warning if the module is not attached. @private **/ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, def, go, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); 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 ^davglass 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); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; for (j in loader.moduleInfo[name].expanded_map) { if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } 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) { if (Y.config.throwFail) { mod.fn(Y, name); } else { 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; }, /** Delays the `use` callback until another event has taken place such as `window.onload`, `domready`, `contentready`, or `available`. @private @method _delayCallback @param {Function} cb The original `use` callback. @param {String|Object} until Either an event name ('load', 'domready', etc.) or an object containing event/args keys for contentready/available. @return {Function} **/ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } return function() { var args = arguments; Y._use(mod, function() { Y.on(until.event, function() { args[1].delayUntil = until.event; cb.apply(Y, args); }, until.args); }); }; }, /** Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen: * All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the `use()` callback will be executed synchronously after the modules are attached. * One or more modules have not yet been loaded, or the Get utility is not available, or the `bootstrap` config option is `false`. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and the `use()` callback will be executed synchronously. * One or more modules are missing and the Loader is not available but the Get utility is, and `bootstrap` is not `false`. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state: * One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the `use()` callback will be executed asynchronously. @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. YUI().use(['dd', 'node'], function (Y) { // ... }); // Attaches all modules that have already been loaded. YUI().use('*', function (Y) { // ... }); // Attaches a gallery module. YUI().use('gallery-yql', function (Y) { // ... }); // Attaches a YUI 2in3 module. YUI().use('yui2-datatable', function (Y) { // ... }); @method use @param {String|Array} modules* One or more module names to attach. @param {Function} [callback] Callback function to be executed once all specified modules and their dependencies have been attached. @param {YUI} callback.Y The YUI instance created for this sandbox. @param {Object} callback.status Object containing `success`, `msg` and `data` properties. @chainable **/ 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(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } 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._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; }, /** Handles Loader notifications about attachment/load errors. @method _notify @param {Function} callback Callback to pass to `Y.config.loadErrorFn`. @param {Object} response Response returned from Loader. @param {Array} args Arguments 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) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** Called from the `use` method queue to ensure that only one set of loading logic is performed at a time. @method _use @param {String} args* One or more modules to attach. @param {Function} [callback] Function to call once all required modules have been attached. @private **/ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; 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 ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { 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()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // 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._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } 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) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance. When called statically, a namespace will be created on the YUI global object: // Create `YUI.your.namespace.here` as nested objects, preserving any // objects that already exist instead of overwriting them. YUI.namespace('your.namespace.here'); When called as a method on a YUI instance, a namespace will be created on that 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 and will not be overwritten. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace('really.long.nested.namespace'); Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function. @method namespace @param {String} namespace* One or more namespaces to create. @return {Object} Reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present 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] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } 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; }, /** Reports an error. The reporting mechanism is controlled by the `throwFail` configuration attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is truthy, a JS exception is thrown. If an `errorFn` is specified in the config it must return `true` to indicate that the exception was handled and keep it from being thrown. @method error @param {String} msg Error message. @param {Error|String} [e] JavaScript error object or an error string. @param {String} [src] Source of the error (such as the name of the module in which the error occurred). @chainable **/ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** Generates an id string that is unique among all YUI instances in this execution context. @method guid @param {String} [pre] Prefix. @return {String} Unique id. **/ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** Returns a unique id associated with the given object and (if *readOnly* is falsy) stamps the object with that id so it can be identified in the future. Stamping an object involves adding a `_yuid` property to it that contains the object's id. One exception to this is that in Internet Explorer, DOM nodes have a `uniqueID` property that contains a browser-generated unique id, which will be used instead of a YUI-generated id when available. @method stamp @param {Object} o Object to stamp. @param {Boolean} readOnly If truthy and the given object has not already been stamped, the object will not be modified and `null` will be returned. @return {String} Object's unique id, or `null` if *readOnly* was truthy and the given object was not already stamped. **/ 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 this 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; } /** Safe `instanceof` wrapper that works around a memory leak in IE when the object being tested is `window` or `document`. Unless you are testing objects that may be `window` or `document`, you should use the native `instanceof` operator instead of this method. @method instanceOf @param {Object} o Object to check. @param {Object} type Class to check against. @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]; } } /** Applies a configuration to all YUI instances in this execution context. The main use case for this method is in "mashups" where several third-party scripts need to write to a global YUI config, but cannot share a single centrally-managed config object. This way they can all call `YUI.applyConfig({})` instead of overwriting the single global config. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function (Y) { // Module davglass will be available here. }); @method applyConfig @param {Object} o Configuration object to apply. @static @since 3.5.0 **/ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // 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; /** * Set a method to be called when `Get.script` is called in Node.js * `Get` will open the file, then pass it's content and it's path * to this method before attaching it. Commonly used for code coverage * instrumentation. <strong>Calling this multiple times will only * attach the last hook method</strong>. This method is only * available in Node.js. * @method setLoadHook * @static * @param {Function} fn The function to set * @param {String} fn.data The content of the file * @param {String} fn.path The file path of the file */ YUI.setLoadHook = function(fn) { YUI._getLoadHook = fn; }; /** * Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook` * @method _getLoadHook * @private * @param {String} data The content of the file * @param {String} path The file path of the file */ YUI._getLoadHook = null; } }()); /** Config object that contains all of the configuration options for this `YUI` instance. This object is supplied by the implementer when instantiating YUI. Some properties have default values if they are not supplied by the implementer. This object 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 **/ /** If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata if they're needed to load additional dependencies and aren't already available. Setting this to `false` will prevent YUI from automatically loading the Loader and module metadata, so you will need to manually ensure that they're available or handle dependency resolution yourself. @property {Boolean} bootstrap @default true **/ /** @property {Object} aliases **/ /** A hash of module group definitions. For each group you can specify a list of modules and the base path and combo spec to use when dynamically loading the modules. @example groups: { yui2: { // specify whether or not this group has a combo service combine: true, // The comboSeperator to use with this group's combo handler comboSep: ';', // The maxURLLength for this server maxURLLength: 500, // 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 {Object} groups **/ /** Path to the Loader JS file, relative to the `base` path. This is used to dynamically bootstrap the Loader when it's needed and isn't yet available. @property {String} loaderPath @default "loader/loader-min.js" **/ /** If `true`, YUI will attempt to load CSS dependencies and skins. Set this to `false` to prevent YUI from loading any CSS, or set it to the string `"force"` to force CSS dependencies to be loaded even if their associated JS modules are already loaded. @property {Boolean|String} fetchCSS @default true **/ /** Default gallery version used to build gallery module urls. @property {String} gallery @since 3.1.0 **/ /** Default YUI 2 version used to build YUI 2 module urls. This is used for intrinsic YUI 2 support via the 2in3 project. Also see the `2in3` config for pulling different revisions of the wrapped YUI 2 modules. @property {String} yui2 @default "2.9.0" @since 3.1.0 **/ /** Revision number of YUI 2in3 modules that should be used when loading YUI 2in3. @property {String} 2in3 @default "4" @since 3.1.0 **/ /** Alternate console log function that should be used in environments without a supported native console. This function is executed with the YUI instance as its `this` object. @property {Function} logFn @since 3.1.0 **/ /** Callback to execute when `Y.error()` is called. It receives the error message and a JavaScript error object if one was provided. This function is executed with the YUI instance as its `this` object. Returning `true` from this function will prevent an exception from being thrown. @property {Function} errorFn @param {String} errorFn.msg Error message @param {Object} [errorFn.err] Error object (if one was provided). @since 3.2.0 **/ /** A callback to execute when Loader fails to load one or more resources. This could be because of a script load failure. It could also be because a module fails to register itself when the `requireRegistration` config is `true`. If this function is defined, the `use()` callback will only be called when the loader succeeds. Otherwise, `use()` will always executes unless there was a JavaScript error when attaching a module. @property {Function} loadErrorFn @since 3.3.0 **/ /** If `true`, Loader will expect all loaded scripts to be first-class YUI modules that register themselves with the YUI global, and will trigger a failure if a loaded script does not register a YUI module. @property {Boolean} requireRegistration @default false @since 3.3.0 **/ /** Cache serviced use() requests. @property {Boolean} cacheUse @default true @since 3.3.0 @deprecated No longer used. **/ /** Whether or not YUI should use native ES5 functionality when available for features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will always use its own fallback implementations instead of relying on ES5 functionality, even when ES5 functionality is available. @property {Boolean} useNativeES5 @default true @since 3.5.0 **/ /** * Leverage native JSON stringify if the browser has a native * implementation. In general, this is a good idea. See the Known Issues * section in the JSON user guide for caveats. The default value is true * for browsers with native JSON support. * * @property useNativeJSONStringify * @type Boolean * @default true * @since 3.8.0 */ /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeJSONParse * @type Boolean * @default true * @since 3.8.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property delayUntil @type String|Object @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function (Y) { // This will not execute until 'domeready' occurs. }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args : '#foo' } }, function (Y) { // This will not execute until a node matching the selector "#foo" is // available in the DOM. }); @property {Object|String} delayUntil @since 3.6.0 **/ YUI.add('yui-base', function (Y, NAME) { /* * 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, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * 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 = L._isNative(Array.isArray) ? 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'; }; /** * 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); }; /** * <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 * &nbsp; * 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 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'; }; /** * 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; } }; /** * 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(); }; /** * 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 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+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @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'); }; /** @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; /*jshint expr: true*/ 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; /** 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 = Lang._isNative(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. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } 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 = Lang._isNative(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; }; /** 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 scrollTo/document (window. From DOM.isWindow test which we can't use here), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * 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) { /*jshint expr: true*/ cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); /*jshint eqeqeq: false*/ if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** 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 i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. 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 {Number} [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 // property existence check 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; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; 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; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; 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 Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, 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 = Lang._isNative(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'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * 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 = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { 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) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * 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 (!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(Object(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 on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {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, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 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 Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * 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, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0, /** * Window8/IE10 Application host environment * @property winjs * @type Boolean * @static */ winjs: !!((typeof Windows !== "undefined") && Windows.System), /** * Are touch/msPointer events available on this device * @property touchEnabled * @type Boolean * @static */ touchEnabled: false }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } 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; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // 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; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).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.os = 'ios'; 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]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } 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) if (/Opera/.test(ua)) { 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+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } 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]); } } } } } } //Check for known properties to tell if touch events are enabled on this device or if //the number of MSPointer touchpoints on this device is greater than 0. if (win && nav && !(o.chrome && o.chrome < 6)) { o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0))); } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process === 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); /*jshint expr: true*/ isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "anim-shape-transform": ["anim-shape"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","router","view","view-node-map"], "attribute": ["attribute-base","attribute-complex"], "attribute-events": ["attribute-observable"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "axes": ["axis-numeric","axis-category","axis-time","axis-stacked"], "axes-base": ["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "charts": ["charts-base"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "color": ["color-base","color-hsl","color-harmony"], "controller": ["router"], "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-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatype": ["datatype-date","datatype-number","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"], "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","editor-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-touch","event-move","event-flick","event-valuechange","event-tap"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "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"], "template": ["template-base","template-micro"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { } else { } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { } else { } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { } else { } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes // IE10 doesn't return true for the MDN feature test, so setting it explicitly, // because it is async by default, and allows you to disable async by setting it to false async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10), // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+ cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10)) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; options._onFinish = Get._onTransactionFinish; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _onTransactionFinish : function() { Get._pending = null; Get._next(); }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(item.callback); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._reqsWaiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._reqsWaiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } self._reqsWaiting = requests.length; for (i = 0, len = requests.length; i < len; ++i) { req = requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } if (options._onFinish) { options._onFinish(); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. if (ua.ie >= 10) { // We currently need to introduce a timeout for IE10, since it // calls onerror/onload synchronously for 304s - messing up existing // program flow. // Remove this block if the following bug gets fixed by GA /*jshint maxlen: 1500 */ // https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload node.onerror = function() { setTimeout(onError, 0); }; node.onload = function() { setTimeout(onLoad, 0); }; } else { node.onerror = onError; node.onload = onLoad; } // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._reqsWaiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._reqsWaiting -= 1; this._next(); } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ 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(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } 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 (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // 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" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "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" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "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" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "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" }); // graphics-vml-default add('load', '11', { "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" }); // history-hash-ie add('load', '12', { "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" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "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 || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * 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, NAME) { /** * 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 src = src || ""; if (typeof src !== "undefined") { 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, NAME) { /** * 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) : NO_ARGS; o = o || Y.config.win || Y; 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('yui', function (Y, NAME) {}, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('oop', function (Y, NAME) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Copies object properties from the supplier to the receiver. If the target has * the property, and the property is an object, the target object will be * augmented with the supplier's value. * * @method aggregate * @param {Object} receiver Object to receive the augmentation. * @param {Object} supplier Object that supplies the properties with which to * augment the receiver. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver * will be overwritten if found on the supplier. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this * list will be applied to the receiver. * @return {Object} Augmented object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** * Deep object/array copy. Function clones are actually * wrappers around the original function. * Array-like objects are treated as arrays. * Primitives are returned untouched. Optionally, a * function can be provided to handle other data types, * filter keys, validate values, etc. * * NOTE: Cloning a non-trivial object is a reasonably heavy operation, due to * the need to recurrsively iterate down non-primitive properties. Clone * should be used only when a deep clone down to leaf level properties * is explicitly required. * * In many cases (for example, when trying to isolate objects used as * hashes for configuration properties), a shallow copy, using Y.merge is * normally sufficient. If more than one level of isolation is required, * Y.merge can be used selectively at each level which needs to be * isolated from the original without going all the way to leaf properties. * * @method clone * @param {object} o what to clone. * @param {boolean} safe if true, objects will not have prototype * items from the source. If false, they will. In this case, the * original is initially protected, but the clone is not completely * immune from changes to the source object prototype. Also, cloned * prototype items that are deleted from the clone will result * in the value of the source prototype being exposed. If operating * on a non-safe clone, items should be nulled out rather than deleted. * @param {function} f optional function to apply to each item in a * collection; it will be executed prior to applying the value to * the new object. Return false to prevent the copy. * @param {object} c optional execution context for f. * @param {object} owner Owner object passed when clone is iterating * an object. Used to set up context for cloned functions. * @param {object} cloned hash of previously cloned objects to avoid * multiple clones. * @return {Array|Object} the cloned object. */ Y.clone = function(o, safe, f, c, owner, cloned) { if (!L.isObject(o)) { return o; } // @todo cloning YUI instances doesn't currently work if (Y.instanceOf(o, YUI)) { return o; } var o2, marked = cloned || {}, stamp, yeach = Y.each; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } // #2528250 don't try to clone element properties if (!o.addEventListener && !o.attachEvent) { yeach(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); } if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ 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(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } 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 (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // 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" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "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" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "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" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "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" }); // graphics-vml-default add('load', '11', { "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" }); // history-hash-ie add('load', '12', { "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" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "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 || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dom-core', function (Y, NAME) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], // IE < 8 throws on node.contains(textNode) supportsContainsTextNode = (function() { var node = Y.config.doc.createElement('div'), textNode = node.appendChild(Y.config.doc.createTextNode('')), result = false; try { result = node.contains(textNode); } catch(e) {} return result; })(), /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @main dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, getId: function(node) { var id; // HTMLElement returned from FORM when INPUT name === "id" // IE < 8: HTMLCollection returned when INPUT id === "id" // via both getAttribute and form.id if (node.id && !node.id.tagName && !node.id.item) { id = node.id; } else if (node.attributes && node.attributes.id) { id = node.attributes.id.value; } return id; }, setId: function(node, id) { if (node.setAttribute) { node.setAttribute('id', id); } else { node.id = id; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf, stopFn) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf, stopFn) { var ancestor = element, ret = []; while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) { testSelf = false; if (ancestor) { ret.unshift(ancestor); if (stopFn && stopFn(ancestor)) { return ret; } } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all, stopAt) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } if (stopAt && stopAt(element)) { return null; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS] && // IE < 8 throws on node.contains(textNode) so fall back to brute. // Falling back for other nodeTypes as well. (needle[NODE_TYPE] === 1 || supportsContainsTextNode)) { ret = element[CONTAINS](needle); } else if (element[COMPARE_DOCUMENT_POSITION]) { // Match contains behavior (node.contains(node) === true). // Needed for Firefox < 4. if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } else { ret = Y_DOM._bruteContains(element, needle); } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.scrollTo && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@', {"requires": ["oop", "features"]}); YUI.add('dom-base', function (Y, NAME) { /** * @for DOM * @module dom */ var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } }; } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { } else if (node.selectedIndex > -1) { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _children: function(node, tag) { var i = 0, children = node.children, childNodes, hasComments, child; if (children && children.tags) { // use tags filter when possible if (tag) { children = node.children.tags(tag); } else { // IE leaks comments into children hasComments = children.tags('!').length; } } if (!children || (!children.tags && tag) || hasComments) { childNodes = children || node.childNodes; children = []; while ((child = childNodes[i++])) { if (child.nodeType === 1) { if (!tag || tag === child.tagName) { children.push(child); } } } } return children || []; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (newNode && where.parentNode) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': if (newNode) { nodeParent.insertBefore(newNode, node); } break; case 'after': if (newNode) { if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } } break; default: if (newNode) { node.appendChild(newNode); } } } } else if (newNode) { node.appendChild(newNode); } return ret; }, wrap: function(node, html) { var parent = (html && html.nodeType) ? html : Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = Y.DOM._children(frag, 'tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; }; creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@', {"requires": ["dom-core"]}); YUI.add('dom-style', function (Y, NAME) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', TRANSFORMORIGIN = 'transformOrigin', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('dom-style-ie', function (Y, NAME) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@', {"requires": ["dom-style"]}); YUI.add('dom-screen', function (Y, NAME) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, mode, box, offX, offY, doc, win, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; mode = doc[COMPAT_MODE]; if (mode !== _BACK_COMPAT) { rootNode = doc[DOCUMENT_ELEMENT]; } else { rootNode = doc.body; } // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { win = doc.defaultView; // inline scroll calc for perf if (win && 'pageXOffset' in win) { scrollLeft = win.pageXOffset; scrollTop = win.pageYOffset; } else { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); } if (Y.UA.ie) { // IE < 8, quirks, or compatMode if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) { offX = rootNode.clientLeft; offY = rootNode.clientTop; } } box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (offX || offY) { xy[0] -= offX; xy[1] -= offY; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** Gets the width of vertical scrollbars on overflowed containers in the body content. @method getScrollbarWidth @return {Number} Pixel width of a scrollbar in the current browser **/ getScrollbarWidth: Y.cached(function () { var doc = Y.config.doc, testNode = doc.createElement('div'), body = doc.getElementsByTagName('body')[0], // 0.1 because cached doesn't support falsy refetch values width = 0.1; if (body) { testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;"; testNode.appendChild(doc.createElement('p')).style.height = '1px'; body.insertBefore(testNode, body.firstChild); width = testNode.offsetWidth - testNode.clientWidth; body.removeChild(testNode); } return width; }, null, 0.1), /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Number} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Number} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } } else { } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Number} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Number} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passed nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node The node to get the region from * @param {Object} node2 The second node to get the region from or an Object literal of the region * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@', {"requires": ["dom-base", "dom-style"]}); YUI.add('selector-native', function (Y, NAME) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _types: { esc: { token: '\uE000', re: /\\[:\[\]\(\)#\.\'\>+~"]/gi }, attr: { token: '\uE001', re: /(\[[^\]]*\])/g }, pseudo: { token: '\uE002', re: /(\([^\)]*\))/g } }, useNative: true, _escapeId: function(id) { if (id) { id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1'); } return id; }, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } return (firstOnly) ? (ret[0] || null) : ret; }, _replaceSelector: function(selector) { var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc. attrs, pseudos; // first replace escaped chars, which could be present in attrs or pseudos selector = Y.Selector._replace('esc', selector); // then replace pseudos before attrs to avoid replacing :not([foo]) pseudos = Y.Selector._parse('pseudo', selector); selector = Selector._replace('pseudo', selector); attrs = Y.Selector._parse('attr', selector); selector = Y.Selector._replace('attr', selector); return { esc: esc, attrs: attrs, pseudos: pseudos, selector: selector }; }, _restoreSelector: function(replaced) { var selector = replaced.selector; selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _replaceCommas: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; if (selector) { selector = selector.replace(/,/g, '\uE007'); replaced.selector = selector; selector = Y.Selector._restoreSelector(replaced); } return selector; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { if (selector.indexOf(',') > -1) { selector = Y.Selector._replaceCommas(selector); } var groups = selector.split('\uE007'), // split on replaced comma token queries = [], prefix = '', id, i, len; if (node) { // enforce for element scoping if (node.nodeType === 1) { // Elements only id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } prefix = '[id="' + id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, id, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); }, _parse: function(name, selector) { return selector.match(Y.Selector._types[name].re); }, _replace: function(name, selector) { var o = Y.Selector._types[name]; return selector.replace(o.re, o.token); }, _restore: function(name, selector, items) { if (items) { var token = Y.Selector._types[name].token, i, len; for (i = 0, len = items.length; i < len; ++i) { selector = selector.replace(token, items[i]); } } return selector; } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('selector', function (Y, NAME) { }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { this._kds = Y.CustomEvent.keepDeprecatedSubs; o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ if (this._kds) { this.subscribers = {}; } /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ this._subscribers = []; /** * 'After' subscribers * @property afters * @type Subscriber {} */ if (this._kds) { this.afters = {}; } /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ this._afters = []; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.subCount = 0; // this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this._subscribers.length, a = this._afters.length, sib = this.sibling; if (sib) { s += sib._subscribers.length; a += sib._afters.length; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = this._subscribers, a = this._afters, sib = this.sibling; s = (sib) ? s.concat(sib._subscribers) : s.concat(); a = (sib) ? a.concat(sib._afters) : a.concat(); return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this._afters.push(s); } else { this._subscribers.push(s); } if (this._kds) { if (when == AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = nativeSlice.call(arguments, 0); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; i = YArray.indexOf(subs, s, 0); } if (s && subs[i] === s) { subs.splice(i, 1); } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; events = edata.events; ce = events[type]; this._monitor('publish', type, { args: arguments }); if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // TODO: Lazy publish goes here. defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, defaults); if (opts) { ce.applyConfig(opts, true); } events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), yuievt = this._yuievt, pre = yuievt.config.prefix, ce, ret, ce2, args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } this._monitor('fire', (ce || t), { args: args }); // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]}); YUI.add('event-custom-complex', function (Y, NAME) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, key, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype, mixFacadeProps = function(facade, payload) { var p; for (p in payload) { if (!(FACADE_KEYS.hasOwnProperty(p))) { facade[p] = payload[p]; } } }; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || EMPTY; this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property _type * @type string * @private */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.mix(Y.EventFacade.prototype, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret, events, subs, postponed, self = this, host = self.host || self, next, oldbubble; if (self.stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != self.stack.next.type) { self.log('queue ' + self.type); self.stack.queue.push([self, args]); return true; } } es = self.stack || { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; if (self.stoppedFn) { events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } if (subs[0]) { self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; es.bubbling = self.type; if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); es.bubbling = oldbubble; } if (self.prevented) { if (self.preventedFn) { self.preventedFn.apply(host, args); } } else if (self.defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { postponed = subs[1]; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } self.stack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } // Kill the cached facade to free up memory. // Otherwise we have the facade from the last fire, sitting around forever. self._facade = null; return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { // protect the event facade properties mixFacadeProps(ef, o); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } if (this.events) { this.events.fire('stopped', this); } }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } if (this.events) { this.events.fire('stopped', this); } }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = {}; // Flatten whitelist for (key in FACADE) { FACADE_KEYS[key] = true; } }, '@VERSION@', {"requires": ["event-custom-base"]}); YUI.add('node-core', function (Y, NAME) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @main node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @type DOMNode * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @type String * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @type Object * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Node | HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Node | NodeList | Any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && args[0]._node) { args[0] = args[0]._node; } if (args[1] && args[1]._node) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { DATA_PREFIX: 'data-', /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (refNode && refNode._node) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * If fn is not passed as an argument, the parent node will be returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @param {String | Function} stopFn optional A selector string or boolean * method to indicate when the search should stop. The search bails when the function * returns true or the selector matches. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf, stopFn) { // testSelf is optional, check for stopFn as 2nd arg if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf, stopFn) { if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a single Node instance, the first element matching the given * CSS selector. * Returns null if no match found. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node | null} A Node instance for the matching HTMLElement or null * if no match found. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; return nodelist; }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Node | HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners. * Note that destroy() will not remove the node from its parent or from the DOM. For that * functionality, call remove(true). * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } else { // purge in case added by other means Y.Event.purgeElement(node); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && a._node) { a = a._node; } if (b && b._node) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor * @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList. */ var NodeList = function(nodes) { var tmp = []; if (nodes) { if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (nodes._node) { // Y.Node nodes = [nodes._node]; } else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes || []; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { _invoke: function(method, args, getter) { var ret = (getter) ? [] : this; this.each(function(node) { var val = node[method].apply(node, args); if (getter) { ret.push(val); } }); return ret; }, /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return {Node} a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Node | DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance. Nulls internal node references, * removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to * remove listeners from the node's subtree (default is false) * @see Node.destroy */ 'destroy', /** * Called on each Node instance. Removes and destroys all of the nodes * within the node * @method empty * @chainable * @see Node.empty */ 'empty', /** * Called on each Node instance. Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * @see Node.remove */ 'remove', /** * Called on each Node instance. Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node} The last item in the NodeList. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node} The first item in the NodeList. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method unshift * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ // one-off implementation due to IE returning boolean, breaking chaining Y.Node.prototype.removeAttribute = function(attr) { var node = this._node; if (node) { node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive } return this; }; Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@', {"requires": ["dom-core", "selector"]}); YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using given named effect. * @method toggleView * @for Node * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using given named effect. * @method toggleView * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { name = this.DATA_PREFIX + name; var node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '@VERSION@', {"requires": ["event-base", "node-core", "dom-base"]}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function (Y, NAME) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; // charCode is unknown in keyup, keydown. keyCode is unknown in keypress. // FF 3.6 - 8+? pass 0 for keyCode in keypress events. // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup. // Webkit and IE9+? duplicate charCode in keyCode. // Opera never sets charCode, always keyCode (though with the charCode). // IE6-8 don't set charCode or which. // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and // which=charCode in keypress. // // Moral of the story: (e.which || e.keyCode) will always return the // known code for that key event phase. e.keyCode is often different in // keypress from keydown and keyup. c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; // Fill in e.which for IE - implementers should always use this over // e.keyCode or e.charCode. this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event * @type {Native DOM Event} * @private */ /** The name of the event (e.g. "click") @property type @type {String} **/ /** `true` if the "alt" or "option" key is pressed. @property altKey @type {Boolean} **/ /** `true` if the shift key is pressed. @property shiftKey @type {Boolean} **/ /** `true` if the "Windows" key on a Windows keyboard, "command" key on an Apple keyboard, or "meta" key on other keyboards is pressed. @property metaKey @type {Boolean} **/ /** `true` if the "Ctrl" or "control" key is pressed. @property ctrlKey @type {Boolean} **/ /** * The X location of the event on the page (including scroll) * @property pageX * @type {Number} */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type {Number} */ /** * The X location of the event in the viewport * @property clientX * @type {Number} */ /** * The Y location of the event in the viewport * @property clientY * @type {Number} */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type {Number} */ /** * The charCode for key events. Same as keyCode * @property charCode * @type {Number} */ /** * The button that was pushed. 1 for left click, 2 for middle click, 3 for * right click. This is only reliably populated on `mouseup` events. * @property button * @type {Number} */ /** * The button that was pushed. Same as button. * @property which * @type {Number} */ /** * Node reference for the targeted element * @property target * @type {Node} */ /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type {Node} */ /** * Node reference to the relatedTarget * @property relatedTarget * @type {Node} */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type {Number} */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * @module event * @main event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var YDOM = Y.DOM, _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { // TODO: See if there's a more performant way to return true early on this, for the common case return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !YDOM.isWindow(o)); } catch(ex) { return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.hasSubs()) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = YDOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { ret = Event.onAvailable(el, function() { ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = YDOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return YDOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; try { if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } } catch (e) { } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { executeItem(el, item); _avail[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); len = children.length; for (i = 0; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {CustomEvent} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } try { add(win, "unload", onUnload); } catch(e) { } Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); }()); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@', {"requires": ["event-custom-base"]}); (function() { var stateChangeListener, GLOBAL_ENV = YUI.Env, config = YUI.config, doc = config.doc, docElement = doc && doc.documentElement, EVENT_NAME = 'onreadystatechange', pollInterval = config.pollInterval || 40; if (docElement.doScroll && !GLOBAL_ENV._ieready) { GLOBAL_ENV._ieready = function() { GLOBAL_ENV._ready(); }; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the doScroll() method on the root element. // This isolates what appears to be a safe moment to manipulate the // DOM prior to when the document's readyState suggests it is safe to do so. if (self !== self.top) { stateChangeListener = function() { if (doc.readyState == 'complete') { GLOBAL_ENV.remove(doc, EVENT_NAME, stateChangeListener); GLOBAL_ENV.ieready(); } }; GLOBAL_ENV.add(doc, EVENT_NAME, stateChangeListener); } else { GLOBAL_ENV._dri = setInterval(function() { try { docElement.doScroll('left'); clearInterval(GLOBAL_ENV._dri); GLOBAL_ENV._dri = null; GLOBAL_ENV._ieready(); } catch (domNotReady) { } }, pollInterval); } } })(); YUI.add('event-base-ie', function (Y, NAME) { /* * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ function IEEventFacade() { // IEEventFacade.superclass.constructor.apply(this, arguments); Y.DOM2EventFacade.apply(this, arguments); } /* * (intentially left out of API docs) * Alternate Facade implementation that is based on Object.defineProperty, which * is partially supported in IE8. Properties that involve setup work are * deferred to temporary getters using the static _define method. */ function IELazyFacade(e) { var proxy = Y.config.doc.createEventObject(e), proto = IELazyFacade.prototype; // TODO: necessary? proxy.hasOwnProperty = function () { return true; }; proxy.init = proto.init; proxy.halt = proto.halt; proxy.preventDefault = proto.preventDefault; proxy.stopPropagation = proto.stopPropagation; proxy.stopImmediatePropagation = proto.stopImmediatePropagation; Y.DOM2EventFacade.apply(proxy, arguments); return proxy; } var imp = Y.config.doc && Y.config.doc.implementation, useLazyFacade = Y.config.lazyEventFacade, buttonMap = { 0: 1, // left click 4: 2, // middle click 2: 3 // right click }, relatedTargetMap = { mouseout: 'toElement', mouseover: 'fromElement' }, resolve = Y.DOM2EventFacade.resolve, proto = { init: function() { IEEventFacade.superclass.init.apply(this, arguments); var e = this._event, x, y, d, b, de, t; this.target = resolve(e.srcElement); if (('clientX' in e) && (!x) && (0 !== x)) { x = e.clientX; y = e.clientY; d = Y.config.doc; b = d.body; de = d.documentElement; x += (de.scrollLeft || (b && b.scrollLeft) || 0); y += (de.scrollTop || (b && b.scrollTop) || 0); this.pageX = x; this.pageY = y; } if (e.type == "mouseout") { t = e.toElement; } else if (e.type == "mouseover") { t = e.fromElement; } // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. this.relatedTarget = resolve(t || e.relatedTarget); // which should contain the unicode key code if this is a key event. // For click events, which is normalized for which mouse button was // clicked. this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; }, stopPropagation: function() { this._event.cancelBubble = true; this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { this.stopPropagation(); this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { this._event.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; } }; Y.extend(IEEventFacade, Y.DOM2EventFacade, proto); Y.extend(IELazyFacade, Y.DOM2EventFacade, proto); IELazyFacade.prototype.init = function () { var e = this._event, overrides = this._wrapper.overrides, define = IELazyFacade._define, lazyProperties = IELazyFacade._lazyProperties, prop; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.keyCode = // chained assignment this.charCode = e.keyCode; this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; for (prop in lazyProperties) { if (lazyProperties.hasOwnProperty(prop)) { define(this, prop, lazyProperties[prop]); } } if (this._touch) { this._touch(e, this._currentTarget, this._wrapper); } }; IELazyFacade._lazyProperties = { target: function () { return resolve(this._event.srcElement); }, relatedTarget: function () { var e = this._event, targetProp = relatedTargetMap[e.type] || 'relatedTarget'; // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. return resolve(e[targetProp] || e.relatedTarget); }, currentTarget: function () { return resolve(this._currentTarget); }, wheelDelta: function () { var e = this._event; if (e.type === "mousewheel" || e.type === "DOMMouseScroll") { return (e.detail) ? (e.detail * -1) : // wheelDelta between -80 and 80 result in -1 or 1 Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } }, pageX: function () { var e = this._event, val = e.pageX, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollLeft; docScroll = doc.documentElement.scrollLeft; val = e.clientX + (docScroll || bodyScroll || 0); } return val; }, pageY: function () { var e = this._event, val = e.pageY, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollTop; docScroll = doc.documentElement.scrollTop; val = e.clientY + (docScroll || bodyScroll || 0); } return val; } }; /** * Wrapper function for Object.defineProperty that creates a property whose * value will be calulated only when asked for. After calculating the value, * the getter wll be removed, so it will behave as a normal property beyond that * point. A setter is also assigned so assigning to the property will clear * the getter, so foo.prop = 'a'; foo.prop; won't trigger the getter, * overwriting value 'a'. * * Used only by the DOMEventFacades used by IE8 when the YUI configuration * <code>lazyEventFacade</code> is set to true. * * @method _define * @param o {DOMObject} A DOM object to add the property to * @param prop {String} The name of the new property * @param valueFn {Function} The function that will return the initial, default * value for the property. * @static * @private */ IELazyFacade._define = function (o, prop, valueFn) { function val(v) { var ret = (arguments.length) ? v : valueFn.call(this); delete o[prop]; Object.defineProperty(o, prop, { value: ret, configurable: true, writable: true }); return ret; } Object.defineProperty(o, prop, { get: val, set: val, configurable: true }); }; if (imp && (!imp.hasFeature('Events', '2.0'))) { if (useLazyFacade) { // Make sure we can use the lazy facade logic try { Object.defineProperty(Y.config.doc.createEventObject(), 'z', {}); } catch (e) { useLazyFacade = false; } } Y.DOMEventFacade = (useLazyFacade) ? IELazyFacade : IEEventFacade; } }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('pluginhost-base', function (Y, NAME) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config if (this[ns].setAttrs) { this[ns].setAttrs(config); } } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namespace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { if (this[ns].destroy) { this[ns].destroy(); } delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('pluginhost-config', function (Y, NAME) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin * @for Plugin.Host */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes * @for Plugin.Host */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@', {"requires": ["pluginhost-base"]}); YUI.add('event-delegate', function (Y, NAME) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Regex to test for disabled elements during filtering. This is only relevant to IE to normalize behavior with other browsers, which swallow events that occur to disabled elements. IE fires the event from the parent element instead of the original target, though it does preserve `event.srcElement` as the disabled element. IE also supports disabled on `<a>`, but the event still bubbles, so it acts more like `e.preventDefault()` plus styling. That issue is not handled here because other browsers fire the event on the `<a>`, so delegate is supported in both cases. @property _disabledRE @type {RegExp} @protected @since 3.8.1 **/ delegate._disabledRE = /^(?:button|input|select|textarea)$/i; /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // For IE. IE propagates events from the parent element of disabled // elements, where other browsers swallow the event entirely. To normalize // this in IE, filtering for matching elements should abort if the target // is a disabled form control. if (target.disabled && delegate._disabledRE.test(target.nodeName)) { return match; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('node-event-delegate', function (Y, NAME) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@', {"requires": ["node-base", "event-delegate"]}); YUI.add('node-pluginhost', function (Y, NAME) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) /** * Adds a plugin to each node in the NodeList. * This will instantiate the plugin and attach it to the configured namespace on each node * @method plug * @for NodeList * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @chainable */ Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); return this; }; /** * Removes a plugin from all nodes in the NodeList. This will destroy the * plugin instance and delete the namespace each node. * @method unplug * @for NodeList * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @chainable */ Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); return this; }; }, '@VERSION@', {"requires": ["node-base", "pluginhost"]}); YUI.add('node-screen', function (Y, NAME) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config docWidth * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Node | HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@', {"requires": ["dom-screen", "node-base"]}); YUI.add('node-style', function (Y, NAME) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); }, '@VERSION@', {"requires": ["dom-style", "node-base"]}); YUI.add('querystring-stringify-simple', function (Y, NAME) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('io-base', function (Y, NAME) { /** Base IO functionality. Provides basic XHR transport support. @module io @submodule io-base @for IO **/ var // List of events that comprise the IO event lifecycle. EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'], // Whitelist of used XHR response object properties. XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'], win = Y.config.win, uid = 0; /** The IO class is a utility that brokers HTTP requests through a simplified interface. Specifically, it allows JavaScript to make HTTP requests to a resource without a page reload. The underlying transport for making same-domain requests is the XMLHttpRequest object. IO can also use Flash, if specified as a transport, for cross-domain requests. @class IO @constructor @param {Object} config Object of EventTarget's publish method configurations used to configure IO's events. **/ function IO (config) { var io = this; io._uid = 'io:' + uid++; io._init(config); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * A counter that increments for each transaction. * * @property _id * @private * @type {Number} */ _id: 0, /** * Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type {Object} */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * Object that stores timeout values for any transaction with a defined * "timeout" configuration property. * * @property _timeout * @private * @type {Object} */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(config) { var io = this, i, len; io.cfg = config || {}; Y.augment(io, Y.EventTarget); for (i = 0, len = EVENTS.length; i < len; ++i) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + EVENTS[i], config); } }, /** * Method that creates a unique transaction object for each request. * * @method _create * @private * @param {Object} cfg Configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {Number} id Transaction id * @return {Object} The transaction object */ _create: function(config, id) { var io = this, transaction = { id : Y.Lang.isNumber(id) ? id : io._id++, uid: io._uid }, alt = config.xdr ? config.xdr.use : null, form = config.form && config.form.upload ? 'iframe' : null, use; if (alt === 'native') { // Non-IE and IE >= 10 can use XHR level 2 and not rely on an // external transport. alt = Y.UA.ie && !SUPPORTS_CORS ? 'xdr' : null; // Prevent "pre-flight" OPTIONS request by removing the // `X-Requested-With` HTTP header from CORS requests. This header // can be added back on a per-request basis, if desired. io.setHeader('X-Requested-With'); } use = alt || form; transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) : Y.merge(Y.IO.defaultTransport(), transaction); if (transaction.notify) { config.notify = function (e, t, c) { io.notify(e, t, c); }; } if (!use) { if (win && win.FormData && config.data instanceof win.FormData) { transaction.c.upload.onprogress = function (e) { io.progress(transaction, e, config); }; transaction.c.onload = function (e) { io.load(transaction, e, config); }; transaction.c.onerror = function (e) { io.error(transaction, e, config); }; transaction.upload = true; } } return transaction; }, _destroy: function(transaction) { if (win && !transaction.notify && !transaction.xdr) { if (XHR && !transaction.upload) { transaction.c.onreadystatechange = null; } else if (transaction.upload) { transaction.c.upload.onprogress = null; transaction.c.onload = null; transaction.c.onerror = null; } else if (Y.UA.ie && !transaction.e) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". transaction.c.abort(); } } transaction = transaction.c = null; }, /** * Method for creating and firing events. * * @method _evt * @private * @param {String} eventName Event to be published. * @param {Object} transaction Transaction object. * @param {Object} config Configuration data subset for event subscription. */ _evt: function(eventName, transaction, config) { var io = this, params, args = config['arguments'], emitFacade = io.cfg.emitFacade, globalEvent = "io:" + eventName, trnEvent = "io-trn:" + eventName; // Workaround for #2532107 this.detach(trnEvent); if (transaction.e) { transaction.c = { status: 0, statusText: transaction.e }; } // Fire event with parameters or an Event Facade. params = [ emitFacade ? { id: transaction.id, data: transaction.c, cfg: config, 'arguments': args } : transaction.id ]; if (!emitFacade) { if (eventName === EVENTS[0] || eventName === EVENTS[2]) { if (args) { params.push(args); } } else { if (transaction.evt) { params.push(transaction.evt); } else { params.push(transaction.c); } if (args) { params.push(args); } } } params.unshift(globalEvent); // Fire global events. io.fire.apply(io, params); // Fire transaction events, if receivers are defined. if (config.on) { params[0] = trnEvent; io.once(trnEvent, config.on[eventName], config.context || Y); io.fire.apply(io, params); } }, /** * Fires event "io:start" and creates, fires a transaction-specific * start event, if `config.on.start` is defined. * * @method start * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ start: function(transaction, config) { /** * Signals the start of an IO request. * @event io:start */ this._evt(EVENTS[0], transaction, config); }, /** * Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ complete: function(transaction, config) { /** * Signals the completion of the request-response phase of a * transaction. Response status and data are accessible, if * available, in this event. * @event io:complete */ this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:end" and creates, fires a transaction-specific "end" * event, if config.on.end is defined. * * @method end * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ end: function(transaction, config) { /** * Signals the end of the transaction lifecycle. * @event io:end */ this._evt(EVENTS[2], transaction, config); this._destroy(transaction); }, /** * Fires event "io:success" and creates, fires a transaction-specific * "success" event, if config.on.success is defined. * * @method success * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ success: function(transaction, config) { /** * Signals an HTTP response with status in the 2xx range. * Fires after io:complete. * @event io:success */ this._evt(EVENTS[3], transaction, config); this.end(transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event, if config.on.failure is defined. * * @method failure * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ failure: function(transaction, config) { /** * Signals an HTTP response with status outside of the 2xx range. * Fires after io:complete. * @event io:failure */ this._evt(EVENTS[4], transaction, config); this.end(transaction, config); }, /** * Fires event "io:progress" and creates, fires a transaction-specific * "progress" event -- for XMLHttpRequest file upload -- if * config.on.progress is defined. * * @method progress * @param {Object} transaction Transaction object. * @param {Object} progress event. * @param {Object} config Configuration object for the transaction. */ progress: function(transaction, e, config) { /** * Signals the interactive state during a file upload transaction. * This event fires after io:start and before io:complete. * @event io:progress */ transaction.evt = e; this._evt(EVENTS[5], transaction, config); }, /** * Fires event "io:complete" and creates, fires a transaction-specific * "complete" event -- for XMLHttpRequest file upload -- if * config.on.complete is defined. * * @method load * @param {Object} transaction Transaction object. * @param {Object} load event. * @param {Object} config Configuration object for the transaction. */ load: function (transaction, e, config) { transaction.evt = e.target; this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event -- for XMLHttpRequest file upload -- if * config.on.failure is defined. * * @method error * @param {Object} transaction Transaction object. * @param {Object} error event. * @param {Object} config Configuration object for the transaction. */ error: function (transaction, e, config) { transaction.evt = e; this._evt(EVENTS[4], transaction, config); }, /** * Retry an XDR transaction, using the Flash tranport, if the native * transport fails. * * @method _retry * @private * @param {Object} transaction Transaction object. * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. */ _retry: function(transaction, uri, config) { this._destroy(transaction); config.xdr.use = 'flash'; return this.send(uri, config, transaction.id); }, /** * Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {String} uri URI or root data. * @param {String} data Data to be concatenated onto URI. * @return {String} */ _concat: function(uri, data) { uri += (uri.indexOf('?') === -1 ? '?' : '&') + data; return uri; }, /** * Stores default client headers for all transactions. If a label is * passed with no value argument, the header will be deleted. * * @method setHeader * @param {String} name HTTP header * @param {String} value HTTP header value */ setHeader: function(name, value) { if (value) { this._headers[name] = value; } else { delete this._headers[name]; } }, /** * Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {Object} transaction - XHR instance for the specific transaction. * @param {Object} headers - HTTP headers for the specific transaction, as * defined in the configuration object passed to YUI.io(). */ _setHeaders: function(transaction, headers) { headers = Y.merge(this._headers, headers); Y.Object.each(headers, function(value, name) { if (value !== 'disable') { transaction.setRequestHeader(name, headers[name]); } }); }, /** * Starts timeout count if the configuration object has a defined * timeout property. * * @method _startTimeout * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} timeout Timeout in milliseconds. */ _startTimeout: function(transaction, timeout) { var io = this; io._timeout[transaction.id] = setTimeout(function() { io._abort(transaction, 'timeout'); }, timeout); }, /** * Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {Number} id - Transaction id. */ _clearTimeout: function(id) { clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * Method that determines if a transaction response qualifies as success * or failure, based on the response HTTP status code, and fires the * appropriate success or failure events. * * @method _result * @private * @static * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to io(). */ _result: function(transaction, config) { var status; // Firefox will throw an exception if attempting to access // an XHR object's status property, after a request is aborted. try { status = transaction.c.status; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 304 || status === 1223) { this.success(transaction, config); } else { this.failure(transaction, config); } }, /** * Event handler bound to onreadystatechange. * * @method _rS * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to YUI.io(). */ _rS: function(transaction, config) { var io = this; if (transaction.c.readyState === 4) { if (config.timeout) { io._clearTimeout(transaction.id); } // Yield in the event of request timeout or abort. setTimeout(function() { io.complete(transaction, config); io._result(transaction, config); }, 0); } }, /** * Terminates a transaction due to an explicit abort or timeout. * * @method _abort * @private * @param {Object} transaction Transaction object generated by _create(). * @param {String} type Identifies timed out or aborted transaction. */ _abort: function(transaction, type) { if (transaction && transaction.c) { transaction.e = type; transaction.c.abort(); } }, /** * Requests a transaction. `send()` is implemented as `Y.io()`. Each * transaction may include a configuration object. Its properties are: * * <dl> * <dt>method</dt> * <dd>HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET.</dd> * * <dt>data</dt> * <dd>This is the name-value string that will be sent as the * transaction data. If the request is HTTP GET, the data become * part of querystring. If HTTP POST, the data are sent in the * message body.</dd> * * <dt>xdr</dt> * <dd>Defines the transport to be used for cross-domain requests. * By setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. The properties of the * transport object are: * <dl> * <dt>use</dt> * <dd>The transport to be used: 'flash' or 'native'</dd> * <dt>dataType</dt> * <dd>Set the value to 'XML' if that is the expected response * content type.</dd> * </dl></dd> * * <dt>form</dt> * <dd>Form serialization configuration object. Its properties are: * <dl> * <dt>id</dt> * <dd>Node object or id of HTML form</dd> * <dt>useDisabled</dt> * <dd>`true` to also serialize disabled form field values * (defaults to `false`)</dd> * </dl></dd> * * <dt>on</dt> * <dd>Assigns transaction event subscriptions. Available events are: * <dl> * <dt>start</dt> * <dd>Fires when a request is sent to a resource.</dd> * <dt>complete</dt> * <dd>Fires when the transaction is complete.</dd> * <dt>success</dt> * <dd>Fires when the HTTP response status is within the 2xx * range.</dd> * <dt>failure</dt> * <dd>Fires when the HTTP response status is outside the 2xx * range, if an exception occurs, if the transation is aborted, * or if the transaction exceeds a configured `timeout`.</dd> * <dt>end</dt> * <dd>Fires at the conclusion of the transaction * lifecycle, after `success` or `failure`.</dd> * </dl> * * <p>Callback functions for `start` and `end` receive the id of the * transaction as a first argument. For `complete`, `success`, and * `failure`, callbacks receive the id and the response object * (usually the XMLHttpRequest instance). If the `arguments` * property was included in the configuration object passed to * `Y.io()`, the configured data will be passed to all callbacks as * the last argument.</p> * </dd> * * <dt>sync</dt> * <dd>Pass `true` to make a same-domain transaction synchronous. * <strong>CAVEAT</strong>: This will negatively impact the user * experience. Have a <em>very</em> good reason if you intend to use * this.</dd> * * <dt>context</dt> * <dd>The "`this'" object for all configured event handlers. If a * specific context is needed for individual callbacks, bind the * callback to a context using `Y.bind()`.</dd> * * <dt>headers</dt> * <dd>Object map of transaction headers to send to the server. The * object keys are the header names and the values are the header * values.</dd> * * <dt>timeout</dt> * <dd>Millisecond threshold for the transaction before being * automatically aborted.</dd> * * <dt>arguments</dt> * <dd>User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" and * "end" event handlers. It is the third argument in the "complete", * "success", and "failure" event handlers. <strong>Be sure to quote * this property name in the transaction configuration as * "arguments" is a reserved word in JavaScript</strong> (e.g. * `Y.io({ ..., "arguments": stuff })`).</dd> * </dl> * * @method send * @public * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. * @param {Number} id Transaction id, if already set. * @return {Object} */ send: function(uri, config, id) { var transaction, method, i, len, sync, data, io = this, u = uri, response = {}; config = config ? Y.Object(config) : {}; transaction = io._create(config, id); method = config.method ? config.method.toUpperCase() : 'GET'; sync = config.sync; data = config.data; // Serialize a map object into a key-value string using // querystring-stringify-simple. if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) { if (Y.QueryString && Y.QueryString.stringify) { config.data = data = Y.QueryString.stringify(data); } else { } } if (config.form) { if (config.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(transaction, uri, config); } else { // Serialize HTML form data into a key-value string. data = io._serialize(config.form, data); } } // Convert falsy values to an empty string. This way IE can't be // rediculous and translate `undefined` to "undefined". data || (data = ''); if (data) { switch (method) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, data); data = ''; break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers); break; } } if (transaction.xdr) { // Route data to io-xdr module for flash and XDomainRequest. return io.xdr(u, transaction, config); } else if (transaction.notify) { // Route data to custom transport return transaction.c.send(transaction, uri, config); } if (!sync && !transaction.upload) { transaction.c.onreadystatechange = function() { io._rS(transaction, config); }; } try { // Determine if request is to be set as // synchronous or asynchronous. transaction.c.open(method, u, !sync, config.username || null, config.password || null); io._setHeaders(transaction.c, config.headers || {}); io.start(transaction, config); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (config.xdr && config.xdr.credentials && SUPPORTS_CORS) { transaction.c.withCredentials = true; } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. transaction.c.send(data); if (sync) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. for (i = 0, len = XHR_PROPS.length; i < len; ++i) { response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]]; } response.getAllResponseHeaders = function() { return transaction.c.getAllResponseHeaders(); }; response.getResponseHeader = function(name) { return transaction.c.getResponseHeader(name); }; io.complete(transaction, config); io._result(transaction, config); return response; } } catch(e) { if (transaction.xdr) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(transaction, uri, config); } else { io.complete(transaction, config); io._result(transaction, config); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (config.timeout) { io._startTimeout(transaction, config.timeout); } return { id: transaction.id, abort: function() { return transaction.c ? io._abort(transaction, 'abort') : false; }, isInProgress: function() { return transaction.c ? (transaction.c.readyState % 4) : false; }, io: io }; } }; /** Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties: <dl> <dt>method</dt> <dd>HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.</dd> <dt>data</dt> <dd>This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.</dd> <dt>xdr</dt> <dd>Defines the transport to be used for cross-domain requests. By setting this property, the transaction will use the specified transport instead of XMLHttpRequest. The properties of the transport object are: <dl> <dt>use</dt> <dd>The transport to be used: 'flash' or 'native'</dd> <dt>dataType</dt> <dd>Set the value to 'XML' if that is the expected response content type.</dd> </dl></dd> <dt>form</dt> <dd>Form serialization configuration object. Its properties are: <dl> <dt>id</dt> <dd>Node object or id of HTML form</dd> <dt>useDisabled</dt> <dd>`true` to also serialize disabled form field values (defaults to `false`)</dd> </dl></dd> <dt>on</dt> <dd>Assigns transaction event subscriptions. Available events are: <dl> <dt>start</dt> <dd>Fires when a request is sent to a resource.</dd> <dt>complete</dt> <dd>Fires when the transaction is complete.</dd> <dt>success</dt> <dd>Fires when the HTTP response status is within the 2xx range.</dd> <dt>failure</dt> <dd>Fires when the HTTP response status is outside the 2xx range, if an exception occurs, if the transation is aborted, or if the transaction exceeds a configured `timeout`.</dd> <dt>end</dt> <dd>Fires at the conclusion of the transaction lifecycle, after `success` or `failure`.</dd> </dl> <p>Callback functions for `start` and `end` receive the id of the transaction as a first argument. For `complete`, `success`, and `failure`, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If the `arguments` property was included in the configuration object passed to `Y.io()`, the configured data will be passed to all callbacks as the last argument.</p> </dd> <dt>sync</dt> <dd>Pass `true` to make a same-domain transaction synchronous. <strong>CAVEAT</strong>: This will negatively impact the user experience. Have a <em>very</em> good reason if you intend to use this.</dd> <dt>context</dt> <dd>The "`this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using `Y.bind()`.</dd> <dt>headers</dt> <dd>Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.</dd> <dt>timeout</dt> <dd>Millisecond threshold for the transaction before being automatically aborted.</dd> <dt>arguments</dt> <dd>User-defined data passed to all registered event handlers. This value is available as the second argument in the "start" and "end" event handlers. It is the third argument in the "complete", "success", and "failure" event handlers. <strong>Be sure to quote this property name in the transaction configuration as "arguments" is a reserved word in JavaScript</strong> (e.g. `Y.io({ ..., "arguments": stuff })`).</dd> </dl> @method io @static @param {String} url qualified path to transaction resource. @param {Object} config configuration object for the transaction. @return {Object} @for YUI **/ Y.io = function(url, config) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); return transaction.send.apply(transaction, [url, config]); }; /** Method for setting and deleting IO HTTP headers to be sent with every request. Hosted as a property on the `io` function (e.g. `Y.io.header`). @method header @param {String} name HTTP header @param {String} value HTTP header value @static **/ Y.io.header = function(name, value) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); transaction.setHeader(name, value); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; var XHR = win && win.XMLHttpRequest, XDR = win && win.XDomainRequest, AX = win && win.ActiveXObject, // Checks for the presence of the `withCredentials` in an XHR instance // object, which will be present if the environment supports CORS. SUPPORTS_CORS = XHR && 'withCredentials' in (new XMLHttpRequest()); Y.mix(Y.IO, { /** * The ID of the default IO transport, defaults to `xhr` * @property _default * @type {String} * @static */ _default: 'xhr', /** * * @method defaultTransport * @static * @param {String} [id] The transport to set as the default, if empty a new transport is created. * @return {Object} The transport object with a `send` method */ defaultTransport: function(id) { if (id) { Y.IO._default = id; } else { var o = { c: Y.IO.transports[Y.IO._default](), notify: Y.IO._default === 'xhr' ? false : true }; return o; } }, /** * An object hash of custom transports available to IO * @property transports * @type {Object} * @static */ transports: { xhr: function () { return XHR ? new XMLHttpRequest() : AX ? new ActiveXObject('Microsoft.XMLHTTP') : null; }, xdr: function () { return XDR ? new XDomainRequest() : null; }, iframe: function () { return {}; }, flash: null, nodejs: null }, /** * Create a custom transport of type and return it's object * @method customTransport * @param {String} id The id of the transport to create. * @static */ customTransport: function(id) { var o = { c: Y.IO.transports[id]() }; o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true; return o; } }); Y.mix(Y.IO.prototype, { /** * Fired from the notify method of the transport which in turn fires * the event on the IO object. * @method notify * @param {String} event The name of the event * @param {Object} transaction The transaction object * @param {Object} config The configuration object for this transaction */ notify: function(event, transaction, config) { var io = this; switch (event) { case 'timeout': case 'abort': case 'transport error': transaction.c = { status: 0, statusText: event }; event = 'failure'; default: io[event].apply(io, [transaction, config]); } } }); }, '@VERSION@', {"requires": ["event-custom-base", "querystring-stringify-simple"]}); YUI.add('json-parse', function (Y, NAME) { var _JSON = Y.config.global.JSON; Y.namespace('JSON').parse = function (obj, reviver, space) { return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition', function (Y, NAME) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', DOCUMENT_STYLE = DOCUMENT[DOCUMENT_ELEMENT].style, TRANSITION_CAMEL = 'transition', TRANSITION_PROPERTY_CAMEL = 'transitionProperty', TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; // One off handling of transform-prefixing. Transition._TRANSFORM = 'transform'; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; // Map transition properties to vendor-specific versions. if ('transition' in DOCUMENT_STYLE && 'transitionProperty' in DOCUMENT_STYLE && 'transitionDuration' in DOCUMENT_STYLE && 'transitionTimingFunction' in DOCUMENT_STYLE && 'transitionDelay' in DOCUMENT_STYLE) { Transition.useNative = true; Transition.supported = true; // TODO: remove } else { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transition'; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); } // Map transform property to vendor-specific versions. // One-off required for cssText injection. if (typeof DOCUMENT_STYLE.transform === 'undefined') { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transform'; if (typeof DOCUMENT_STYLE[property] !== 'undefined') { Transition._TRANSFORM = property; } }); } if (CAMEL_VENDOR_PREFIX) { TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + 'Transition'; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; } TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration !== 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay !== 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[Transition._TRANSFORM]) { config[Transition._TRANSFORM] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur) * 1000; return dur + 'ms'; }, _runNative: function() { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = node.ownerDocument.defaultView.getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } style.cssText += transitionText + duration + easing + delay + cssText; }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; name = Transition._toHyphen(name); if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style } } }, destroy: function() { var anim = this, node = anim._node; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } return this; }; Y.NodeList.prototype.show = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).show(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback && typeof callback === 'function') { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else { this._hide(); } return this; }; Y.NodeList.prototype.hide = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).hide(name, config, callback); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name !== 'string') { // no transition, just toggle on = name; this._toggleView(on, callback); // call original _toggleView in Y.Node return; } if (typeof on === 'function') { // Ignore "on" if used for callback argument. on = undefined; } if (typeof on === 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { node = Y.one(node); node.toggleView.apply(node, arguments); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); }, '@VERSION@', {"requires": ["node-style"]}); YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('selector-css3', function (Y, NAME) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.DOM._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.DOM._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.DOM._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.DOM._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@', {"requires": ["selector-native", "selector-css2"]}); YUI.add('yui-log', function (Y, NAME) { /** * 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 src = src || ""; if (typeof src !== "undefined") { 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('dump', function (Y, NAME) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition-timer', function (Y, NAME) { /** * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@', {"requires": ["transition"]}); YUI.add('yui', function (Y, NAME) { // empty }, '@VERSION@', { "use": [ "yui", "oop", "dom", "event-custom-base", "event-base", "pluginhost", "node", "event-delegate", "io-base", "json-parse", "transition", "selector-css3", "dom-style-ie", "querystring-stringify-simple" ] }); var Y = YUI().use('*');
node_modules/react-icons/ti/spanner.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const TiSpanner = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m33.8 11.9c-0.1-0.3-0.3-0.5-0.6-0.6-0.3-0.1-0.6 0-0.8 0.2l-4.3 4.3-3.2-0.7-0.7-3.2 4.4-4.3c0.3-0.2 0.3-0.5 0.3-0.7s-0.3-0.6-0.6-0.7c-0.9-0.2-1.7-0.4-2.5-0.4-4.6 0-8.3 3.8-8.3 8.4 0 0.5 0.1 1.1 0.2 1.7-0.9 0.7-1.8 1.4-2.8 2.1-1.5 1.1-3.1 2.3-5.3 4.2-1.3 1.2-2.1 2.8-2.1 4.5 0 3.2 2.6 5.8 5.8 5.8 1.7 0 3.4-0.8 4.5-2.1 1.9-2.2 3.1-3.9 4.2-5.3 0.7-1 1.4-1.9 2.1-2.8 0.6 0.1 1.2 0.2 1.7 0.2 4.6 0 8.4-3.7 8.4-8.3 0-0.8-0.1-1.5-0.4-2.3z m-20.5 16.4c-0.9 0-1.6-0.7-1.6-1.6s0.7-1.7 1.6-1.7 1.7 0.7 1.7 1.7-0.7 1.6-1.7 1.6z"/></g> </Icon> ) export default TiSpanner