text
stringlengths
2
1.05M
import React, {useState, useEffect} from 'react'; import firebaseApp from './Firebase'; export const AuthContext = React.createContext(); export const AuthProvider = ({children}) => { const [currentUser, setCurrentUser] = useState(null); const [loadingUser, setLoadingUser] = useState(true); useEffect(() => { firebaseApp.auth().onAuthStateChanged((user) => { setCurrentUser(user); setLoadingUser(false); }); }, []); if (loadingUser) { return ( <div> <h1>Loading....Loading....Loading....Loading....Loading....</h1> </div> ); } return ( <AuthContext.Provider value={{currentUser}}> {children} </AuthContext.Provider> ); };
/** * @typedef {AnimationJob} DisplacementRadiateJob */ /** * This module defines a constructor for DisplacementRadiateJob objects. * * @module DisplacementRadiateJob */ (function () { // ------------------------------------------------------------------------------------------- // // Private static variables var config = {}; config.duration = 500; config.waveSpeed = 3; // pixels / millisecond config.waveWidth = 500; config.displacementDistance = 50; config.isRecurring = false; config.avgDelay = 4000; config.delayDeviationRange = 3800; // --- Dependent parameters --- // config.computeDependentValues = function () { // TODO: }; config.computeDependentValues(); // ------------------------------------------------------------------------------------------- // // Private dynamic functions /** * Calculates and stores the maximal displacement values for all tiles. * * @this DisplacementRadiateJob */ function initializeDisplacements() { // TODO: // var job, i, iCount, j, jCount, k, tiles, displacementRatio; // // job = this; // // displacementRatio = // (window.hg.Grid.config.tileShortLengthWithGap + window.hg.Grid.config.tileGap) / // (window.hg.Grid.config.tileShortLengthWithGap); // // job.displacements = []; // // k = 0; // // if (job.grid.isPostOpen) { // // Consider all of the old AND new tiles // for (i = 0, iCount = job.grid.sectors.length; i < iCount; i += 1) { // tiles = job.grid.sectors[i].tiles; // // for (j = 0, jCount = tiles.length; j < jCount; j += 1) { // job.displacements[k] = { // tile: tiles[j], // displacementX: displacementRatio * // (tiles[j].originalAnchorX - job.tile.originalAnchorX), // displacementY: displacementRatio * // (tiles[j].originalAnchorY - job.tile.originalAnchorY) // }; // k += 1; // } // } // } else { // for (i = 0, iCount = job.grid.originalTiles.length; i < iCount; i += 1) { // job.displacements[i] = { // tile: job.grid.originalTiles[i], // displacementX: displacementRatio * // (job.grid.originalTiles[i].originalAnchorX - job.tile.originalAnchorX), // displacementY: displacementRatio * // (job.grid.originalTiles[i].originalAnchorY - job.tile.originalAnchorY) // }; // } // } } /** * @this DisplacementRadiateJob */ function handleComplete(wasCancelled) { var job = this; console.log('DisplacementRadiateJob ' + (wasCancelled ? 'cancelled' : 'completed')); job.isComplete = true; job.onComplete(); } // ------------------------------------------------------------------------------------------- // // Private static functions // ------------------------------------------------------------------------------------------- // // Public dynamic functions /** * Sets this DisplacementRadiateJob as started. * * @this DisplacementRadiateJob * @param {Number} startTime */ function start(startTime) { var job = this; job.startTime = startTime; job.isComplete = false; } /** * Updates the animation progress of this DisplacementRadiateJob to match the given time. * * This should be called from the overall animation loop. * * @this DisplacementRadiateJob * @param {Number} currentTime * @param {Number} deltaTime */ function update(currentTime, deltaTime) { // TODO: // var job, progress, i, count; // // job = this; // // if (currentTime > job.startTime + config.duration) { // handleComplete.call(job, false); // } else { // // Ease-out halfway, then ease-in back // progress = (currentTime - job.startTime) / config.duration; // progress = (progress > 0.5 ? 1 - progress : progress) * 2; // progress = window.hg.util.easingFunctions.easeOutQuint(progress); // // // Displace the tiles // for (i = 0, count = job.displacements.length; i < count; i += 1) { // job.displacements[i].tile.anchorX += job.displacements[i].displacementX * progress; // job.displacements[i].tile.anchorY += job.displacements[i].displacementY * progress; // } // } } /** * Draws the current state of this DisplacementRadiateJob. * * This should be called from the overall animation loop. * * @this DisplacementRadiateJob */ function draw() { // This animation job updates the state of actual tiles, so it has nothing of its own to draw } /** * Stops this DisplacementRadiateJob, and returns the element its original form. * * @this DisplacementRadiateJob */ function cancel() { var job = this; handleComplete.call(job, true); } /** * @this DisplacementRadiateJob */ function init() { var job = this; config.computeDependentValues(); // TODO: } // ------------------------------------------------------------------------------------------- // // Expose this module's constructor /** * @constructor * @global * @param {Grid} grid * @param {Tile} tile * @param {Function} onComplete */ function DisplacementRadiateJob(grid, tile, onComplete) { var job = this; job.grid = grid; job.tile = tile; job.startTime = 0; job.isComplete = true; job.displacements = null; job.start = start; job.update = update; job.draw = draw; job.cancel = cancel; job.onComplete = onComplete; job.init = init; initializeDisplacements.call(job); console.log('DisplacementRadiateJob created: tileIndex=' + job.tile.originalIndex); } DisplacementRadiateJob.config = config; // Expose this module window.hg = window.hg || {}; window.hg.DisplacementRadiateJob = DisplacementRadiateJob; console.log('DisplacementRadiateJob module loaded'); })();
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link, navigate, StaticQuery, graphql } from 'gatsby'; import Helmet from 'react-helmet'; import Swipeable from 'react-swipeable'; import Transition from '../components/transition'; import './index.css'; const Header = ({ name, title, date }) => ( <header> <Link to="/1"> <span>{name}</span> / {title} </Link> <time>{date}</time> </header> ); class TemplateWrapper extends Component { NEXT = [13, 39]; PREV = 37; swipeLeft = () => { this.navigate({ keyCode: this.NEXT[0] }); }; swipeRight = () => { this.navigate({ keyCode: this.PREV }); }; navigate = ({ keyCode }) => { const now = this.props.data.slide.index; const slidesLength = this.props.slidesLength; if (now) { if (keyCode === this.PREV && now === 1) { return false; } else if (this.NEXT.indexOf(keyCode) !== -1 && now === slidesLength) { return false; } else if (this.NEXT.indexOf(keyCode) !== -1) { navigate(`/${now + 1}`); } else if (keyCode === this.PREV) { navigate(`/${now - 1}`); } } }; componentDidMount() { document.addEventListener('keydown', this.navigate); } componentWillUnmount() { document.removeEventListener('keydown', this.navigate); } render() { const { location, children, site } = this.props; return ( <div> <Helmet title={`${site.siteMetadata.title} / ${site.siteMetadata.name}`} /> <Header name={site.siteMetadata.name} title={site.siteMetadata.title} date={site.siteMetadata.date} /> <Swipeable onSwipedLeft={this.swipeLeft} onSwipedRight={this.swipeRight} > <Transition location={location}> <div id="slide">{children}</div> </Transition> </Swipeable> </div> ); } } TemplateWrapper.propTypes = { children: PropTypes.node, data: PropTypes.object, }; export default props => ( <StaticQuery query={graphql` query IndexQuery { site { siteMetadata { name title date } } allSlide { edges { node { id } } } } `} render={data => ( <TemplateWrapper site={data.site} slidesLength={data.allSlide.edges.length} {...props} /> )} /> );
'use strict'; const childProcess = require('child_process'); const CONFIG = require('../config'); // Recognised by '@electron/get', used by the 'electron-mksnapshot' and 'electron-chromedriver' dependencies process.env.ELECTRON_CUSTOM_VERSION = CONFIG.appMetadata.electronVersion; function installScriptDependencies(ci) { console.log('Installing script dependencies'); childProcess.execFileSync( CONFIG.getNpmBinPath(ci), ['--loglevel=error', ci ? 'ci' : 'install'], { env: process.env, cwd: CONFIG.scriptRootPath } ); } const { expose } = require(`${CONFIG.scriptRunnerModulesPath}/threads/worker`); expose(installScriptDependencies); module.exports = installScriptDependencies;
/** * @author Chong-U Lim <me@chongdashu.com> * @copyright 2015 Chong-U Lim * @module Game.Component */ this.chongdashu = this.chongdashu||{}; (function() { "use strict"; /** * SpriteComponent * @class Game.Component.SpriteComponent * @extends Core.Component * @constructor **/ var SpriteComponent = function(sprite) { // @param {Phaser.Keyboard} entity this.init(sprite); }; var p = createjs.extend(SpriteComponent, chongdashu.Component); /** * The type identifier of this component. * * @property Game.SpriteComponent.TYPE * @type String * @static * @final */ SpriteComponent.TYPE = "component:SpriteComponent"; p.sprite = null; p.init = function(sprite) { console.log("[SpriteComponent], init()"); this.Component_init(SpriteComponent.TYPE); this.sprite = sprite; this.sprite.anchor.set(0.5); }; // Link // ---- chongdashu.SpriteComponent = createjs.promote(SpriteComponent, "Component"); }());
Bw={}; Bw.getParameterValues = function(name) { var search = location.search; var values = []; if(search.length>0) { search = search.substring(1); var paramArr = search.split("&"); for(var i in params) { var pair = paramArr[i].split("="); var key = pair[0]; var value = pair[1]; if (key == name) { values[values.length] = value; } } } return values; }; Bw.getParameter = function(key) { var search = location.search; var values = []; if(search.length>0) { search = search.substring(1); var paramArr = search.split("&"); for(var i in params) { var pair = paramArr[i].split("="); var key = pair[0]; var value = pair[1]; if (key == name) { return value; } } } }; Bw.appendJsessionid = function(url,jsessionid) { if(!jsessionid) { jsessionid = $.cookie("JSESSIONID"); } if(url && jsessionid) { var index = url.indexOf("?"); if(index!=-1) { url = url.substring(0,index) + ";jsessionid="+jsessionid + url.substring(index); } else { url += ";jsessionid="+jsessionid; } } return url; }; Bw.imageDim = function(src, options) { if(src == undefined || src=="") { //$("#"+imgId).hide(); return; } if(!(options && options.cache)) { if(src.indexOf("?")==-1) { src += "?"; } else { src += "&"; } src += "d="+new Date()*1; } var img = $("<img>",{ "src":src }).css({ "display":"none", "background-color":"#fff", "border":"1px solid #ccc", "padding":"2px", "position":"absolute", "z-index":10000 }).appendTo(document.body).offset({left:-99999,top:-99999}).show(); img.load(function(){ var dim = {"width":img.width(),"height":img.height()}; if(options !== null && options !== undefined) { var maxWidth = options.maxWidth || Number.MAX_VALUE; var maxHeight = options.maxHeight || Number.MAX_VALUE; var to = options.to; var of = options.of; var scaleDim; if(dim.width>maxWidth||dim.height>maxHeight) { var widthScale = maxWidth/dim.width; var heightScale = maxHeight/dim.height; if(widthScale<heightScale) { scaleDim = {"width":maxWidth,"height":dim.height*widthScale}; } else { scaleDim = {"width":dim.width*heightScale,"height":maxHeight}; } } if(scaleDim != undefined) { img.css({"width":scaleDim.width,"height":scaleDim.heigth}); } if(to !== null && to !== undefined) { to = $(to); if(to.is("img")) { to.attr("src",src); if(scaleDim != undefined) { to.css({"width":scaleDim.width,"height":scaleDim.heigth}); } } } if(of !== null && of !== undefined) { img.positionSideOf(of); } } }); return img; }; (function($) { var position = function(preferred,self,selfWidth,selfHeight,topHeight,bottomHeight,leftWidth,rightWidth,topByTop,topByBottom,leftByLeft,leftByRight) { var top,left; if (bottomHeight - selfHeight < 0 && topHeight > bottomHeight) { top = topByTop; } else if(topHeight - selfHeight < 0 && bottomHeight > topHeight) { top = topByBottom; } else if(preferred[0]!='bottom') { top = topByTop; } else { top = topByBottom; } if (rightWidth - selfWidth < 0 && leftWidth > rightWidth) { left = leftByLeft; } else if(leftWidth - selfWidth < 0 && rightWidth > leftWidth) { left = leftByRight; } else if(preferred[1]!='right') { left = leftByLeft; } else { left = leftByRight; } self.offset({left:left,top:top}); if($.fn.bgiframe && !self.is("img")) { self.bgiframe(); } }; $.fn.positionSideOf = function(of, options) { var settings = { preferred : ['bottom','right'], spacing : 1 }; $.extend(settings, options); var ofOffset = of.offset(); var selfWidth = this.outerWidth(); var selfHeight = this.outerHeight(); var topHeight = ofOffset.top - $(document).scrollTop() + of.outerHeight(); var bottomHeight = $(document).scrollTop() + $(window).height() - ofOffset.top; var leftWidth = ofOffset.left - $(document).scrollLeft(); var rightWidth = $(document).scrollLeft() + $(window).width() - ofOffset.left - of.outerWidth(); var topByTop = ofOffset.top + of.outerHeight() - selfHeight; var topByBottom = ofOffset.top; var leftByLeft = ofOffset.left - selfWidth - settings.spacing; var leftByRight = ofOffset.left + of.outerWidth() + settings.spacing; position(settings.preferred,this,selfWidth,selfHeight,topHeight,bottomHeight,leftWidth,rightWidth,topByTop,topByBottom,leftByLeft,leftByRight); }; $.fn.positionOf = function(of, options) { var settings = { preferred : ['bottom','right'], spacing : 1 }; $.extend(settings, options); var ofOffset = of.offset(); var selfWidth = this.outerWidth(); var selfHeight = this.outerHeight(); var leftWidth = ofOffset.left - $(document).scrollLeft() + of.outerWidth(); var rightWidth = $(document).scrollLeft() + $(window).width() - ofOffset.left; var topHeight = ofOffset.top - $(document).scrollTop(); var bottomHeight = $(document).scrollTop() + $(window).height() - ofOffset.top - of.outerHeight(); var topByTop = ofOffset.top - selfHeight - settings.spacing; var topByBottom = ofOffset.top + of.outerHeight() + settings.spacing; var leftByRight = ofOffset.left; var leftByLeft = ofOffset.left + of.outerWidth() - selfWidth; position(settings.preferred,this,selfWidth,selfHeight,topHeight,bottomHeight,leftWidth,rightWidth,topByTop,topByBottom,leftByLeft,leftByRight); }; })(jQuery); (function($) { $.fn.colorPicker = function() { var pubColorText = this; var isVisible = false; var selectedSpan = $("#__selectedSpan"); if(selectedSpan.length<=0) { selectedSpan = $("<div>",{ "id" : "__selectedSpan" }).html("&nbsp;").appendTo(document.body).css({ "line-height" : "1px", "width" : "10px", "height" : "10px", "border" : "1px solid #fff", "cursor" : "pointer", "z-index" : "5", "display" : "none", "position" : "absolute", "left" : "0", "top" : "0" }); } var hoverSpan = $("#__hoverSpan"); if(hoverSpan.length<=0) { hoverSpan = $("<div>",{ "id" : "__hoverSpan" }).html("&nbsp;").appendTo(document.body).css({ "line-height" : "1px", "width" : "10px", "height" : "10px", "border" : "1px solid #fff", "cursor" : "pointer", "z-index" : "6", "display" : "none", "position" : "absolute", "left" : "0", "top" : "0" }); } var pubColorShow = $("<input>", { "type" : "text", "readonly" : "readonly", "tabindex" : "-1" }).css({ "width" : "35px", "cursor" : "pointer", "border" : "1px solid #ccc", "padding" : "2px", "background-color" : "#FFFFFF" }); this.after(pubColorShow); var panel = $("#__colorPanel"); if(panel.length<=0) { panel = $("<div id='__colorPanel' style='position:absolute;display:none;width:228px;border:1px solid #646464;'><div style='padding:2px;text-align:center;background-color:#d6d6d6;'><div id='__colorShow' style='float:left;width:55px;height:20px;border:1px solid #000'></div><div id='__colorText' style='float:left;width:108px;height:22px;font:12px/22px \"Courier New\";'></div><div id='__colorClear' style='float:right;width:55px;height:20px;border:1px dashed #000;cursor:pointer;font:12px/20px \"Courier New\";'>clear</div><div style='clear:both;'></div></div><div style='line-height:1px;'><div style='float:left;width:30px;background-color:#000;'><div id='__colorQuickSpan' style='padding:0 10px 0 9px;'><span id='colorQuickSpan000000' style='background-color:#000000;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpan333333' style='background-color:#333333;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpan666666' style='background-color:#666666;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpan999999' style='background-color:#999999;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpanCCCCCC' style='background-color:#CCCCCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpanFFFFFF' style='background-color:#FFFFFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpanFF0000' style='background-color:#FF0000;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpan00FF00' style='background-color:#00FF00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpan0000FF' style='background-color:#0000FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpanFFFF00' style='background-color:#FFFF00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpan00FFFF' style='background-color:#00FFFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='colorQuickSpanFF00FF' style='background-color:#FF00FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><div style='clear:both;'></div></div></div><div id='__colorSpan' style='float:left;width:198px;'><span id='__colorSpan000000' style='background-color:#000000;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan003300' style='background-color:#003300;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan006600' style='background-color:#006600;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan009900' style='background-color:#009900;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00CC00' style='background-color:#00CC00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00FF00' style='background-color:#00FF00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan330000' style='background-color:#330000;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan333300' style='background-color:#333300;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan336600' style='background-color:#336600;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan339900' style='background-color:#339900;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33CC00' style='background-color:#33CC00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33FF00' style='background-color:#33FF00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan660000' style='background-color:#660000;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan663300' style='background-color:#663300;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan666600' style='background-color:#666600;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan669900' style='background-color:#669900;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66CC00' style='background-color:#66CC00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66FF00' style='background-color:#66FF00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan000033' style='background-color:#000033;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan003333' style='background-color:#003333;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan006633' style='background-color:#006633;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan009933' style='background-color:#009933;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00CC33' style='background-color:#00CC33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00FF33' style='background-color:#00FF33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan330033' style='background-color:#330033;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan333333' style='background-color:#333333;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan336633' style='background-color:#336633;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan339933' style='background-color:#339933;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33CC33' style='background-color:#33CC33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33FF33' style='background-color:#33FF33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan660033' style='background-color:#660033;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan663333' style='background-color:#663333;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan666633' style='background-color:#666633;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan669933' style='background-color:#669933;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66CC33' style='background-color:#66CC33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66FF33' style='background-color:#66FF33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan000066' style='background-color:#000066;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan003366' style='background-color:#003366;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan006666' style='background-color:#006666;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan009966' style='background-color:#009966;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00CC66' style='background-color:#00CC66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00FF66' style='background-color:#00FF66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan330066' style='background-color:#330066;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan333366' style='background-color:#333366;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan336666' style='background-color:#336666;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan339966' style='background-color:#339966;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33CC66' style='background-color:#33CC66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33FF66' style='background-color:#33FF66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan660066' style='background-color:#660066;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan663366' style='background-color:#663366;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan666666' style='background-color:#666666;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan669966' style='background-color:#669966;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66CC66' style='background-color:#66CC66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66FF66' style='background-color:#66FF66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan000099' style='background-color:#000099;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan003399' style='background-color:#003399;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan006699' style='background-color:#006699;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan009999' style='background-color:#009999;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00CC99' style='background-color:#00CC99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00FF99' style='background-color:#00FF99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan330099' style='background-color:#330099;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan333399' style='background-color:#333399;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan336699' style='background-color:#336699;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan339999' style='background-color:#339999;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33CC99' style='background-color:#33CC99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33FF99' style='background-color:#33FF99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan660099' style='background-color:#660099;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan663399' style='background-color:#663399;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan666699' style='background-color:#666699;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan669999' style='background-color:#669999;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66CC99' style='background-color:#66CC99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66FF99' style='background-color:#66FF99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan0000CC' style='background-color:#0000CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan0033CC' style='background-color:#0033CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan0066CC' style='background-color:#0066CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan0099CC' style='background-color:#0099CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00CCCC' style='background-color:#00CCCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00FFCC' style='background-color:#00FFCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan3300CC' style='background-color:#3300CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan3333CC' style='background-color:#3333CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan3366CC' style='background-color:#3366CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan3399CC' style='background-color:#3399CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33CCCC' style='background-color:#33CCCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33FFCC' style='background-color:#33FFCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan6600CC' style='background-color:#6600CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan6633CC' style='background-color:#6633CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan6666CC' style='background-color:#6666CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan6699CC' style='background-color:#6699CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66CCCC' style='background-color:#66CCCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66FFCC' style='background-color:#66FFCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan0000FF' style='background-color:#0000FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan0033FF' style='background-color:#0033FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan0066FF' style='background-color:#0066FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan0099FF' style='background-color:#0099FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00CCFF' style='background-color:#00CCFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan00FFFF' style='background-color:#00FFFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan3300FF' style='background-color:#3300FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan3333FF' style='background-color:#3333FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan3366FF' style='background-color:#3366FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan3399FF' style='background-color:#3399FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33CCFF' style='background-color:#33CCFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan33FFFF' style='background-color:#33FFFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan6600FF' style='background-color:#6600FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan6633FF' style='background-color:#6633FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan6666FF' style='background-color:#6666FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan6699FF' style='background-color:#6699FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66CCFF' style='background-color:#66CCFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan66FFFF' style='background-color:#66FFFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan990000' style='background-color:#990000;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan993300' style='background-color:#993300;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan996600' style='background-color:#996600;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan999900' style='background-color:#999900;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99CC00' style='background-color:#99CC00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99FF00' style='background-color:#99FF00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC0000' style='background-color:#CC0000;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC3300' style='background-color:#CC3300;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC6600' style='background-color:#CC6600;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC9900' style='background-color:#CC9900;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCCC00' style='background-color:#CCCC00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCFF00' style='background-color:#CCFF00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF0000' style='background-color:#FF0000;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF3300' style='background-color:#FF3300;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF6600' style='background-color:#FF6600;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF9900' style='background-color:#FF9900;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFCC00' style='background-color:#FFCC00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFFF00' style='background-color:#FFFF00;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan990033' style='background-color:#990033;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan993333' style='background-color:#993333;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan996633' style='background-color:#996633;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan999933' style='background-color:#999933;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99CC33' style='background-color:#99CC33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99FF33' style='background-color:#99FF33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC0033' style='background-color:#CC0033;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC3333' style='background-color:#CC3333;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC6633' style='background-color:#CC6633;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC9933' style='background-color:#CC9933;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCCC33' style='background-color:#CCCC33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCFF33' style='background-color:#CCFF33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF0033' style='background-color:#FF0033;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF3333' style='background-color:#FF3333;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF6633' style='background-color:#FF6633;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF9933' style='background-color:#FF9933;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFCC33' style='background-color:#FFCC33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFFF33' style='background-color:#FFFF33;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan990066' style='background-color:#990066;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan993366' style='background-color:#993366;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan996666' style='background-color:#996666;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan999966' style='background-color:#999966;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99CC66' style='background-color:#99CC66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99FF66' style='background-color:#99FF66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC0066' style='background-color:#CC0066;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC3366' style='background-color:#CC3366;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC6666' style='background-color:#CC6666;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC9966' style='background-color:#CC9966;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCCC66' style='background-color:#CCCC66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCFF66' style='background-color:#CCFF66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF0066' style='background-color:#FF0066;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF3366' style='background-color:#FF3366;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF6666' style='background-color:#FF6666;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF9966' style='background-color:#FF9966;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFCC66' style='background-color:#FFCC66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFFF66' style='background-color:#FFFF66;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan990099' style='background-color:#990099;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan993399' style='background-color:#993399;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan996699' style='background-color:#996699;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan999999' style='background-color:#999999;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99CC99' style='background-color:#99CC99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99FF99' style='background-color:#99FF99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC0099' style='background-color:#CC0099;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC3399' style='background-color:#CC3399;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC6699' style='background-color:#CC6699;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC9999' style='background-color:#CC9999;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCCC99' style='background-color:#CCCC99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCFF99' style='background-color:#CCFF99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF0099' style='background-color:#FF0099;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF3399' style='background-color:#FF3399;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF6699' style='background-color:#FF6699;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF9999' style='background-color:#FF9999;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFCC99' style='background-color:#FFCC99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFFF99' style='background-color:#FFFF99;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan9900CC' style='background-color:#9900CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan9933CC' style='background-color:#9933CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan9966CC' style='background-color:#9966CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan9999CC' style='background-color:#9999CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99CCCC' style='background-color:#99CCCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99FFCC' style='background-color:#99FFCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC00CC' style='background-color:#CC00CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC33CC' style='background-color:#CC33CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC66CC' style='background-color:#CC66CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC99CC' style='background-color:#CC99CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCCCCC' style='background-color:#CCCCCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCFFCC' style='background-color:#CCFFCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF00CC' style='background-color:#FF00CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF33CC' style='background-color:#FF33CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF66CC' style='background-color:#FF66CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF99CC' style='background-color:#FF99CC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFCCCC' style='background-color:#FFCCCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFFFCC' style='background-color:#FFFFCC;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan9900FF' style='background-color:#9900FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan9933FF' style='background-color:#9933FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan9966FF' style='background-color:#9966FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan9999FF' style='background-color:#9999FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99CCFF' style='background-color:#99CCFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpan99FFFF' style='background-color:#99FFFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC00FF' style='background-color:#CC00FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC33FF' style='background-color:#CC33FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC66FF' style='background-color:#CC66FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCC99FF' style='background-color:#CC99FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCCCFF' style='background-color:#CCCCFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanCCFFFF' style='background-color:#CCFFFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF00FF' style='background-color:#FF00FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF33FF' style='background-color:#FF33FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF66FF' style='background-color:#FF66FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFF99FF' style='background-color:#FF99FF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFCCFF' style='background-color:#FFCCFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><span id='__colorSpanFFFFFF' style='background-color:#FFFFFF;z-index:10;float:left;width:10px;height:10px;cursor:pointer;border-left:1px solid;border-top:1px solid;'>&nbsp;</span><div style='clear:both;'></div></div><div style='clear:both;'></div></div></div>"); panel.appendTo(document.body).offset({left:-99999,top:-99999}).show(); var colorText = $("#__colorText"); var colorShow = $("#__colorShow"); var colorClear = $("#__colorClear"); $("#__colorSpan span, #__colorQuickSpan span").add(selectedSpan).mouseenter(function(){ if(!isVisible) return; var attrBg = $(this).attr("attrBgColor"); var bg = attrBg || "#"+this.id.substring(this.id.length-6).toUpperCase(); colorText.html(bg); colorShow.css("background-color",bg); hoverSpan.css("background-color",bg); hoverSpan.show(); hoverSpan.offset($(this).offset()); }); hoverSpan.click(function() { var bg = colorText.html(); pubColorText.val(bg); pubColorShow.css("background-color",bg); }); colorClear.mouseover(function() { hoverSpan.hide(); colorText.html(""); colorShow.css("background-color","#FFFFFF"); }).click(function() { pubColorText.val(""); pubColorShow.css("background-color","#FFFFFF"); }); } pubColorShow.focus(function() { $(this).blur(); }).click(function() { if(!isVisible) { isVisible = true; panel.show(); panel.positionOf(pubColorText); var color = $.trim(pubColorText.val()); if(color!="") { var currColorSpan = $("#__colorSpan"+color.substring(1).toUpperCase()); if(currColorSpan.length>0) { selectedSpan.show(); selectedSpan.css("background-color",color); selectedSpan.attr("attrBgColor",color); selectedSpan.offset(currColorSpan.offset()); } else { selectedSpan.hide(); } colorText.html(color); colorShow.css("background-color","#FFFFFF"); colorShow.css("background-color",color); } $(document).bind("mousedown", function(event) { $(document).unbind("mousedown"); setTimeout(function() { isVisible = false; hoverSpan.hide(); selectedSpan.hide(); panel.hide(); pubColorText.focus(); },200); }); } }); pubColorText.change(function() { var color = $.trim($(this).val()); try { if (color != "") { pubColorShow.css("background-color", "#FFFFFF"); pubColorShow.css("background-color", color); } else { pubColorShow.css("background-color", "#FFFFFF"); } } catch (ex) { alert("Invalid color: " + color); $(this).focus().select(); } }); pubColorText.change(); }; })(jQuery);
var WebTorrent = require('webtorrent') var client = new WebTorrent() client.add(magnet_uri, function (torrent) { // Got torrent metadata! console.log('Torrent info hash:', torrent.infoHash) // Let's say the first file is a webm (vp8) or mp4 (h264) video... var file = torrent.files[0] // Create a video element var video = document.createElement('video') video.controls = true document.body.appendChild(video) // Stream the video into the video tag file.createReadStream().pipe(video) })
import express from 'express'; import bodyParser from 'body-parser'; import morgan from 'morgan'; import expressValidator from 'express-validator'; import 'babel-polyfill'; // Test things out // Import The Routes Index File ========================================= import allRoutes from './routes/api/v1'; const app = express(); // Static assets app.use(express.static('server/UI')); // Some neccessary middleware app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(morgan('dev')); // Set Up CORS app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header( 'Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, x-access-token, Origin, X-Requested-With, Content-Type, Accept, Authorization', ); if (req.method === 'OPTIONS') { res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); return res.status(200).json({}); } return next(); }); // Express Validator Middleware app.use( expressValidator({ errorFormatter: (param, msg, value) => { const namespace = param.split('.'); const root = namespace.shift(); let formParam = root; while (namespace.length) { formParam += `[${namespace.shift()}]`; } return { param: formParam, msg, value, }; }, }), ); // Use The Routes Index File app.use('/api/v1/', allRoutes); // 404 page app.use('*/*', express.static('server/UI/404.html')); // Default to here when an invalid endpoint is entered app.use('/', (req, res) => res.status(404).json({ success: false, errors: [{ msg: 'This endpoint does not exist' }], })); // App use app.use((errors, req, res) => { const msg = errors.message || 'An error occured while processing your request, try again in a moment'; res.status(errors.status || 500); res.json({ errors: [{ msg }], }); }); // Define The Port and Host const PORT = process.env.PORT || 5000; // Start the node server app.listen(PORT, () => { console.log(`Server Started Successfully On PORT: ${PORT}`); }); export default app;
define('node_modules/lodash/fp/assignInAll', function(require, exports, module) { var convert = require('node_modules/lodash/fp/convert'), func = convert('assignInAll', require('node_modules/lodash/assignIn')); func.placeholder = require('node_modules/lodash/fp/placeholder'); module.exports = func; });
/* * @Author: your name * @Date: 2021-02-01 11:45:33 * @LastEditTime: 2021-04-20 22:16:29 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \vue-admin-template\src\api\user.js */ import request from '@/utils/request' export function login(params = {}) { return request.postNormal('/library/auth/login', params) } export function getInfo(username, params = {}) { return request.get(`/library/auth/success/${username}`, params) } export function logout(params = {}) { return request.postNormal('/library/auth/logout', params) }
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); reportWebVitals();
'use strict'; function _child_process() { const data = require('child_process'); _child_process = function _child_process() { return data; }; return data; } function _crypto() { const data = _interopRequireDefault(require('crypto')); _crypto = function _crypto() { return data; }; return data; } function _events() { const data = _interopRequireDefault(require('events')); _events = function _events() { return data; }; return data; } function _os() { const data = _interopRequireDefault(require('os')); _os = function _os() { return data; }; return data; } function _path() { const data = _interopRequireDefault(require('path')); _path = function _path() { return data; }; return data; } function _sane() { const data = _interopRequireDefault(require('sane')); _sane = function _sane() { return data; }; return data; } function _invariant() { const data = _interopRequireDefault(require('invariant')); _invariant = function _invariant() { return data; }; return data; } function _jestSerializer() { const data = _interopRequireDefault(require('jest-serializer')); _jestSerializer = function _jestSerializer() { return data; }; return data; } function _jestWorker() { const data = _interopRequireDefault(require('jest-worker')); _jestWorker = function _jestWorker() { return data; }; return data; } var _worker = require('./worker'); var _getMockName = _interopRequireDefault(require('./getMockName')); var _getPlatformExtension = _interopRequireDefault( require('./lib/getPlatformExtension') ); var _constants = _interopRequireDefault(require('./constants')); var _HasteFS = _interopRequireDefault(require('./HasteFS')); var _ModuleMap = _interopRequireDefault(require('./ModuleMap')); var _node = _interopRequireDefault(require('./crawlers/node')); var _normalizePathSep = _interopRequireDefault( require('./lib/normalizePathSep') ); var _watchman = _interopRequireDefault(require('./crawlers/watchman')); var _WatchmanWatcher = _interopRequireDefault(require('./lib/WatchmanWatcher')); var _FSEventsWatcher = _interopRequireDefault(require('./lib/FSEventsWatcher')); var fastPath = _interopRequireWildcard(require('./lib/fast_path')); 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)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } function _slicedToArray(arr, i) { return ( _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest() ); } function _nonIterableRest() { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for ( var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true ) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return'] != null) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err); } _next(undefined); }); }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } const CHANGE_INTERVAL = 30; const MAX_WAIT_TIME = 240000; const NODE_MODULES = _path().default.sep + 'node_modules' + _path().default.sep; const PACKAGE_JSON = _path().default.sep + 'package.json'; // TypeScript doesn't like us importing from outside `rootDir`, but it doesn't // understand `require`. const _require = require('../package.json'), VERSION = _require.version; const canUseWatchman = (() => { try { (0, _child_process().execSync)('watchman --version', { stdio: ['ignore'] }); return true; } catch (e) {} return false; })(); const escapePathSeparator = string => _path().default.sep === '\\' ? string.replace(/(\/|\\)/g, '\\\\') : string; const getWhiteList = list => { if (list && list.length) { const newList = list.map(item => escapePathSeparator(item.replace(/(\/)/g, _path().default.sep)) ); return new RegExp( '(' + escapePathSeparator(NODE_MODULES) + '(?:' + newList.join('|') + ')(?=$|' + escapePathSeparator(_path().default.sep) + '))', 'g' ); } return null; }; /** * HasteMap is a JavaScript implementation of Facebook's haste module system. * * This implementation is inspired by https://github.com/facebook/node-haste * and was built with for high-performance in large code repositories with * hundreds of thousands of files. This implementation is scalable and provides * predictable performance. * * Because the haste map creation and synchronization is critical to startup * performance and most tasks are blocked by I/O this class makes heavy use of * synchronous operations. It uses worker processes for parallelizing file * access and metadata extraction. * * The data structures created by `jest-haste-map` can be used directly from the * cache without further processing. The metadata objects in the `files` and * `map` objects contain cross-references: a metadata object from one can look * up the corresponding metadata object in the other map. Note that in most * projects, the number of files will be greater than the number of haste * modules one module can refer to many files based on platform extensions. * * type HasteMap = { * clocks: WatchmanClocks, * files: {[filepath: string]: FileMetaData}, * map: {[id: string]: ModuleMapItem}, * mocks: {[id: string]: string}, * } * * // Watchman clocks are used for query synchronization and file system deltas. * type WatchmanClocks = {[filepath: string]: string}; * * type FileMetaData = { * id: ?string, // used to look up module metadata objects in `map`. * mtime: number, // check for outdated files. * size: number, // size of the file in bytes. * visited: boolean, // whether the file has been parsed or not. * dependencies: Array<string>, // all relative dependencies of this file. * sha1: ?string, // SHA-1 of the file, if requested via options. * }; * * // Modules can be targeted to a specific platform based on the file name. * // Example: platform.ios.js and Platform.android.js will both map to the same * // `Platform` module. The platform should be specified during resolution. * type ModuleMapItem = {[platform: string]: ModuleMetaData}; * * // * type ModuleMetaData = { * path: string, // the path to look up the file object in `files`. * type: string, // the module type (either `package` or `module`). * }; * * Note that the data structures described above are conceptual only. The actual * implementation uses arrays and constant keys for metadata storage. Instead of * `{id: 'flatMap', mtime: 3421, size: 42, visited: true, dependencies: []}` the real * representation is similar to `['flatMap', 3421, 42, 1, []]` to save storage space * and reduce parse and write time of a big JSON blob. * * The HasteMap is created as follows: * 1. read data from the cache or create an empty structure. * * 2. crawl the file system. * * empty cache: crawl the entire file system. * * cache available: * * if watchman is available: get file system delta changes. * * if watchman is unavailable: crawl the entire file system. * * build metadata objects for every file. This builds the `files` part of * the `HasteMap`. * * 3. parse and extract metadata from changed files. * * this is done in parallel over worker processes to improve performance. * * the worst case is to parse all files. * * the best case is no file system access and retrieving all data from * the cache. * * the average case is a small number of changed files. * * 4. serialize the new `HasteMap` in a cache file. * Worker processes can directly access the cache through `HasteMap.read()`. * */ /* eslint-disable-next-line no-redeclare */ class HasteMap extends _events().default { constructor(options) { super(); _defineProperty(this, '_buildPromise', void 0); _defineProperty(this, '_cachePath', void 0); _defineProperty(this, '_changeInterval', void 0); _defineProperty(this, '_console', void 0); _defineProperty(this, '_options', void 0); _defineProperty(this, '_watchers', void 0); _defineProperty(this, '_whitelist', void 0); _defineProperty(this, '_worker', void 0); this._options = { cacheDirectory: options.cacheDirectory || _os().default.tmpdir(), computeDependencies: options.computeDependencies === undefined ? true : options.computeDependencies, computeSha1: options.computeSha1 || false, dependencyExtractor: options.dependencyExtractor, extensions: options.extensions, forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, hasteImplModulePath: options.hasteImplModulePath, ignorePattern: options.ignorePattern, mapper: options.mapper, maxWorkers: options.maxWorkers, mocksPattern: options.mocksPattern ? new RegExp(options.mocksPattern) : null, name: options.name, platforms: options.platforms, resetCache: options.resetCache, retainAllFiles: options.retainAllFiles, rootDir: options.rootDir, roots: Array.from(new Set(options.roots)), skipPackageJson: !!options.skipPackageJson, throwOnModuleCollision: !!options.throwOnModuleCollision, useWatchman: options.useWatchman == null ? true : options.useWatchman, watch: !!options.watch }; this._console = options.console || global.console; if (options.ignorePattern && !(options.ignorePattern instanceof RegExp)) { this._console.warn( 'jest-haste-map: the `ignorePattern` options as a function is being ' + 'deprecated. Provide a RegExp instead. See https://github.com/facebook/jest/pull/4063.' ); } const rootDirHash = _crypto() .default.createHash('md5') .update(options.rootDir) .digest('hex'); let hasteImplHash = ''; let dependencyExtractorHash = ''; if (options.hasteImplModulePath) { const hasteImpl = require(options.hasteImplModulePath); if (hasteImpl.getCacheKey) { hasteImplHash = String(hasteImpl.getCacheKey()); } } if (options.dependencyExtractor) { const dependencyExtractor = require(options.dependencyExtractor); if (dependencyExtractor.getCacheKey) { dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); } } this._cachePath = HasteMap.getCacheFilePath( this._options.cacheDirectory, `haste-map-${this._options.name}-${rootDirHash}`, VERSION, this._options.name, this._options.roots .map(root => fastPath.relative(options.rootDir, root)) .join(':'), this._options.extensions.join(':'), this._options.platforms.join(':'), this._options.computeSha1.toString(), options.mocksPattern || '', (options.ignorePattern || '').toString(), hasteImplHash, dependencyExtractorHash ); this._whitelist = getWhiteList(options.providesModuleNodeModules); this._buildPromise = null; this._watchers = []; this._worker = null; } static getCacheFilePath(tmpdir, name, ...extra) { const hash = _crypto() .default.createHash('md5') .update(extra.join('')); return _path().default.join( tmpdir, name.replace(/\W/g, '-') + '-' + hash.digest('hex') ); } getCacheFilePath() { return this._cachePath; } build() { var _this = this; if (!this._buildPromise) { this._buildPromise = _asyncToGenerator(function*() { const data = yield _this._buildFileMap(); // Persist when we don't know if files changed (changedFiles undefined) // or when we know a file was changed or deleted. let hasteMap; if ( data.changedFiles === undefined || data.changedFiles.size > 0 || data.removedFiles.size > 0 ) { hasteMap = yield _this._buildHasteMap(data); _this._persist(hasteMap); } else { hasteMap = data.hasteMap; } const rootDir = _this._options.rootDir; const hasteFS = new _HasteFS.default({ files: hasteMap.files, rootDir }); const moduleMap = new _ModuleMap.default({ duplicates: hasteMap.duplicates, map: hasteMap.map, mocks: hasteMap.mocks, rootDir }); const __hasteMapForTest = (process.env.NODE_ENV === 'test' && hasteMap) || null; yield _this._watch(hasteMap); return { __hasteMapForTest, hasteFS, moduleMap }; })(); } return this._buildPromise; } /** * 1. read data from the cache or create an empty structure. */ read() { let hasteMap; try { hasteMap = _jestSerializer().default.readFileSync(this._cachePath); } catch (err) { hasteMap = this._createEmptyMap(); } return hasteMap; } readModuleMap() { const data = this.read(); return new _ModuleMap.default({ duplicates: data.duplicates, map: data.map, mocks: data.mocks, rootDir: this._options.rootDir }); } /** * 2. crawl the file system. */ _buildFileMap() { var _this2 = this; return _asyncToGenerator(function*() { let hasteMap; try { const read = _this2._options.resetCache ? _this2._createEmptyMap : _this2.read; hasteMap = yield read.call(_this2); } catch (_unused) { hasteMap = _this2._createEmptyMap(); } return _this2._crawl(hasteMap); })(); } /** * 3. parse and extract metadata from changed files. */ _processFile(hasteMap, map, mocks, filePath, workerOptions) { const rootDir = this._options.rootDir; const setModule = (id, module) => { let moduleMap = map.get(id); if (!moduleMap) { moduleMap = Object.create(null); map.set(id, moduleMap); } const platform = (0, _getPlatformExtension.default)( module[_constants.default.PATH], this._options.platforms ) || _constants.default.GENERIC_PLATFORM; const existingModule = moduleMap[platform]; if ( existingModule && existingModule[_constants.default.PATH] !== module[_constants.default.PATH] ) { const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; this._console[method]( [ 'jest-haste-map: Haste module naming collision: ' + id, ' The following files share their name; please adjust your hasteImpl:', ' * <rootDir>' + _path().default.sep + existingModule[_constants.default.PATH], ' * <rootDir>' + _path().default.sep + module[_constants.default.PATH], '' ].join('\n') ); if (this._options.throwOnModuleCollision) { throw new DuplicateError( existingModule[_constants.default.PATH], module[_constants.default.PATH] ); } // We do NOT want consumers to use a module that is ambiguous. delete moduleMap[platform]; if (Object.keys(moduleMap).length === 1) { map.delete(id); } let dupsByPlatform = hasteMap.duplicates.get(id); if (dupsByPlatform == null) { dupsByPlatform = new Map(); hasteMap.duplicates.set(id, dupsByPlatform); } const dups = new Map([ [module[_constants.default.PATH], module[_constants.default.TYPE]], [ existingModule[_constants.default.PATH], existingModule[_constants.default.TYPE] ] ]); dupsByPlatform.set(platform, dups); return; } const dupsByPlatform = hasteMap.duplicates.get(id); if (dupsByPlatform != null) { const dups = dupsByPlatform.get(platform); if (dups != null) { dups.set( module[_constants.default.PATH], module[_constants.default.TYPE] ); } return; } moduleMap[platform] = module; }; const relativeFilePath = fastPath.relative(rootDir, filePath); const fileMetadata = hasteMap.files.get(relativeFilePath); if (!fileMetadata) { throw new Error( 'jest-haste-map: File to process was not found in the haste map.' ); } const moduleMetadata = hasteMap.map.get( fileMetadata[_constants.default.ID] ); const computeSha1 = this._options.computeSha1 && !fileMetadata[_constants.default.SHA1]; // Callback called when the response from the worker is successful. const workerReply = metadata => { // `1` for truthy values instead of `true` to save cache space. fileMetadata[_constants.default.VISITED] = 1; const metadataId = metadata.id; const metadataModule = metadata.module; if (metadataId && metadataModule) { fileMetadata[_constants.default.ID] = metadataId; setModule(metadataId, metadataModule); } fileMetadata[_constants.default.DEPENDENCIES] = metadata.dependencies ? metadata.dependencies.join(_constants.default.DEPENDENCY_DELIM) : ''; if (computeSha1) { fileMetadata[_constants.default.SHA1] = metadata.sha1; } }; // Callback called when the response from the worker is an error. const workerError = error => { if (typeof error !== 'object' || !error.message || !error.stack) { error = new Error(error); error.stack = ''; // Remove stack for stack-less errors. } // @ts-ignore: checking error code is OK if error comes from "fs". if (!['ENOENT', 'EACCES'].includes(error.code)) { throw error; } // If a file cannot be read we remove it from the file list and // ignore the failure silently. hasteMap.files.delete(relativeFilePath); }; // If we retain all files in the virtual HasteFS representation, we avoid // reading them if they aren't important (node_modules). if (this._options.retainAllFiles && this._isNodeModulesDir(filePath)) { if (computeSha1) { return this._getWorker(workerOptions) .getSha1({ computeDependencies: this._options.computeDependencies, computeSha1, dependencyExtractor: this._options.dependencyExtractor, filePath, hasteImplModulePath: this._options.hasteImplModulePath, rootDir }) .then(workerReply, workerError); } return null; } if ( this._options.mocksPattern && this._options.mocksPattern.test(filePath) ) { const mockPath = (0, _getMockName.default)(filePath); const existingMockPath = mocks.get(mockPath); if (existingMockPath) { const secondMockPath = fastPath.relative(rootDir, filePath); if (existingMockPath !== secondMockPath) { const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; this._console[method]( [ 'jest-haste-map: duplicate manual mock found: ' + mockPath, ' The following files share their name; please delete one of them:', ' * <rootDir>' + _path().default.sep + existingMockPath, ' * <rootDir>' + _path().default.sep + secondMockPath, '' ].join('\n') ); if (this._options.throwOnModuleCollision) { throw new DuplicateError(existingMockPath, secondMockPath); } } } mocks.set(mockPath, relativeFilePath); } if (fileMetadata[_constants.default.VISITED]) { if (!fileMetadata[_constants.default.ID]) { return null; } if (moduleMetadata != null) { const platform = (0, _getPlatformExtension.default)( filePath, this._options.platforms ) || _constants.default.GENERIC_PLATFORM; const module = moduleMetadata[platform]; if (module == null) { return null; } const moduleId = fileMetadata[_constants.default.ID]; let modulesByPlatform = map.get(moduleId); if (!modulesByPlatform) { modulesByPlatform = Object.create(null); map.set(moduleId, modulesByPlatform); } modulesByPlatform[platform] = module; return null; } } return this._getWorker(workerOptions) .worker({ computeDependencies: this._options.computeDependencies, computeSha1, dependencyExtractor: this._options.dependencyExtractor, filePath, hasteImplModulePath: this._options.hasteImplModulePath, rootDir }) .then(workerReply, workerError); } _buildHasteMap(data) { const removedFiles = data.removedFiles, changedFiles = data.changedFiles, hasteMap = data.hasteMap; // If any files were removed or we did not track what files changed, process // every file looking for changes. Otherwise, process only changed files. let map; let mocks; let filesToProcess; if (changedFiles === undefined || removedFiles.size) { map = new Map(); mocks = new Map(); filesToProcess = hasteMap.files; } else { map = hasteMap.map; mocks = hasteMap.mocks; filesToProcess = changedFiles; } var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for ( var _iterator = removedFiles[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true ) { const _step$value = _slicedToArray(_step.value, 2), relativeFilePath = _step$value[0], fileMetadata = _step$value[1]; this._recoverDuplicates( hasteMap, relativeFilePath, fileMetadata[_constants.default.ID] ); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } const promises = []; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for ( var _iterator2 = filesToProcess.keys()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true ) { const relativeFilePath = _step2.value; if ( this._options.skipPackageJson && relativeFilePath.endsWith(PACKAGE_JSON) ) { continue; } // SHA-1, if requested, should already be present thanks to the crawler. const filePath = fastPath.resolve( this._options.rootDir, relativeFilePath ); const promise = this._processFile(hasteMap, map, mocks, filePath); if (promise) { promises.push(promise); } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return != null) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return Promise.all(promises).then( () => { this._cleanup(); hasteMap.map = map; hasteMap.mocks = mocks; return hasteMap; }, error => { this._cleanup(); throw error; } ); } _cleanup() { const worker = this._worker; // @ts-ignore if (worker && typeof worker.end === 'function') { // @ts-ignore worker.end(); } this._worker = null; } /** * 4. serialize the new `HasteMap` in a cache file. */ _persist(hasteMap) { _jestSerializer().default.writeFileSync(this._cachePath, hasteMap); } /** * Creates workers or parses files and extracts metadata in-process. */ _getWorker(options) { if (!this._worker) { if ((options && options.forceInBand) || this._options.maxWorkers <= 1) { this._worker = { getSha1: _worker.getSha1, worker: _worker.worker }; } else { // @ts-ignore: assignment of a worker with custom properties. this._worker = new (_jestWorker()).default( require.resolve('./worker'), { exposedMethods: ['getSha1', 'worker'], maxRetries: 3, numWorkers: this._options.maxWorkers } ); } } return this._worker; } _crawl(hasteMap) { const options = this._options; const ignore = this._ignore.bind(this); const crawl = canUseWatchman && this._options.useWatchman ? _watchman.default : _node.default; const crawlerOptions = { computeSha1: options.computeSha1, data: hasteMap, extensions: options.extensions, forceNodeFilesystemAPI: options.forceNodeFilesystemAPI, ignore, mapper: options.mapper, rootDir: options.rootDir, roots: options.roots }; const retry = error => { if (crawl === _watchman.default) { this._console.warn( `jest-haste-map: Watchman crawl failed. Retrying once with node ` + `crawler.\n` + ` Usually this happens when watchman isn't running. Create an ` + `empty \`.watchmanconfig\` file in your project's root folder or ` + `initialize a git or hg repository in your project.\n` + ` ` + error ); return (0, _node.default)(crawlerOptions).catch(e => { throw new Error( `Crawler retry failed:\n` + ` Original error: ${error.message}\n` + ` Retry error: ${e.message}\n` ); }); } throw error; }; try { return crawl(crawlerOptions).catch(retry); } catch (error) { return retry(error); } } /** * Watch mode */ _watch(hasteMap) { if (!this._options.watch) { return Promise.resolve(); } // In watch mode, we'll only warn about module collisions and we'll retain // all files, even changes to node_modules. this._options.throwOnModuleCollision = false; this._options.retainAllFiles = true; // WatchmanWatcher > FSEventsWatcher > sane.NodeWatcher const Watcher = canUseWatchman && this._options.useWatchman ? _WatchmanWatcher.default : _FSEventsWatcher.default.isSupported() ? _FSEventsWatcher.default : _sane().default.NodeWatcher; const extensions = this._options.extensions; const ignorePattern = this._options.ignorePattern; const rootDir = this._options.rootDir; let changeQueue = Promise.resolve(); let eventsQueue = []; // We only need to copy the entire haste map once on every "frame". let mustCopy = true; const createWatcher = root => { // @ts-ignore: TODO how? "Cannot use 'new' with an expression whose type lacks a call or construct signature." const watcher = new Watcher(root, { dot: false, glob: extensions.map(extension => '**/*.' + extension), ignored: ignorePattern }); return new Promise((resolve, reject) => { const rejectTimeout = setTimeout( () => reject(new Error('Failed to start watch mode.')), MAX_WAIT_TIME ); watcher.once('ready', () => { clearTimeout(rejectTimeout); watcher.on('all', onChange); resolve(watcher); }); }); }; const emitChange = () => { if (eventsQueue.length) { mustCopy = true; const changeEvent = { eventsQueue, hasteFS: new _HasteFS.default({ files: hasteMap.files, rootDir }), moduleMap: new _ModuleMap.default({ duplicates: hasteMap.duplicates, map: hasteMap.map, mocks: hasteMap.mocks, rootDir }) }; this.emit('change', changeEvent); eventsQueue = []; } }; const onChange = (type, filePath, root, stat) => { filePath = _path().default.join( root, (0, _normalizePathSep.default)(filePath) ); if ( (stat && stat.isDirectory()) || this._ignore(filePath) || !extensions.some(extension => filePath.endsWith(extension)) ) { return; } changeQueue = changeQueue .then(() => { // If we get duplicate events for the same file, ignore them. if ( eventsQueue.find( event => event.type === type && event.filePath === filePath && ((!event.stat && !stat) || (!!event.stat && !!stat && event.stat.mtime.getTime() === stat.mtime.getTime())) ) ) { return null; } if (mustCopy) { mustCopy = false; hasteMap = { clocks: new Map(hasteMap.clocks), duplicates: new Map(hasteMap.duplicates), files: new Map(hasteMap.files), map: new Map(hasteMap.map), mocks: new Map(hasteMap.mocks) }; } const add = () => { eventsQueue.push({ filePath, stat, type }); return null; }; const relativeFilePath = fastPath.relative(rootDir, filePath); const fileMetadata = hasteMap.files.get(relativeFilePath); // If it's not an addition, delete the file and all its metadata if (fileMetadata != null) { const moduleName = fileMetadata[_constants.default.ID]; const platform = (0, _getPlatformExtension.default)( filePath, this._options.platforms ) || _constants.default.GENERIC_PLATFORM; hasteMap.files.delete(relativeFilePath); let moduleMap = hasteMap.map.get(moduleName); if (moduleMap != null) { // We are forced to copy the object because jest-haste-map exposes // the map as an immutable entity. moduleMap = copy(moduleMap); delete moduleMap[platform]; if (Object.keys(moduleMap).length === 0) { hasteMap.map.delete(moduleName); } else { hasteMap.map.set(moduleName, moduleMap); } } if ( this._options.mocksPattern && this._options.mocksPattern.test(filePath) ) { const mockName = (0, _getMockName.default)(filePath); hasteMap.mocks.delete(mockName); } this._recoverDuplicates(hasteMap, relativeFilePath, moduleName); } // If the file was added or changed, // parse it and update the haste map. if (type === 'add' || type === 'change') { (0, _invariant().default)( stat, 'since the file exists or changed, it should have stats' ); const fileMetadata = [ '', stat ? stat.mtime.getTime() : -1, stat ? stat.size : 0, 0, '', null ]; hasteMap.files.set(relativeFilePath, fileMetadata); const promise = this._processFile( hasteMap, hasteMap.map, hasteMap.mocks, filePath, { forceInBand: true } ); // Cleanup this._cleanup(); if (promise) { return promise.then(add); } else { // If a file in node_modules has changed, // emit an event regardless. add(); } } else { add(); } return null; }) .catch(error => { this._console.error( `jest-haste-map: watch error:\n ${error.stack}\n` ); }); }; this._changeInterval = setInterval(emitChange, CHANGE_INTERVAL); return Promise.all(this._options.roots.map(createWatcher)).then( watchers => { this._watchers = watchers; } ); } /** * This function should be called when the file under `filePath` is removed * or changed. When that happens, we want to figure out if that file was * part of a group of files that had the same ID. If it was, we want to * remove it from the group. Furthermore, if there is only one file * remaining in the group, then we want to restore that single file as the * correct resolution for its ID, and cleanup the duplicates index. */ _recoverDuplicates(hasteMap, relativeFilePath, moduleName) { let dupsByPlatform = hasteMap.duplicates.get(moduleName); if (dupsByPlatform == null) { return; } const platform = (0, _getPlatformExtension.default)( relativeFilePath, this._options.platforms ) || _constants.default.GENERIC_PLATFORM; let dups = dupsByPlatform.get(platform); if (dups == null) { return; } dupsByPlatform = copyMap(dupsByPlatform); hasteMap.duplicates.set(moduleName, dupsByPlatform); dups = copyMap(dups); dupsByPlatform.set(platform, dups); dups.delete(relativeFilePath); if (dups.size !== 1) { return; } const uniqueModule = dups.entries().next().value; if (!uniqueModule) { return; } let dedupMap = hasteMap.map.get(moduleName); if (dedupMap == null) { dedupMap = Object.create(null); hasteMap.map.set(moduleName, dedupMap); } dedupMap[platform] = uniqueModule; dupsByPlatform.delete(platform); if (dupsByPlatform.size === 0) { hasteMap.duplicates.delete(moduleName); } } end() { // @ts-ignore: TODO TS cannot decide if `setInterval` and `clearInterval` comes from NodeJS or the DOM clearInterval(this._changeInterval); if (!this._watchers.length) { return Promise.resolve(); } return Promise.all( this._watchers.map( watcher => new Promise(resolve => watcher.close(resolve)) ) ).then(() => { this._watchers = []; }); } /** * Helpers */ _ignore(filePath) { const ignorePattern = this._options.ignorePattern; const ignoreMatched = ignorePattern instanceof RegExp ? ignorePattern.test(filePath) : ignorePattern && ignorePattern(filePath); return ( ignoreMatched || (!this._options.retainAllFiles && this._isNodeModulesDir(filePath)) ); } _isNodeModulesDir(filePath) { if (!filePath.includes(NODE_MODULES)) { return false; } if (this._whitelist) { const whitelist = this._whitelist; const match = whitelist.exec(filePath); const matchEndIndex = whitelist.lastIndex; whitelist.lastIndex = 0; if (!match) { return true; } const filePathInPackage = filePath.substr(matchEndIndex); return filePathInPackage.startsWith(NODE_MODULES); } return true; } _createEmptyMap() { return { clocks: new Map(), duplicates: new Map(), files: new Map(), map: new Map(), mocks: new Map() }; } } _defineProperty(HasteMap, 'H', void 0); _defineProperty(HasteMap, 'DuplicateError', void 0); _defineProperty(HasteMap, 'ModuleMap', void 0); class DuplicateError extends Error { constructor(mockPath1, mockPath2) { super('Duplicated files or mocks. Please check the console for more info'); _defineProperty(this, 'mockPath1', void 0); _defineProperty(this, 'mockPath2', void 0); this.mockPath1 = mockPath1; this.mockPath2 = mockPath2; } } function copy(object) { return Object.assign(Object.create(null), object); } function copyMap(input) { return new Map(input); } HasteMap.H = _constants.default; HasteMap.DuplicateError = DuplicateError; HasteMap.ModuleMap = _ModuleMap.default; module.exports = HasteMap;
TestCase("Presenter logic", { setUp: function () { this.presenter = AddonTable_create(); sinon.stub(this.presenter, 'upgradeModel'); sinon.stub(this.presenter, 'validateModel'); sinon.stub(this.presenter, 'generateTable'); this.presenter.generateTable.returns({}); sinon.stub(this.presenter, 'setColumnWidth'); sinon.stub(this.presenter, 'setRowHeight'); sinon.stub(this.presenter, 'setVisibility'); sinon.stub(this.presenter, 'parseDefinitionLinks'); sinon.stub(this.presenter, 'gapLogic'); sinon.stub(this.presenter, 'attachGapsHandlers'); sinon.stub(DOMOperationsUtils, 'showErrorMessage'); }, tearDown: function () { this.presenter.upgradeModel.restore(); this.presenter.validateModel.restore(); this.presenter.generateTable.restore(); this.presenter.setColumnWidth.restore(); this.presenter.setRowHeight.restore(); this.presenter.setVisibility.restore(); this.presenter.parseDefinitionLinks.restore(); this.presenter.gapLogic.restore(); this.presenter.attachGapsHandlers.restore(); DOMOperationsUtils.showErrorMessage.restore(); }, 'test proper config in run mode': function () { this.presenter.validateModel.returns({ isValid: true }); this.presenter.logic({}, {}, false); assertTrue(this.presenter.upgradeModel.calledOnce); assertTrue(this.presenter.validateModel.calledOnce); assertFalse(DOMOperationsUtils.showErrorMessage.called); assertTrue(this.presenter.setColumnWidth.calledOnce); assertTrue(this.presenter.setRowHeight.calledOnce); assertTrue(this.presenter.setVisibility.calledOnce); assertTrue(this.presenter.gapLogic.calledOnce); assertTrue(this.presenter.parseDefinitionLinks.calledOnce); assertTrue(this.presenter.attachGapsHandlers.calledOnce); }, 'test errors during model validation in run mode': function () { this.presenter.validateModel.returns({ isValid: false, errorCode: 'ERR' }); this.presenter.logic({}, {}, false); assertTrue(this.presenter.upgradeModel.calledOnce); assertTrue(this.presenter.validateModel.calledOnce); assertTrue(DOMOperationsUtils.showErrorMessage.calledOnce); assertFalse(this.presenter.setColumnWidth.calledOnce); assertFalse(this.presenter.setRowHeight.calledOnce); assertFalse(this.presenter.setVisibility.calledOnce); assertFalse(this.presenter.gapLogic.calledOnce); assertFalse(this.presenter.parseDefinitionLinks.calledOnce); assertFalse(this.presenter.attachGapsHandlers.calledOnce); }, 'test proper config in preview mode': function () { this.presenter.validateModel.returns({ isValid: true }); this.presenter.logic({}, {}, true); assertTrue(this.presenter.upgradeModel.calledOnce); assertTrue(this.presenter.validateModel.calledOnce); assertFalse(DOMOperationsUtils.showErrorMessage.called); assertTrue(this.presenter.setColumnWidth.calledOnce); assertTrue(this.presenter.setRowHeight.calledOnce); assertTrue(this.presenter.setVisibility.calledOnce); assertFalse(this.presenter.gapLogic.calledOnce); assertFalse(this.presenter.parseDefinitionLinks.calledOnce); assertFalse(this.presenter.attachGapsHandlers.calledOnce); }, 'test errors during model validation in preview mode': function () { this.presenter.validateModel.returns({ isValid: false, errorCode: 'ERR' }); this.presenter.logic({}, {}, true); assertTrue(this.presenter.upgradeModel.calledOnce); assertTrue(this.presenter.validateModel.calledOnce); assertTrue(DOMOperationsUtils.showErrorMessage.calledOnce); assertFalse(this.presenter.setColumnWidth.calledOnce); assertFalse(this.presenter.setRowHeight.calledOnce); assertFalse(this.presenter.setVisibility.calledOnce); assertFalse(this.presenter.gapLogic.calledOnce); assertFalse(this.presenter.parseDefinitionLinks.calledOnce); assertFalse(this.presenter.attachGapsHandlers.calledOnce); } });
/* jshint node: true */ var subject = require('../../index'); var assert = require('../helpers/assert'); describe('Github Deployment Status plugin', function() { it('has a name', function() { var instance = subject.createDeployPlugin({ name: 'foo' }); assert.equal(instance.name, 'foo'); }); it('implements the correct hooks', function() { var plugin = subject.createDeployPlugin({ name: 'foo' }); assert.isDefined(plugin.setup); assert.isFunction(plugin.setup); assert.isDefined(plugin.willDeploy); assert.isFunction(plugin.willDeploy); assert.isDefined(plugin.didDeploy); assert.isFunction(plugin.didDeploy); assert.isDefined(plugin.didFail); assert.isFunction(plugin.didFail); }); });
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * 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. * */ // Italian - root strings /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define({ "MY_DOCUMENTS" : "Miei documenti", "DOCUMENTS" : "Documenti", "MENU_TITLE" : "nuovo progetto…", "NEW_PROJECT_BASE_NAME" : "Senza titolo-", "CHANGE" : "Cambia…", "PROJECT_DIRECTORY_lABEL" : "Cartella genitore:", "CHOOSE_TEMPLATE_LABEL" : "Template:", "PROJECT_NAME_LABEL" : "Nome:", "DIALOG_TITLE" : "Crea Nuovo Progetto", "NO_TEMPLATE_OPTION_LABEL" : "Niente (Progetto vuoto)", "ERROR_NOT_A_DIRECTORY" : "Impossibile scrivere {1} perché non è una cartella valida, il volume non è in linea o non esiste.", "ERROR_DIRECTORY_ALREADY_EXISTS" : "Impossibile creare la cartella di progetto {1} perché esiste già.", "ERROR_UNABLE_TO_WRITE_DIRECTORY" : "Impossibile scrivere su {1} (Errore {0})", "INVALID_PROJECT_NAME" : "Nome del progetto invalido", "INVALID_PROJECT_NAME_MESSAGE" : "Il nome del progetto non può contenere i seguenti caratteri: /?*:;{}<>\\| or use any system reserved words.", "ONE_OR_MORE_TEMPLATE_FILES_FAILED" : "Impossibile copiare tutti i file di modello nella cartella di destinazione. Uno o più operazioni di copia é fallito." });
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Evan You @yyx990803 */ const splitRE = /\r?\n/g const emptyRE = /^\s*$/ const needFixRE = /^(\r?\n)*[\t\s]/ module.exports = function deindent( str ) { if ( !needFixRE.test( str ) ) { return str } const lines = str.split( splitRE ) let min = Infinity let type, cur, c for ( let i = 0; i < lines.length; i++ ) { const line = lines[ i ] if ( !emptyRE.test( line ) ) { if ( type ) { cur = count( line, type ) if ( cur < min ) { min = cur } } else { c = line.charAt( 0 ) if ( c === ' ' || c === '\t' ) { type = c cur = count( line, type ) if ( cur < min ) { min = cur } } else { return str } } } } return lines .map( function ( line ) { return line.slice( min ) } ) .join( '\n' ) } function count( line, type ) { let i = 0 while ( line.charAt( i ) === type ) { i++ } return i }
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ function swap (arr, i, j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } function defaultCompare (a, b) { return a < b ? -1 : a > b ? 1 : 0; } /** * A [Floyd-Rivest](https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm) quick selection algorithm. * * Rearranges the array items so that all items in the [left, k] range are smaller than all items in [k, right]; * The k-th element will have the (k - left + 1)th smallest value in [left, right]. * * The array is modified in-place. * * Based on code by [Vladimir Agafonkin](https://www.npmjs.com/~mourner) * * @function Phaser.Utils.Array.QuickSelect * @since 3.0.0 * * @param {array} arr - The array to sort. * @param {integer} k - The k-th element index. * @param {integer} [left=0] - The index of the left part of the range. * @param {integer} [right] - The index of the right part of the range. * @param {function} [compare] - An optional comparison function. Is passed two elements and should return 0, 1 or -1. */ var QuickSelect = function (arr, k, left, right, compare) { if (left === undefined) { left = 0; } if (right === undefined) { right = arr.length - 1; } if (compare === undefined) { compare = defaultCompare; } while (right > left) { if (right - left > 600) { var n = right - left + 1; var m = k - left + 1; var z = Math.log(n); var s = 0.5 * Math.exp(2 * z / 3); var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); QuickSelect(arr, k, newLeft, newRight, compare); } var t = arr[k]; var i = left; var j = right; swap(arr, left, k); if (compare(arr[right], t) > 0) { swap(arr, left, right); } while (i < j) { swap(arr, i, j); i++; j--; while (compare(arr[i], t) < 0) { i++; } while (compare(arr[j], t) > 0) { j--; } } if (compare(arr[left], t) === 0) { swap(arr, left, j); } else { j++; swap(arr, j, right); } if (j <= k) { left = j + 1; } if (k <= j) { right = j - 1; } } }; module.exports = QuickSelect;
import Vue from 'vue'; import Router from 'vue-router'; // Components import Home from 'pages/Home'; Vue.use(Router) const routes = [ { path: '*', component: Home } ] export default new Router({ routes })
const path = require('path'); module.exports = { appBuild: path.resolve(__dirname, '../dist'), };
import React from 'react' import { Link } from 'react-router-dom' import Delete from './Delete' const BookClubPreview = (props) => { return ( <div className="book-club"> {/* x-button, on click shows confirmation */} <Delete type="Book Club" id={props.id} /> {/* links to specific book club */} <Link to={`/bookclubs/${props.id}`}> <div className="book-club-name"> <h3>{props.name}</h3> </div> </Link> </div> ) } export default BookClubPreview
#!/usr/bin/env node var packageJson = require('./package.json') var execSync = require('child_process').execSync; var path = require('path'); var fs = require('fs'); console.log('Installing npm dependencies'); execSync('yarn install', {stdio:[0,1,2]}); console.log('Installing sdk dependencies'); var sdkDependency = 'SalesforceMobileSDK-iOS'; var repoUrlWithBranch = packageJson.sdkDependencies[sdkDependency]; var parts = repoUrlWithBranch.split('#'), repoUrl = parts[0], branch = parts.length > 1 ? parts[1] : 'master'; var targetDir = path.join('mobile_sdk', sdkDependency); if (fs.existsSync(targetDir)) { console.log(targetDir + ' already exists - if you want to refresh it, please remove it and re-run install.js'); } else { execSync('git clone --branch ' + branch + ' --single-branch --depth 1 ' + repoUrl + ' ' + targetDir, {stdio:[0,1,2]}); } console.log('Installing pod dependencies'); execSync('pod update', {stdio:[0,1,2], cwd:'ios'});
define( ({ showLayerLabels: "Näytä ajan huomioivien karttatasojen nimet pienoisohjelmassa." }) );
var firstnext = document.getElementById('firstnext'), secondnext = document.getElementById('secondnext'), firstback = document.getElementById('firstback'), secondback = document.getElementById('secondback'), first_form = document.getElementById('first_form'), second_form = document.getElementById('second_form'), third_form = document.getElementById('third_form'), progress_bar = document.getElementById("progress_bar"); firstnext.onclick = function (e) { e.preventDefault(); second_form.style.left ="0px"; first_form.style.left="400px"; third_form.style.left ="-400px"; progress_bar.style.width = "66.6666%"; } firstback.onclick = function (e) { e.preventDefault(); second_form.style.left ="-400px"; first_form.style.left="0px"; third_form.style.left ="400px"; third_form.style.opacity="0"; first_form.style.opacity="1"; progress_bar.style.width = "33.3333%"; } secondnext.onclick = function (e) { e.preventDefault(); first_form.style.opacity ="0"; second_form.style.left ="400px"; first_form.style.left="-400px"; third_form.style.left ="0px"; third_form.style.opacity ="1"; progress_bar.style.width = "100%"; } secondback.onclick = function (e) { e.preventDefault(); second_form.style.left ="0px"; first_form.style.left="400px"; third_form.style.left ="-400px"; third_form.style.opacity="1"; progress_bar.style.width = "66.6666%"; }
var mongoose = require('mongoose'); var userSchema = new mongoose.Schema({ name: String, // "Bob" hash: String, // "3hkf67dkh5f73d5kh3f6" email: String, passwordHash: String, // TODO: Add email and login authentication skin: String // "Sky" }); var model = mongoose.model('User', userSchema); module.exports = model;
import { Selector } from 'testcafe'; import testcafeconfig from './testcafeconfig'; import Page from "./page-model"; fixture `Test files` .page`${testcafeconfig.url}`; const page = new Page(); test('#1 Add originals files to album', async t => { await page.openNav(); await t.click(Selector('.p-navigation-albums')); await t .typeText(Selector('.p-albums-search input'), 'KanadaVacation') .pressKey('enter'); await t .expect(Selector('h3').innerText).eql('No albums matched your search'); await t .click(Selector('div.p-navigation-library + div')) .click(Selector('.p-navigation-originals')) .click(Selector('button').withText('Vacation')); const FirstItemInVacation = await Selector('div.v-card__title').nth(0).innerText; const KanadaUid = await Selector('div.v-card__title').nth(0).getAttribute('data-uid'); const SecondItemInVacation = await Selector('div.v-card__title').nth(1).innerText; await t .expect(FirstItemInVacation).contains('Kanada') .expect(SecondItemInVacation).contains('Korsika') .click(Selector('button').withText('Kanada')); const FirstItemInKanada = await Selector('div.v-card__title').nth(0).innerText; const SecondItemInKanada = await Selector('div.v-card__title').nth(1).innerText; await t .expect(FirstItemInKanada).contains('BotanicalGarden') .expect(SecondItemInKanada).contains('IMG') .click(Selector('button').withText('BotanicalGarden')) .click(Selector('a[href="/library/files/Vacation"]')); await page.selectFromUID(KanadaUid); const clipboardCount = await Selector('span.count-clipboard'); await t .expect(clipboardCount.textContent).eql("1"); await page.addSelectedToAlbum('KanadaVacation'); await t .click(Selector('.p-navigation-albums')) .typeText(Selector('.p-albums-search input'), 'KanadaVacation') .pressKey('enter'); const AlbumUid = await Selector('div.p-album').nth(0).getAttribute('data-uid'); await t .click(Selector('div.p-album').nth(0)); const PhotoCountAfterAdd = await Selector('div.p-photo').count; await t .expect(PhotoCountAfterAdd).eql(2) .click(Selector('.p-navigation-albums')); await page.selectFromUID(AlbumUid); await page.deleteSelected(); }); //TODO test download itself + clipboard count after download test('#2 Download original files', async t => { await page.openNav(); await t .click(Selector('div.p-navigation-library + div')) .click(Selector('.p-navigation-originals')); const FirstFile = await Selector('div.p-file').nth(0).getAttribute('data-uid'); await page.selectFromUID(FirstFile); const clipboardCount = await Selector('span.count-clipboard'); await t .expect(clipboardCount.textContent).eql("1") .click(Selector('button.action-menu')) .expect(Selector('button.action-download').visible).ok(); });
'use strict'; const userNameInput = document.getElementById('user-name'); const assessmentButton = document.getElementById('assessment'); const resultDivided = document.getElementById('result-area'); const tweetDivided = document.getElementById('tweet-area'); /* 指定した要素の子供をすべて削除する @param {HTMLElement}element HTMLの要素 */ function removeAllChildren(element){ while (element.firstChild){ //子供の要素があるかぎり削除 element.removeChild(element.firstChild); } } userNameInput.onkeydown = event => { if (event.key == 'Enter'){ assessmentButton.onclick(); } } assessmentButton.onclick = () => { const userName = userNameInput.value; if (userName.length === 0) { // 名前が空の時は処理を終了する return; } // 診断結果表示エリアの作成 removeAllChildren(resultDivided); const header = document.createElement('h3'); header.innerText = '診断結果'; resultDivided.appendChild(header); const paragraph = document.createElement('p'); const result = assessment(userName); paragraph.innerText = result; resultDivided.appendChild(paragraph); // TODO ツイートエリアの作成 removeAllChildren(tweetDivided); const anchor = document.createElement('a'); const hrefValue = 'https://twitter.com/intent/tweet?button_hashtag=' + encodeURIComponent('あなたのいいところ') + '&ref_src=twsrc%5Etfw'; anchor.setAttribute('href',hrefValue); anchor.className = 'twitter-hashtag-button'; anchor.setAttribute('data-text',result); anchor.innerText = 'Tweet #あなたのいいところ'; tweetDivided.appendChild(anchor); const script = document.createElement('script'); script.setAttribute('src', 'https://platform.twitter.com/widgets.js'); tweetDivided.appendChild(script); }; const answers = [ '{userName}のいいところは声です。{userName}の特徴的な声は皆を惹きつけ、心に残ります。', '{userName}のいいところはまなざしです。{userName}に見つめられた人は、気になって仕方がないでしょう。', '{userName}のいいところは情熱です。{userName}の情熱に周りの人は感化されます。', '{userName}のいいところは厳しさです。{userName}の厳しさがものごとをいつも成功に導きます。', '{userName}のいいところは知識です。博識な{userName}を多くの人が頼りにしています。', '{userName}のいいところはユニークさです。{userName}だけのその特徴が皆を楽しくさせます。', '{userName}のいいところは用心深さです。{userName}の洞察に、多くの人が助けられます。', '{userName}のいいところは見た目です。内側から溢れ出る{userName}の良さに皆が気を惹かれます。', '{userName}のいいところは決断力です。{userName}がする決断にいつも助けられる人がいます。', '{userName}のいいところは思いやりです。{userName}に気をかけてもらった多くの人が感謝しています。', '{userName}のいいところは感受性です。{userName}が感じたことに皆が共感し、わかりあうことができます。', '{userName}のいいところは節度です。強引すぎない{userName}の考えに皆が感謝しています。', '{userName}のいいところは好奇心です。新しいことに向かっていく{userName}の心構えが多くの人に魅力的に映ります。', '{userName}のいいところは気配りです。{userName}の配慮が多くの人を救っています。', '{userName}のいいところはその全てです。ありのままの{userName}自身がいいところなのです。', '{userName}のいいところは自制心です。やばいと思ったときにしっかりと衝動を抑えられる{userName}が皆から評価されています。', '{userName}のいいところは優しさです。{userName}の優しい雰囲気や立ち振る舞いに多くの人が癒やされています。' ]; /** * 名前の文字列を渡すと診断結果を返す関数 * @param {string} userName ユーザーの名前 * @return {string} 診断結果 */ function assessment(userName) { // 全文字のコード番号を取得してそれを足し合わせる let sumOfCharCode = 0; for (let i = 0; i < userName.length; i++) { sumOfCharCode = sumOfCharCode + userName.charCodeAt(i); } // 文字のコード番号の合計を回答の数で割って添字の数値を求める const index = sumOfCharCode % answers.length; let result = answers[index]; result = result.replaceAll('{userName}', userName); return result; } // テストコード console.assert( assessment('太郎') === '太郎のいいところは決断力です。太郎がする決断にいつも助けられる人がいます。', '診断結果の文言の特定の部分を名前に置き換える処理が正しくありません。' ); console.assert( assessment('太郎') === assessment('太郎'), '入力が同じ名前なら同じ診断結果を出力する処理が正しくありません。' );
const models = require('../models'); const Cat = models.Cat.CatModel; const Dog = models.Dog.DogModel; const defaultData = { name: 'unknown', bedsOwned: 0, }; const defaultData2 = { name: 'unknown', breed: 'unknown', age: 0, }; let lastAdded = new Cat(defaultData); let lastAdded2 = new Dog(defaultData2); const hostIndex = (req, res) => { res.render('index', { currentName: lastAdded.name, currentName2: lastAdded2.name, title: 'Home', pageName: 'Home Page', }); }; const readAllCats = (req, res, callback) => { Cat.find(callback).lean(); }; const readAllDogs = (req, res, callback2) => { Dog.find(callback2).lean(); }; const readCat = (req, res) => { const name1 = req.query.name; const callback = (err, doc) => { if (err) { return res.status(500).json({ err }); } return res.json(doc); }; Cat.findByName(name1, callback); }; const readDog = (req, res) => { const name2 = req.query.name; const callback2 = (err, doc) => { if (err) { return res.status(500).json({ err }); } return res.json(doc); }; Dog.findByDogName(name2, callback2); }; const hostPage1 = (req, res) => { const callback = (err, docs) => { if (err) { return res.status(500).json({ err }); } return res.render('page1', { cats: docs }); }; readAllCats(req, res, callback); }; const hostPage3 = (req, res) => { const callback2 = (err, docs) => { if (err) { return res.status(500).json({ err }); } return res.render('page3', { dogs: docs }); }; readAllDogs(req, res, callback2); }; const hostPage2 = (req, res) => { res.render('page2'); }; const getName = (req, res) => { res.json({ name: lastAdded.name }); }; const setName = (req, res) => { if (!req.body.firstname || !req.body.lastname || !req.body.beds) { return res.status(400).json({ error: 'firstname, lastname and beds are all required' }); } const name = `${req.body.firstname} ${req.body.lastname}`; const catData = { name, bedsOwned: req.body.beds, }; const newCat = new Cat(catData); const savePromise = newCat.save(); savePromise.then(() => { lastAdded = newCat; res.json({ name: lastAdded.name, beds: lastAdded.bedsOwned }); }); savePromise.catch((err) => res.status(500).json({ err })); return res; }; const searchName = (req, res) => { if (!req.query.name) { return res.status(400).json({ error: 'Name is required to perform a search' }); } return Cat.findByName(req.query.name, (err, doc) => { if (err) { return res.status(500).json({ err }); } if (!doc) { return res.json({ error: 'No cats found' }); } return res.json({ name: doc.name, beds: doc.bedsOwned }); }); }; /// ////////////////////////////////////////////////////// const hostPage4 = (req, res) => { res.render('page4'); }; const getName2 = (req, res) => { res.json({ name2: lastAdded2.name }); }; const setName2 = (req, res) => { if (!req.body.firstname || !req.body.lastname || !req.body.age) { return res.status(400).json({ error: 'firstname, lastname and age are all required' }); } const name = `${req.body.firstname} ${req.body.lastname}`; const dogData = { name, age: req.body.age, }; const newDog = new Dog(dogData); const savePromise2 = newDog.save(); savePromise2.then(() => { lastAdded2 = newDog; res.json({ name: lastAdded2.name, age: lastAdded2.age }); }); savePromise2.catch((err) => res.status(500).json({ err })); return res; }; const searchDogName = (req, res) => { if (!req.query.name) { return res.status(400).json({ error: 'Name is required to perform a search' }); } return Dog.findByDogName(req.query.name, (err, doc) => { if (err) { return res.status(500).json({ err }); } if (!doc) { return res.json({ error: 'No dogs found' }); } return res.json({ name: doc.name, age: doc.age }); }); }; const updateLast = (req, res) => { lastAdded.bedsOwned++; lastAdded2.age++; const savePromise = lastAdded.save(); const savePromise2 = lastAdded2.save(); savePromise.then(() => res.json({ name: lastAdded.name, beds: lastAdded.bedsOwned })); savePromise2.then(() => res.json({ name: lastAdded2.name, age: lastAdded2.age })); savePromise.catch((err) => res.status(500).json({ err })); savePromise2.catch((err) => res.status(500).json({ err })); }; const notFound = (req, res) => { res.status(404).render('notFound', { page: req.url, }); }; module.exports = { index: hostIndex, page1: hostPage1, page2: hostPage2, page3: hostPage3, page4: hostPage4, readCat, readDog, getName, getName2, setName, setName2, updateLast, searchName, searchDogName, notFound, };
const express = require("express"); const puppeteer = require("puppeteer"); const app = express(); let browser; puppeteer .launch({ args: ["--no-sandbox"] }) .then( (subject) => (browser = subject), (e) => console.error(e), ); const getPageHTML = async (url) => { const page = await browser.newPage(); await page.goto(url, {waitUntil: 'networkidle0'}); const html = await page.content(); page.close(); return html; }; app.get("*", async (req, res, next) => { const url = `https://seoullatte.com${req.originalUrl}`; const start = new Date(); try { const html = await getPageHTML(url); res .set( "Server-Timing", `Prerender;dur=${new Date() - start};desc="Headless render time (ms)"`, ) .status(200) .send(html); } catch (e) { next(e); } }); app.listen(80, () => console.log("port 80"));
var Node = require('./Node'); /** * @constructor AssignmentNode * @extends {Node} * Define a symbol, like "a = 3.2" * * @param {String} name Symbol name * @param {Node} expr The expression defining the symbol */ function AssignmentNode(name, expr) { this.name = name; this.expr = expr; } AssignmentNode.prototype = new Node(); /** * Compile the node to javascript code * @param {Object} defs Object which can be used to define functions * or constants globally available for the compiled * expression * @private */ AssignmentNode.prototype._compile = function (defs) { return 'scope["' + this.name + '"] = ' + this.expr._compile(defs) + ''; }; /** * Find all nodes matching given filter * @param {Object} filter See Node.find for a description of the filter settings * @returns {Node[]} nodes */ AssignmentNode.prototype.find = function (filter) { var nodes = []; // check itself if (this.match(filter)) { nodes.push(this); } // search in expression if (this.expr) { nodes = nodes.concat(this.expr.find(filter)); } return nodes; }; /** * Get string representation * @return {String} */ AssignmentNode.prototype.toString = function() { return this.name + ' = ' + this.expr.toString(); }; module.exports = AssignmentNode;
/* Copyright (c) 2012 Andrey Mikhalevich, Katren ltd. */ /* Description */ //ф /** Requirements * @requires controls/ViewDialog.js */ /* constructor */ function ViewDocument(id,options){ options = options || {}; ViewDocument.superclass.constructor.call(this, id,options); var self = this; this.m_beforeOpen = function(contr,isInsert){ var doc_id = 0; if (!isInsert){ doc_id = self.getViewControl(self.getId()+"_id").getValue(); } contr.run("before_open",{async:false, params:{"doc_id":doc_id } }); } this.addDataControl( new EditNum(id+"_id", {"attrs":{"name":"id","value":"0"}, "visible":false}), {"modelId":options.readModelId, "valueFieldId":"id", "keyFieldIds":null}, {"valueFieldId":"id","keyFieldIds":null} ); this.addDataControl( new EditCheckBox(id+"_processed", {"attrs":{"name":"processed"}, "visible":false}), {"modelId":options.readModelId, "valueFieldId":"processed", "keyFieldIds":null}, {"valueFieldId":"processed","keyFieldIds":null} ); this.addDataControl( new EditNum(id+"_number", {"labelCaption":"Номер:","name":"number", "attrs":{"maxlength":5,"size":5,"disabled":"disabled"} } ), {"modelId":options.readModelId, "valueFieldId":"number", "keyFieldIds":null}, {"valueFieldId":null,"keyFieldIds":null} ); this.addDataControl( new EditDateTime(id+"_date_time", {"labelCaption":"Дата:","name":"date_time", "attrs":{"required":"required"}, "value":DateHandler.dateToStr(null,"dd/mm/y hh:mmin:ss") } ), {"modelId":options.readModelId, "valueFieldId":"date_time_descr", "keyFieldIds":null}, {"valueFieldId":"date_time","keyFieldIds":null} ); } extend(ViewDocument,ViewDialog); ViewDocument.prototype.m_detailContainer; ViewDocument.prototype.addDetailControl = function(detailControl){ if (this.m_details==undefined){ var detail_row = new ControlContainer(this.getId()+"_det_row","tr"); var td = new ControlContainer(this.getId()+"_det_row_col","td",{"attrs":{"colspan":"2"}}); detail_row.addElement(td); this.m_details = new ControlContainer(this.getId()+"_details","div",{"attrs":{"class":"tabber"}}); /* this.m_detailFilter = new ListFilter(); this.m_detailFilter.addFilter(this.getId()+"_detailFilter", {keyFieldIds:["doc_id"],valueFieldId:null,sign:"e"}); */ td.addElement(this.m_details); this.addElement(detail_row); } //var grid = detailControl.getGridControl(); //grid.setFilter(this.m_detailFilter); this.m_details.addElement(detailControl); } ViewDocument.prototype.getDetailControl = function(controlId){ return this.m_details.getElementById(controlId); } /* ViewDocument.prototype.toDOM = function(parent){ ViewDocument.superclass.toDOM.call(this,parent); if (this.m_details){ this.m_details.toDOM(parent); } } ViewDocument.prototype.removeDOM = function(){ if (this.m_details){ this.m_details.removeDOM(); } ViewDocument.superclass.removeDOM.call(this); } */ ViewDocument.prototype.readData = function(async,isCopy){ ViewDocument.superclass.readData.call(this,false,isCopy); /* if (this.m_detailFilter){ var node = this.getControl(this.getId()+"_id").control.m_node; this.m_detailFilter.setParamValue(this.getId()+"_detailFilter","key", node.getAttribute("old_id")); } */ } ViewDocument.prototype.onClickSave = function(){ var cmd_insert = this.getIsNew(); if (cmd_insert){ //need return new serial id if any var contr = this.getWriteController(); var meth_id = this.getWriteMethodId(); var pm = contr.getPublicMethodById(meth_id); if (pm.paramExists(contr.PARAM_RET_ID)){ pm.setParamValue(contr.PARAM_RET_ID,1); } } this.writeData(false); //this.readData(false); /* if (cmd_insert){ this.m_bindings[this.m_idPrefix+"processed"].control.setChecked(true); if (this.m_details){ for (var detail_id in this.m_details.m_elements){ var grid = this.m_details.m_elements[detail_id].getGridControl(); grid.onRefresh(); } } } */ } ViewDocument.prototype.getModified = function(){ var modif = ViewDocument.superclass.getModified.call(this); if (!modif){ //проверить табличные части modif = true; } return modif; } ViewDocument.prototype.setMethodParams = function(pm,checkRes){ pm.setParamValue("processed","true"); ViewDocument.superclass.setMethodParams.call(this,pm,checkRes); if (!checkRes.modif){ //проверить табличные части checkRes.modif = true; } }
'use strict'; const fs = require('fs'); const test = require('ava'); const transform = require('./index'); test.cb('toUpperCase()', t => { let str = ''; fs.createReadStream('README.md') .setEncoding('utf8') .pipe(transform(function * () { let chunk; while (Boolean(chunk = yield)) { this.push(chunk.toUpperCase()); } }, {decodeStrings: false})) .on('data', chunk => { str += chunk; }) .on('end', () => { t.is(fs.readFileSync('README.md', {encoding: 'utf8'}).toUpperCase(), str); t.end(); }); }); test.cb('error at generator', t => { fs.createReadStream('README.md') .pipe(transform(function * () { let chunk; while (Boolean(chunk = yield)) { this.push(chunk); throw new Error('SomeError'); } })) .on('error', error => { t.is(error.message, 'SomeError'); t.end(); }) .on('end', () => { t.fail(); }); });
const mongoose = require("mongoose") const inception_sunucu = new mongoose.Schema({ guild: String, ihlal: Number }) module.exports = mongoose.model("inception_sunucu", inception_sunucu)
/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./node_modules/alpinejs/dist/module.esm.js": /*!**************************************************!*\ !*** ./node_modules/alpinejs/dist/module.esm.js ***! \**************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ module_default) /* harmony export */ }); var __create = Object.create; var __defProp = Object.defineProperty; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __markAsModule = (target) => __defProp(target, "__esModule", {value: true}); var __commonJS = (callback, module) => () => { if (!module) { module = {exports: {}}; callback(module.exports, module); } return module.exports; }; var __exportStar = (target, module, desc) => { if (module && typeof module === "object" || typeof module === "function") { for (let key of __getOwnPropNames(module)) if (!__hasOwnProp.call(target, key) && key !== "default") __defProp(target, key, {get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable}); } return target; }; var __toModule = (module) => { return __exportStar(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", module && module.__esModule && "default" in module ? {get: () => module.default, enumerable: true} : {value: module, enumerable: true})), module); }; // node_modules/@vue/shared/dist/shared.cjs.js var require_shared_cjs = __commonJS((exports) => { "use strict"; Object.defineProperty(exports, "__esModule", {value: true}); function makeMap(str, expectsLowerCase) { const map = Object.create(null); const list = str.split(","); for (let i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? (val) => !!map[val.toLowerCase()] : (val) => !!map[val]; } var PatchFlagNames = { [1]: `TEXT`, [2]: `CLASS`, [4]: `STYLE`, [8]: `PROPS`, [16]: `FULL_PROPS`, [32]: `HYDRATE_EVENTS`, [64]: `STABLE_FRAGMENT`, [128]: `KEYED_FRAGMENT`, [256]: `UNKEYED_FRAGMENT`, [512]: `NEED_PATCH`, [1024]: `DYNAMIC_SLOTS`, [2048]: `DEV_ROOT_FRAGMENT`, [-1]: `HOISTED`, [-2]: `BAIL` }; var slotFlagsText = { [1]: "STABLE", [2]: "DYNAMIC", [3]: "FORWARDED" }; var GLOBALS_WHITE_LISTED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt"; var isGloballyWhitelisted = /* @__PURE__ */ makeMap(GLOBALS_WHITE_LISTED); var range = 2; function generateCodeFrame(source, start2 = 0, end = source.length) { const lines = source.split(/\r?\n/); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start2) { for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue; const line = j + 1; res.push(`${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); const lineLength = lines[j].length; if (j === i) { const pad = start2 - (count - lineLength) + 1; const length = Math.max(1, end > count ? lineLength - pad : end - start2); res.push(` | ` + " ".repeat(pad) + "^".repeat(length)); } else if (j > i) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); res.push(` | ` + "^".repeat(length)); } count += lineLength + 1; } } break; } } return res.join("\n"); } var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; var isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); var isBooleanAttr2 = /* @__PURE__ */ makeMap(specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`); var unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/; var attrValidationCache = {}; function isSSRSafeAttrName(name) { if (attrValidationCache.hasOwnProperty(name)) { return attrValidationCache[name]; } const isUnsafe = unsafeAttrCharRE.test(name); if (isUnsafe) { console.error(`unsafe attribute name: ${name}`); } return attrValidationCache[name] = !isUnsafe; } var propsToAttrMap = { acceptCharset: "accept-charset", className: "class", htmlFor: "for", httpEquiv: "http-equiv" }; var isNoUnitNumericStyleProp = /* @__PURE__ */ makeMap(`animation-iteration-count,border-image-outset,border-image-slice,border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,stroke-miterlimit,stroke-opacity,stroke-width`); var isKnownAttr = /* @__PURE__ */ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap`); function normalizeStyle(value) { if (isArray(value)) { const res = {}; for (let i = 0; i < value.length; i++) { const item = value[i]; const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item); if (normalized) { for (const key in normalized) { res[key] = normalized[key]; } } } return res; } else if (isObject(value)) { return value; } } var listDelimiterRE = /;(?![^(]*\))/g; var propertyDelimiterRE = /:(.+)/; function parseStringStyle(cssText) { const ret = {}; cssText.split(listDelimiterRE).forEach((item) => { if (item) { const tmp = item.split(propertyDelimiterRE); tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); } }); return ret; } function stringifyStyle(styles) { let ret = ""; if (!styles) { return ret; } for (const key in styles) { const value = styles[key]; const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); if (isString(value) || typeof value === "number" && isNoUnitNumericStyleProp(normalizedKey)) { ret += `${normalizedKey}:${value};`; } } return ret; } function normalizeClass(value) { let res = ""; if (isString(value)) { res = value; } else if (isArray(value)) { for (let i = 0; i < value.length; i++) { const normalized = normalizeClass(value[i]); if (normalized) { res += normalized + " "; } } } else if (isObject(value)) { for (const name in value) { if (value[name]) { res += name + " "; } } } return res.trim(); } var HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; var SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; var VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; var isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); var isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); var isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); var escapeRE = /["'&<>]/; function escapeHtml(string) { const str = "" + string; const match = escapeRE.exec(str); if (!match) { return str; } let html = ""; let escaped; let index; let lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: escaped = "&quot;"; break; case 38: escaped = "&amp;"; break; case 39: escaped = "&#39;"; break; case 60: escaped = "&lt;"; break; case 62: escaped = "&gt;"; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escaped; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } var commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g; function escapeHtmlComment(src) { return src.replace(commentStripRE, ""); } function looseCompareArrays(a, b) { if (a.length !== b.length) return false; let equal = true; for (let i = 0; equal && i < a.length; i++) { equal = looseEqual(a[i], b[i]); } return equal; } function looseEqual(a, b) { if (a === b) return true; let aValidType = isDate(a); let bValidType = isDate(b); if (aValidType || bValidType) { return aValidType && bValidType ? a.getTime() === b.getTime() : false; } aValidType = isArray(a); bValidType = isArray(b); if (aValidType || bValidType) { return aValidType && bValidType ? looseCompareArrays(a, b) : false; } aValidType = isObject(a); bValidType = isObject(b); if (aValidType || bValidType) { if (!aValidType || !bValidType) { return false; } const aKeysCount = Object.keys(a).length; const bKeysCount = Object.keys(b).length; if (aKeysCount !== bKeysCount) { return false; } for (const key in a) { const aHasKey = a.hasOwnProperty(key); const bHasKey = b.hasOwnProperty(key); if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) { return false; } } } return String(a) === String(b); } function looseIndexOf(arr, val) { return arr.findIndex((item) => looseEqual(item, val)); } var toDisplayString = (val) => { return val == null ? "" : isObject(val) ? JSON.stringify(val, replacer, 2) : String(val); }; var replacer = (_key, val) => { if (isMap(val)) { return { [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2]) => { entries[`${key} =>`] = val2; return entries; }, {}) }; } else if (isSet(val)) { return { [`Set(${val.size})`]: [...val.values()] }; } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) { return String(val); } return val; }; var babelParserDefaultPlugins = [ "bigInt", "optionalChaining", "nullishCoalescingOperator" ]; var EMPTY_OBJ = Object.freeze({}); var EMPTY_ARR = Object.freeze([]); var NOOP = () => { }; var NO = () => false; var onRE = /^on[^a-z]/; var isOn = (key) => onRE.test(key); var isModelListener = (key) => key.startsWith("onUpdate:"); var extend = Object.assign; var remove = (arr, el) => { const i = arr.indexOf(el); if (i > -1) { arr.splice(i, 1); } }; var hasOwnProperty = Object.prototype.hasOwnProperty; var hasOwn = (val, key) => hasOwnProperty.call(val, key); var isArray = Array.isArray; var isMap = (val) => toTypeString(val) === "[object Map]"; var isSet = (val) => toTypeString(val) === "[object Set]"; var isDate = (val) => val instanceof Date; var isFunction = (val) => typeof val === "function"; var isString = (val) => typeof val === "string"; var isSymbol = (val) => typeof val === "symbol"; var isObject = (val) => val !== null && typeof val === "object"; var isPromise = (val) => { return isObject(val) && isFunction(val.then) && isFunction(val.catch); }; var objectToString = Object.prototype.toString; var toTypeString = (value) => objectToString.call(value); var toRawType = (value) => { return toTypeString(value).slice(8, -1); }; var isPlainObject = (val) => toTypeString(val) === "[object Object]"; var isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; var isReservedProp = /* @__PURE__ */ makeMap(",key,ref,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"); var cacheStringFunction = (fn) => { const cache = Object.create(null); return (str) => { const hit = cache[str]; return hit || (cache[str] = fn(str)); }; }; var camelizeRE = /-(\w)/g; var camelize = cacheStringFunction((str) => { return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); }); var hyphenateRE = /\B([A-Z])/g; var hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase()); var capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1)); var toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``); var hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue); var invokeArrayFns = (fns, arg) => { for (let i = 0; i < fns.length; i++) { fns[i](arg); } }; var def = (obj, key, value) => { Object.defineProperty(obj, key, { configurable: true, enumerable: false, value }); }; var toNumber = (val) => { const n = parseFloat(val); return isNaN(n) ? val : n; }; var _globalThis; var getGlobalThis = () => { return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : {}); }; exports.EMPTY_ARR = EMPTY_ARR; exports.EMPTY_OBJ = EMPTY_OBJ; exports.NO = NO; exports.NOOP = NOOP; exports.PatchFlagNames = PatchFlagNames; exports.babelParserDefaultPlugins = babelParserDefaultPlugins; exports.camelize = camelize; exports.capitalize = capitalize; exports.def = def; exports.escapeHtml = escapeHtml; exports.escapeHtmlComment = escapeHtmlComment; exports.extend = extend; exports.generateCodeFrame = generateCodeFrame; exports.getGlobalThis = getGlobalThis; exports.hasChanged = hasChanged; exports.hasOwn = hasOwn; exports.hyphenate = hyphenate; exports.invokeArrayFns = invokeArrayFns; exports.isArray = isArray; exports.isBooleanAttr = isBooleanAttr2; exports.isDate = isDate; exports.isFunction = isFunction; exports.isGloballyWhitelisted = isGloballyWhitelisted; exports.isHTMLTag = isHTMLTag; exports.isIntegerKey = isIntegerKey; exports.isKnownAttr = isKnownAttr; exports.isMap = isMap; exports.isModelListener = isModelListener; exports.isNoUnitNumericStyleProp = isNoUnitNumericStyleProp; exports.isObject = isObject; exports.isOn = isOn; exports.isPlainObject = isPlainObject; exports.isPromise = isPromise; exports.isReservedProp = isReservedProp; exports.isSSRSafeAttrName = isSSRSafeAttrName; exports.isSVGTag = isSVGTag; exports.isSet = isSet; exports.isSpecialBooleanAttr = isSpecialBooleanAttr; exports.isString = isString; exports.isSymbol = isSymbol; exports.isVoidTag = isVoidTag; exports.looseEqual = looseEqual; exports.looseIndexOf = looseIndexOf; exports.makeMap = makeMap; exports.normalizeClass = normalizeClass; exports.normalizeStyle = normalizeStyle; exports.objectToString = objectToString; exports.parseStringStyle = parseStringStyle; exports.propsToAttrMap = propsToAttrMap; exports.remove = remove; exports.slotFlagsText = slotFlagsText; exports.stringifyStyle = stringifyStyle; exports.toDisplayString = toDisplayString; exports.toHandlerKey = toHandlerKey; exports.toNumber = toNumber; exports.toRawType = toRawType; exports.toTypeString = toTypeString; }); // node_modules/@vue/shared/index.js var require_shared = __commonJS((exports, module) => { "use strict"; if (false) {} else { module.exports = require_shared_cjs(); } }); // node_modules/@vue/reactivity/dist/reactivity.cjs.js var require_reactivity_cjs = __commonJS((exports) => { "use strict"; Object.defineProperty(exports, "__esModule", {value: true}); var shared = require_shared(); var targetMap = new WeakMap(); var effectStack = []; var activeEffect; var ITERATE_KEY = Symbol("iterate"); var MAP_KEY_ITERATE_KEY = Symbol("Map key iterate"); function isEffect(fn) { return fn && fn._isEffect === true; } function effect3(fn, options = shared.EMPTY_OBJ) { if (isEffect(fn)) { fn = fn.raw; } const effect4 = createReactiveEffect(fn, options); if (!options.lazy) { effect4(); } return effect4; } function stop2(effect4) { if (effect4.active) { cleanup(effect4); if (effect4.options.onStop) { effect4.options.onStop(); } effect4.active = false; } } var uid = 0; function createReactiveEffect(fn, options) { const effect4 = function reactiveEffect() { if (!effect4.active) { return fn(); } if (!effectStack.includes(effect4)) { cleanup(effect4); try { enableTracking(); effectStack.push(effect4); activeEffect = effect4; return fn(); } finally { effectStack.pop(); resetTracking(); activeEffect = effectStack[effectStack.length - 1]; } } }; effect4.id = uid++; effect4.allowRecurse = !!options.allowRecurse; effect4._isEffect = true; effect4.active = true; effect4.raw = fn; effect4.deps = []; effect4.options = options; return effect4; } function cleanup(effect4) { const {deps} = effect4; if (deps.length) { for (let i = 0; i < deps.length; i++) { deps[i].delete(effect4); } deps.length = 0; } } var shouldTrack = true; var trackStack = []; function pauseTracking() { trackStack.push(shouldTrack); shouldTrack = false; } function enableTracking() { trackStack.push(shouldTrack); shouldTrack = true; } function resetTracking() { const last = trackStack.pop(); shouldTrack = last === void 0 ? true : last; } function track(target, type, key) { if (!shouldTrack || activeEffect === void 0) { return; } let depsMap = targetMap.get(target); if (!depsMap) { targetMap.set(target, depsMap = new Map()); } let dep = depsMap.get(key); if (!dep) { depsMap.set(key, dep = new Set()); } if (!dep.has(activeEffect)) { dep.add(activeEffect); activeEffect.deps.push(dep); if (activeEffect.options.onTrack) { activeEffect.options.onTrack({ effect: activeEffect, target, type, key }); } } } function trigger(target, type, key, newValue, oldValue, oldTarget) { const depsMap = targetMap.get(target); if (!depsMap) { return; } const effects = new Set(); const add2 = (effectsToAdd) => { if (effectsToAdd) { effectsToAdd.forEach((effect4) => { if (effect4 !== activeEffect || effect4.allowRecurse) { effects.add(effect4); } }); } }; if (type === "clear") { depsMap.forEach(add2); } else if (key === "length" && shared.isArray(target)) { depsMap.forEach((dep, key2) => { if (key2 === "length" || key2 >= newValue) { add2(dep); } }); } else { if (key !== void 0) { add2(depsMap.get(key)); } switch (type) { case "add": if (!shared.isArray(target)) { add2(depsMap.get(ITERATE_KEY)); if (shared.isMap(target)) { add2(depsMap.get(MAP_KEY_ITERATE_KEY)); } } else if (shared.isIntegerKey(key)) { add2(depsMap.get("length")); } break; case "delete": if (!shared.isArray(target)) { add2(depsMap.get(ITERATE_KEY)); if (shared.isMap(target)) { add2(depsMap.get(MAP_KEY_ITERATE_KEY)); } } break; case "set": if (shared.isMap(target)) { add2(depsMap.get(ITERATE_KEY)); } break; } } const run = (effect4) => { if (effect4.options.onTrigger) { effect4.options.onTrigger({ effect: effect4, target, key, type, newValue, oldValue, oldTarget }); } if (effect4.options.scheduler) { effect4.options.scheduler(effect4); } else { effect4(); } }; effects.forEach(run); } var isNonTrackableKeys = /* @__PURE__ */ shared.makeMap(`__proto__,__v_isRef,__isVue`); var builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol).map((key) => Symbol[key]).filter(shared.isSymbol)); var get2 = /* @__PURE__ */ createGetter(); var shallowGet = /* @__PURE__ */ createGetter(false, true); var readonlyGet = /* @__PURE__ */ createGetter(true); var shallowReadonlyGet = /* @__PURE__ */ createGetter(true, true); var arrayInstrumentations = {}; ["includes", "indexOf", "lastIndexOf"].forEach((key) => { const method = Array.prototype[key]; arrayInstrumentations[key] = function(...args) { const arr = toRaw2(this); for (let i = 0, l = this.length; i < l; i++) { track(arr, "get", i + ""); } const res = method.apply(arr, args); if (res === -1 || res === false) { return method.apply(arr, args.map(toRaw2)); } else { return res; } }; }); ["push", "pop", "shift", "unshift", "splice"].forEach((key) => { const method = Array.prototype[key]; arrayInstrumentations[key] = function(...args) { pauseTracking(); const res = method.apply(this, args); resetTracking(); return res; }; }); function createGetter(isReadonly2 = false, shallow = false) { return function get3(target, key, receiver) { if (key === "__v_isReactive") { return !isReadonly2; } else if (key === "__v_isReadonly") { return isReadonly2; } else if (key === "__v_raw" && receiver === (isReadonly2 ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap).get(target)) { return target; } const targetIsArray = shared.isArray(target); if (!isReadonly2 && targetIsArray && shared.hasOwn(arrayInstrumentations, key)) { return Reflect.get(arrayInstrumentations, key, receiver); } const res = Reflect.get(target, key, receiver); if (shared.isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { return res; } if (!isReadonly2) { track(target, "get", key); } if (shallow) { return res; } if (isRef(res)) { const shouldUnwrap = !targetIsArray || !shared.isIntegerKey(key); return shouldUnwrap ? res.value : res; } if (shared.isObject(res)) { return isReadonly2 ? readonly(res) : reactive3(res); } return res; }; } var set2 = /* @__PURE__ */ createSetter(); var shallowSet = /* @__PURE__ */ createSetter(true); function createSetter(shallow = false) { return function set3(target, key, value, receiver) { let oldValue = target[key]; if (!shallow) { value = toRaw2(value); oldValue = toRaw2(oldValue); if (!shared.isArray(target) && isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } } const hadKey = shared.isArray(target) && shared.isIntegerKey(key) ? Number(key) < target.length : shared.hasOwn(target, key); const result = Reflect.set(target, key, value, receiver); if (target === toRaw2(receiver)) { if (!hadKey) { trigger(target, "add", key, value); } else if (shared.hasChanged(value, oldValue)) { trigger(target, "set", key, value, oldValue); } } return result; }; } function deleteProperty(target, key) { const hadKey = shared.hasOwn(target, key); const oldValue = target[key]; const result = Reflect.deleteProperty(target, key); if (result && hadKey) { trigger(target, "delete", key, void 0, oldValue); } return result; } function has(target, key) { const result = Reflect.has(target, key); if (!shared.isSymbol(key) || !builtInSymbols.has(key)) { track(target, "has", key); } return result; } function ownKeys(target) { track(target, "iterate", shared.isArray(target) ? "length" : ITERATE_KEY); return Reflect.ownKeys(target); } var mutableHandlers = { get: get2, set: set2, deleteProperty, has, ownKeys }; var readonlyHandlers = { get: readonlyGet, set(target, key) { { console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target); } return true; }, deleteProperty(target, key) { { console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target); } return true; } }; var shallowReactiveHandlers = shared.extend({}, mutableHandlers, { get: shallowGet, set: shallowSet }); var shallowReadonlyHandlers = shared.extend({}, readonlyHandlers, { get: shallowReadonlyGet }); var toReactive = (value) => shared.isObject(value) ? reactive3(value) : value; var toReadonly = (value) => shared.isObject(value) ? readonly(value) : value; var toShallow = (value) => value; var getProto = (v) => Reflect.getPrototypeOf(v); function get$1(target, key, isReadonly2 = false, isShallow = false) { target = target["__v_raw"]; const rawTarget = toRaw2(target); const rawKey = toRaw2(key); if (key !== rawKey) { !isReadonly2 && track(rawTarget, "get", key); } !isReadonly2 && track(rawTarget, "get", rawKey); const {has: has2} = getProto(rawTarget); const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive; if (has2.call(rawTarget, key)) { return wrap(target.get(key)); } else if (has2.call(rawTarget, rawKey)) { return wrap(target.get(rawKey)); } else if (target !== rawTarget) { target.get(key); } } function has$1(key, isReadonly2 = false) { const target = this["__v_raw"]; const rawTarget = toRaw2(target); const rawKey = toRaw2(key); if (key !== rawKey) { !isReadonly2 && track(rawTarget, "has", key); } !isReadonly2 && track(rawTarget, "has", rawKey); return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); } function size(target, isReadonly2 = false) { target = target["__v_raw"]; !isReadonly2 && track(toRaw2(target), "iterate", ITERATE_KEY); return Reflect.get(target, "size", target); } function add(value) { value = toRaw2(value); const target = toRaw2(this); const proto = getProto(target); const hadKey = proto.has.call(target, value); if (!hadKey) { target.add(value); trigger(target, "add", value, value); } return this; } function set$1(key, value) { value = toRaw2(value); const target = toRaw2(this); const {has: has2, get: get3} = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw2(key); hadKey = has2.call(target, key); } else { checkIdentityKeys(target, has2, key); } const oldValue = get3.call(target, key); target.set(key, value); if (!hadKey) { trigger(target, "add", key, value); } else if (shared.hasChanged(value, oldValue)) { trigger(target, "set", key, value, oldValue); } return this; } function deleteEntry(key) { const target = toRaw2(this); const {has: has2, get: get3} = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw2(key); hadKey = has2.call(target, key); } else { checkIdentityKeys(target, has2, key); } const oldValue = get3 ? get3.call(target, key) : void 0; const result = target.delete(key); if (hadKey) { trigger(target, "delete", key, void 0, oldValue); } return result; } function clear() { const target = toRaw2(this); const hadItems = target.size !== 0; const oldTarget = shared.isMap(target) ? new Map(target) : new Set(target); const result = target.clear(); if (hadItems) { trigger(target, "clear", void 0, void 0, oldTarget); } return result; } function createForEach(isReadonly2, isShallow) { return function forEach(callback, thisArg) { const observed = this; const target = observed["__v_raw"]; const rawTarget = toRaw2(target); const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive; !isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY); return target.forEach((value, key) => { return callback.call(thisArg, wrap(value), wrap(key), observed); }); }; } function createIterableMethod(method, isReadonly2, isShallow) { return function(...args) { const target = this["__v_raw"]; const rawTarget = toRaw2(target); const targetIsMap = shared.isMap(rawTarget); const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; const isKeyOnly = method === "keys" && targetIsMap; const innerIterator = target[method](...args); const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive; !isReadonly2 && track(rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY); return { next() { const {value, done} = innerIterator.next(); return done ? {value, done} : { value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), done }; }, [Symbol.iterator]() { return this; } }; }; } function createReadonlyMethod(type) { return function(...args) { { const key = args[0] ? `on key "${args[0]}" ` : ``; console.warn(`${shared.capitalize(type)} operation ${key}failed: target is readonly.`, toRaw2(this)); } return type === "delete" ? false : this; }; } var mutableInstrumentations = { get(key) { return get$1(this, key); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, false) }; var shallowInstrumentations = { get(key) { return get$1(this, key, false, true); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, true) }; var readonlyInstrumentations = { get(key) { return get$1(this, key, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, false) }; var shallowReadonlyInstrumentations = { get(key) { return get$1(this, key, true, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, true) }; var iteratorMethods = ["keys", "values", "entries", Symbol.iterator]; iteratorMethods.forEach((method) => { mutableInstrumentations[method] = createIterableMethod(method, false, false); readonlyInstrumentations[method] = createIterableMethod(method, true, false); shallowInstrumentations[method] = createIterableMethod(method, false, true); shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true); }); function createInstrumentationGetter(isReadonly2, shallow) { const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations; return (target, key, receiver) => { if (key === "__v_isReactive") { return !isReadonly2; } else if (key === "__v_isReadonly") { return isReadonly2; } else if (key === "__v_raw") { return target; } return Reflect.get(shared.hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver); }; } var mutableCollectionHandlers = { get: createInstrumentationGetter(false, false) }; var shallowCollectionHandlers = { get: createInstrumentationGetter(false, true) }; var readonlyCollectionHandlers = { get: createInstrumentationGetter(true, false) }; var shallowReadonlyCollectionHandlers = { get: createInstrumentationGetter(true, true) }; function checkIdentityKeys(target, has2, key) { const rawKey = toRaw2(key); if (rawKey !== key && has2.call(target, rawKey)) { const type = shared.toRawType(target); console.warn(`Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.`); } } var reactiveMap = new WeakMap(); var shallowReactiveMap = new WeakMap(); var readonlyMap = new WeakMap(); var shallowReadonlyMap = new WeakMap(); function targetTypeMap(rawType) { switch (rawType) { case "Object": case "Array": return 1; case "Map": case "Set": case "WeakMap": case "WeakSet": return 2; default: return 0; } } function getTargetType(value) { return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(shared.toRawType(value)); } function reactive3(target) { if (target && target["__v_isReadonly"]) { return target; } return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap); } function shallowReactive(target) { return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap); } function readonly(target) { return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap); } function shallowReadonly(target) { return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap); } function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { if (!shared.isObject(target)) { { console.warn(`value cannot be made reactive: ${String(target)}`); } return target; } if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { return target; } const existingProxy = proxyMap.get(target); if (existingProxy) { return existingProxy; } const targetType = getTargetType(target); if (targetType === 0) { return target; } const proxy = new Proxy(target, targetType === 2 ? collectionHandlers : baseHandlers); proxyMap.set(target, proxy); return proxy; } function isReactive2(value) { if (isReadonly(value)) { return isReactive2(value["__v_raw"]); } return !!(value && value["__v_isReactive"]); } function isReadonly(value) { return !!(value && value["__v_isReadonly"]); } function isProxy(value) { return isReactive2(value) || isReadonly(value); } function toRaw2(observed) { return observed && toRaw2(observed["__v_raw"]) || observed; } function markRaw(value) { shared.def(value, "__v_skip", true); return value; } var convert = (val) => shared.isObject(val) ? reactive3(val) : val; function isRef(r) { return Boolean(r && r.__v_isRef === true); } function ref(value) { return createRef(value); } function shallowRef(value) { return createRef(value, true); } var RefImpl = class { constructor(_rawValue, _shallow = false) { this._rawValue = _rawValue; this._shallow = _shallow; this.__v_isRef = true; this._value = _shallow ? _rawValue : convert(_rawValue); } get value() { track(toRaw2(this), "get", "value"); return this._value; } set value(newVal) { if (shared.hasChanged(toRaw2(newVal), this._rawValue)) { this._rawValue = newVal; this._value = this._shallow ? newVal : convert(newVal); trigger(toRaw2(this), "set", "value", newVal); } } }; function createRef(rawValue, shallow = false) { if (isRef(rawValue)) { return rawValue; } return new RefImpl(rawValue, shallow); } function triggerRef(ref2) { trigger(toRaw2(ref2), "set", "value", ref2.value); } function unref(ref2) { return isRef(ref2) ? ref2.value : ref2; } var shallowUnwrapHandlers = { get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)), set: (target, key, value, receiver) => { const oldValue = target[key]; if (isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } else { return Reflect.set(target, key, value, receiver); } } }; function proxyRefs(objectWithRefs) { return isReactive2(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); } var CustomRefImpl = class { constructor(factory) { this.__v_isRef = true; const {get: get3, set: set3} = factory(() => track(this, "get", "value"), () => trigger(this, "set", "value")); this._get = get3; this._set = set3; } get value() { return this._get(); } set value(newVal) { this._set(newVal); } }; function customRef(factory) { return new CustomRefImpl(factory); } function toRefs(object) { if (!isProxy(object)) { console.warn(`toRefs() expects a reactive object but received a plain one.`); } const ret = shared.isArray(object) ? new Array(object.length) : {}; for (const key in object) { ret[key] = toRef(object, key); } return ret; } var ObjectRefImpl = class { constructor(_object, _key) { this._object = _object; this._key = _key; this.__v_isRef = true; } get value() { return this._object[this._key]; } set value(newVal) { this._object[this._key] = newVal; } }; function toRef(object, key) { return isRef(object[key]) ? object[key] : new ObjectRefImpl(object, key); } var ComputedRefImpl = class { constructor(getter, _setter, isReadonly2) { this._setter = _setter; this._dirty = true; this.__v_isRef = true; this.effect = effect3(getter, { lazy: true, scheduler: () => { if (!this._dirty) { this._dirty = true; trigger(toRaw2(this), "set", "value"); } } }); this["__v_isReadonly"] = isReadonly2; } get value() { const self2 = toRaw2(this); if (self2._dirty) { self2._value = this.effect(); self2._dirty = false; } track(self2, "get", "value"); return self2._value; } set value(newValue) { this._setter(newValue); } }; function computed(getterOrOptions) { let getter; let setter; if (shared.isFunction(getterOrOptions)) { getter = getterOrOptions; setter = () => { console.warn("Write operation failed: computed value is readonly"); }; } else { getter = getterOrOptions.get; setter = getterOrOptions.set; } return new ComputedRefImpl(getter, setter, shared.isFunction(getterOrOptions) || !getterOrOptions.set); } exports.ITERATE_KEY = ITERATE_KEY; exports.computed = computed; exports.customRef = customRef; exports.effect = effect3; exports.enableTracking = enableTracking; exports.isProxy = isProxy; exports.isReactive = isReactive2; exports.isReadonly = isReadonly; exports.isRef = isRef; exports.markRaw = markRaw; exports.pauseTracking = pauseTracking; exports.proxyRefs = proxyRefs; exports.reactive = reactive3; exports.readonly = readonly; exports.ref = ref; exports.resetTracking = resetTracking; exports.shallowReactive = shallowReactive; exports.shallowReadonly = shallowReadonly; exports.shallowRef = shallowRef; exports.stop = stop2; exports.toRaw = toRaw2; exports.toRef = toRef; exports.toRefs = toRefs; exports.track = track; exports.trigger = trigger; exports.triggerRef = triggerRef; exports.unref = unref; }); // node_modules/@vue/reactivity/index.js var require_reactivity = __commonJS((exports, module) => { "use strict"; if (false) {} else { module.exports = require_reactivity_cjs(); } }); // packages/alpinejs/src/scheduler.js var flushPending = false; var flushing = false; var queue = []; function scheduler(callback) { queueJob(callback); } function queueJob(job) { if (!queue.includes(job)) queue.push(job); queueFlush(); } function queueFlush() { if (!flushing && !flushPending) { flushPending = true; queueMicrotask(flushJobs); } } function flushJobs() { flushPending = false; flushing = true; for (let i = 0; i < queue.length; i++) { queue[i](); } queue.length = 0; flushing = false; } // packages/alpinejs/src/reactivity.js var reactive; var effect; var release; var raw; var shouldSchedule = true; function disableEffectScheduling(callback) { shouldSchedule = false; callback(); shouldSchedule = true; } function setReactivityEngine(engine) { reactive = engine.reactive; release = engine.release; effect = (callback) => engine.effect(callback, {scheduler: (task) => { if (shouldSchedule) { scheduler(task); } else { task(); } }}); raw = engine.raw; } function overrideEffect(override) { effect = override; } function elementBoundEffect(el) { let cleanup = () => { }; let wrappedEffect = (callback) => { let effectReference = effect(callback); if (!el._x_effects) { el._x_effects = new Set(); el._x_runEffects = () => { el._x_effects.forEach((i) => i()); }; } el._x_effects.add(effectReference); cleanup = () => { if (effectReference === void 0) return; el._x_effects.delete(effectReference); release(effectReference); }; }; return [wrappedEffect, () => { cleanup(); }]; } // packages/alpinejs/src/mutation.js var onAttributeAddeds = []; var onElRemoveds = []; var onElAddeds = []; function onElAdded(callback) { onElAddeds.push(callback); } function onElRemoved(callback) { onElRemoveds.push(callback); } function onAttributesAdded(callback) { onAttributeAddeds.push(callback); } function onAttributeRemoved(el, name, callback) { if (!el._x_attributeCleanups) el._x_attributeCleanups = {}; if (!el._x_attributeCleanups[name]) el._x_attributeCleanups[name] = []; el._x_attributeCleanups[name].push(callback); } function cleanupAttributes(el, names) { if (!el._x_attributeCleanups) return; Object.entries(el._x_attributeCleanups).forEach(([name, value]) => { if (names === void 0 || names.includes(name)) { value.forEach((i) => i()); delete el._x_attributeCleanups[name]; } }); } var observer = new MutationObserver(onMutate); var currentlyObserving = false; function startObservingMutations() { observer.observe(document, {subtree: true, childList: true, attributes: true, attributeOldValue: true}); currentlyObserving = true; } function stopObservingMutations() { flushObserver(); observer.disconnect(); currentlyObserving = false; } var recordQueue = []; var willProcessRecordQueue = false; function flushObserver() { recordQueue = recordQueue.concat(observer.takeRecords()); if (recordQueue.length && !willProcessRecordQueue) { willProcessRecordQueue = true; queueMicrotask(() => { processRecordQueue(); willProcessRecordQueue = false; }); } } function processRecordQueue() { onMutate(recordQueue); recordQueue.length = 0; } function mutateDom(callback) { if (!currentlyObserving) return callback(); stopObservingMutations(); let result = callback(); startObservingMutations(); return result; } var isCollecting = false; var deferredMutations = []; function deferMutations() { isCollecting = true; } function flushAndStopDeferringMutations() { isCollecting = false; onMutate(deferredMutations); deferredMutations = []; } function onMutate(mutations) { if (isCollecting) { deferredMutations = deferredMutations.concat(mutations); return; } let addedNodes = []; let removedNodes = []; let addedAttributes = new Map(); let removedAttributes = new Map(); for (let i = 0; i < mutations.length; i++) { if (mutations[i].target._x_ignoreMutationObserver) continue; if (mutations[i].type === "childList") { mutations[i].addedNodes.forEach((node) => node.nodeType === 1 && addedNodes.push(node)); mutations[i].removedNodes.forEach((node) => node.nodeType === 1 && removedNodes.push(node)); } if (mutations[i].type === "attributes") { let el = mutations[i].target; let name = mutations[i].attributeName; let oldValue = mutations[i].oldValue; let add = () => { if (!addedAttributes.has(el)) addedAttributes.set(el, []); addedAttributes.get(el).push({name, value: el.getAttribute(name)}); }; let remove = () => { if (!removedAttributes.has(el)) removedAttributes.set(el, []); removedAttributes.get(el).push(name); }; if (el.hasAttribute(name) && oldValue === null) { add(); } else if (el.hasAttribute(name)) { remove(); add(); } else { remove(); } } } removedAttributes.forEach((attrs, el) => { cleanupAttributes(el, attrs); }); addedAttributes.forEach((attrs, el) => { onAttributeAddeds.forEach((i) => i(el, attrs)); }); for (let node of addedNodes) { if (removedNodes.includes(node)) continue; onElAddeds.forEach((i) => i(node)); } for (let node of removedNodes) { if (addedNodes.includes(node)) continue; onElRemoveds.forEach((i) => i(node)); } addedNodes = null; removedNodes = null; addedAttributes = null; removedAttributes = null; } // packages/alpinejs/src/scope.js function addScopeToNode(node, data2, referenceNode) { node._x_dataStack = [data2, ...closestDataStack(referenceNode || node)]; return () => { node._x_dataStack = node._x_dataStack.filter((i) => i !== data2); }; } function refreshScope(element, scope) { let existingScope = element._x_dataStack[0]; Object.entries(scope).forEach(([key, value]) => { existingScope[key] = value; }); } function closestDataStack(node) { if (node._x_dataStack) return node._x_dataStack; if (typeof ShadowRoot === "function" && node instanceof ShadowRoot) { return closestDataStack(node.host); } if (!node.parentNode) { return []; } return closestDataStack(node.parentNode); } function mergeProxies(objects) { let thisProxy = new Proxy({}, { ownKeys: () => { return Array.from(new Set(objects.flatMap((i) => Object.keys(i)))); }, has: (target, name) => { return objects.some((obj) => obj.hasOwnProperty(name)); }, get: (target, name) => { return (objects.find((obj) => { if (obj.hasOwnProperty(name)) { let descriptor = Object.getOwnPropertyDescriptor(obj, name); if (descriptor.get && descriptor.get._x_alreadyBound || descriptor.set && descriptor.set._x_alreadyBound) { return true; } if ((descriptor.get || descriptor.set) && descriptor.enumerable) { let getter = descriptor.get; let setter = descriptor.set; let property = descriptor; getter = getter && getter.bind(thisProxy); setter = setter && setter.bind(thisProxy); if (getter) getter._x_alreadyBound = true; if (setter) setter._x_alreadyBound = true; Object.defineProperty(obj, name, { ...property, get: getter, set: setter }); } return true; } return false; }) || {})[name]; }, set: (target, name, value) => { let closestObjectWithKey = objects.find((obj) => obj.hasOwnProperty(name)); if (closestObjectWithKey) { closestObjectWithKey[name] = value; } else { objects[objects.length - 1][name] = value; } return true; } }); return thisProxy; } // packages/alpinejs/src/interceptor.js function initInterceptors(data2) { let isObject = (val) => typeof val === "object" && !Array.isArray(val) && val !== null; let recurse = (obj, basePath = "") => { Object.entries(obj).forEach(([key, value]) => { let path = basePath === "" ? key : `${basePath}.${key}`; if (typeof value === "object" && value !== null && value._x_interceptor) { obj[key] = value.initialize(data2, path, key); } else { if (isObject(value) && value !== obj && !(value instanceof Element)) { recurse(value, path); } } }); }; return recurse(data2); } function interceptor(callback, mutateObj = () => { }) { let obj = { initialValue: void 0, _x_interceptor: true, initialize(data2, path, key) { return callback(this.initialValue, () => get(data2, path), (value) => set(data2, path, value), path, key); } }; mutateObj(obj); return (initialValue) => { if (typeof initialValue === "object" && initialValue !== null && initialValue._x_interceptor) { let initialize = obj.initialize.bind(obj); obj.initialize = (data2, path, key) => { let innerValue = initialValue.initialize(data2, path, key); obj.initialValue = innerValue; return initialize(data2, path, key); }; } else { obj.initialValue = initialValue; } return obj; }; } function get(obj, path) { return path.split(".").reduce((carry, segment) => carry[segment], obj); } function set(obj, path, value) { if (typeof path === "string") path = path.split("."); if (path.length === 1) obj[path[0]] = value; else if (path.length === 0) throw error; else { if (obj[path[0]]) return set(obj[path[0]], path.slice(1), value); else { obj[path[0]] = {}; return set(obj[path[0]], path.slice(1), value); } } } // packages/alpinejs/src/magics.js var magics = {}; function magic(name, callback) { magics[name] = callback; } function injectMagics(obj, el) { Object.entries(magics).forEach(([name, callback]) => { Object.defineProperty(obj, `$${name}`, { get() { return callback(el, {Alpine: alpine_default, interceptor}); }, enumerable: false }); }); return obj; } // packages/alpinejs/src/evaluator.js function evaluate(el, expression, extras = {}) { let result; evaluateLater(el, expression)((value) => result = value, extras); return result; } function evaluateLater(...args) { return theEvaluatorFunction(...args); } var theEvaluatorFunction = normalEvaluator; function setEvaluator(newEvaluator) { theEvaluatorFunction = newEvaluator; } function normalEvaluator(el, expression) { let overriddenMagics = {}; injectMagics(overriddenMagics, el); let dataStack = [overriddenMagics, ...closestDataStack(el)]; if (typeof expression === "function") { return generateEvaluatorFromFunction(dataStack, expression); } let evaluator = generateEvaluatorFromString(dataStack, expression); return tryCatch.bind(null, el, expression, evaluator); } function generateEvaluatorFromFunction(dataStack, func) { return (receiver = () => { }, {scope = {}, params = []} = {}) => { let result = func.apply(mergeProxies([scope, ...dataStack]), params); runIfTypeOfFunction(receiver, result); }; } var evaluatorMemo = {}; function generateFunctionFromString(expression) { if (evaluatorMemo[expression]) { return evaluatorMemo[expression]; } let AsyncFunction = Object.getPrototypeOf(async function() { }).constructor; let rightSideSafeExpression = /^[\n\s]*if.*\(.*\)/.test(expression) || /^(let|const)/.test(expression) ? `(() => { ${expression} })()` : expression; let func = new AsyncFunction(["__self", "scope"], `with (scope) { __self.result = ${rightSideSafeExpression} }; __self.finished = true; return __self.result;`); evaluatorMemo[expression] = func; return func; } function generateEvaluatorFromString(dataStack, expression) { let func = generateFunctionFromString(expression); return (receiver = () => { }, {scope = {}, params = []} = {}) => { func.result = void 0; func.finished = false; let completeScope = mergeProxies([scope, ...dataStack]); let promise = func(func, completeScope); if (func.finished) { runIfTypeOfFunction(receiver, func.result, completeScope, params); } else { promise.then((result) => { runIfTypeOfFunction(receiver, result, completeScope, params); }); } }; } function runIfTypeOfFunction(receiver, value, scope, params) { if (typeof value === "function") { let result = value.apply(scope, params); if (result instanceof Promise) { result.then((i) => runIfTypeOfFunction(receiver, i, scope, params)); } else { receiver(result); } } else { receiver(value); } } function tryCatch(el, expression, callback, ...args) { try { return callback(...args); } catch (e) { console.warn(`Alpine Expression Error: ${e.message} Expression: "${expression}" `, el); throw e; } } // packages/alpinejs/src/directives.js var prefixAsString = "x-"; function prefix(subject = "") { return prefixAsString + subject; } function setPrefix(newPrefix) { prefixAsString = newPrefix; } var directiveHandlers = {}; function directive(name, callback) { directiveHandlers[name] = callback; } function directives(el, attributes, originalAttributeOverride) { let transformedAttributeMap = {}; let directives2 = Array.from(attributes).map(toTransformedAttributes((newName, oldName) => transformedAttributeMap[newName] = oldName)).filter(outNonAlpineAttributes).map(toParsedDirectives(transformedAttributeMap, originalAttributeOverride)).sort(byPriority); return directives2.map((directive2) => { return getDirectiveHandler(el, directive2); }); } function attributesOnly(attributes) { return Array.from(attributes).map(toTransformedAttributes()).filter((attr) => !outNonAlpineAttributes(attr)); } var isDeferringHandlers = false; var directiveHandlerStacks = new Map(); var currentHandlerStackKey = Symbol(); function deferHandlingDirectives(callback) { isDeferringHandlers = true; let key = Symbol(); currentHandlerStackKey = key; directiveHandlerStacks.set(key, []); let flushHandlers = () => { while (directiveHandlerStacks.get(key).length) directiveHandlerStacks.get(key).shift()(); directiveHandlerStacks.delete(key); }; let stopDeferring = () => { isDeferringHandlers = false; flushHandlers(); }; callback(flushHandlers); stopDeferring(); } function getDirectiveHandler(el, directive2) { let noop = () => { }; let handler3 = directiveHandlers[directive2.type] || noop; let cleanups = []; let cleanup = (callback) => cleanups.push(callback); let [effect3, cleanupEffect] = elementBoundEffect(el); cleanups.push(cleanupEffect); let utilities = { Alpine: alpine_default, effect: effect3, cleanup, evaluateLater: evaluateLater.bind(evaluateLater, el), evaluate: evaluate.bind(evaluate, el) }; let doCleanup = () => cleanups.forEach((i) => i()); onAttributeRemoved(el, directive2.original, doCleanup); let fullHandler = () => { if (el._x_ignore || el._x_ignoreSelf) return; handler3.inline && handler3.inline(el, directive2, utilities); handler3 = handler3.bind(handler3, el, directive2, utilities); isDeferringHandlers ? directiveHandlerStacks.get(currentHandlerStackKey).push(handler3) : handler3(); }; fullHandler.runCleanups = doCleanup; return fullHandler; } var startingWith = (subject, replacement) => ({name, value}) => { if (name.startsWith(subject)) name = name.replace(subject, replacement); return {name, value}; }; var into = (i) => i; function toTransformedAttributes(callback = () => { }) { return ({name, value}) => { let {name: newName, value: newValue} = attributeTransformers.reduce((carry, transform) => { return transform(carry); }, {name, value}); if (newName !== name) callback(newName, name); return {name: newName, value: newValue}; }; } var attributeTransformers = []; function mapAttributes(callback) { attributeTransformers.push(callback); } function outNonAlpineAttributes({name}) { return alpineAttributeRegex().test(name); } var alpineAttributeRegex = () => new RegExp(`^${prefixAsString}([^:^.]+)\\b`); function toParsedDirectives(transformedAttributeMap, originalAttributeOverride) { return ({name, value}) => { let typeMatch = name.match(alpineAttributeRegex()); let valueMatch = name.match(/:([a-zA-Z0-9\-:]+)/); let modifiers = name.match(/\.[^.\]]+(?=[^\]]*$)/g) || []; let original = originalAttributeOverride || transformedAttributeMap[name] || name; return { type: typeMatch ? typeMatch[1] : null, value: valueMatch ? valueMatch[1] : null, modifiers: modifiers.map((i) => i.replace(".", "")), expression: value, original }; }; } var DEFAULT = "DEFAULT"; var directiveOrder = [ "ignore", "ref", "data", "bind", "init", "for", "model", "transition", "show", "if", DEFAULT, "element" ]; function byPriority(a, b) { let typeA = directiveOrder.indexOf(a.type) === -1 ? DEFAULT : a.type; let typeB = directiveOrder.indexOf(b.type) === -1 ? DEFAULT : b.type; return directiveOrder.indexOf(typeA) - directiveOrder.indexOf(typeB); } // packages/alpinejs/src/utils/dispatch.js function dispatch(el, name, detail = {}) { el.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true, cancelable: true })); } // packages/alpinejs/src/nextTick.js var tickStack = []; var isHolding = false; function nextTick(callback) { tickStack.push(callback); queueMicrotask(() => { isHolding || setTimeout(() => { releaseNextTicks(); }); }); } function releaseNextTicks() { isHolding = false; while (tickStack.length) tickStack.shift()(); } function holdNextTicks() { isHolding = true; } // packages/alpinejs/src/utils/walk.js function walk(el, callback) { if (typeof ShadowRoot === "function" && el instanceof ShadowRoot) { Array.from(el.children).forEach((el2) => walk(el2, callback)); return; } let skip = false; callback(el, () => skip = true); if (skip) return; let node = el.firstElementChild; while (node) { walk(node, callback, false); node = node.nextElementSibling; } } // packages/alpinejs/src/utils/warn.js function warn(message, ...args) { console.warn(`Alpine Warning: ${message}`, ...args); } // packages/alpinejs/src/lifecycle.js function start() { if (!document.body) warn("Unable to initialize. Trying to load Alpine before `<body>` is available. Did you forget to add `defer` in Alpine's `<script>` tag?"); dispatch(document, "alpine:init"); dispatch(document, "alpine:initializing"); startObservingMutations(); onElAdded((el) => initTree(el, walk)); onElRemoved((el) => nextTick(() => destroyTree(el))); onAttributesAdded((el, attrs) => { directives(el, attrs).forEach((handle) => handle()); }); let outNestedComponents = (el) => !closestRoot(el.parentElement, true); Array.from(document.querySelectorAll(allSelectors())).filter(outNestedComponents).forEach((el) => { initTree(el); }); dispatch(document, "alpine:initialized"); } var rootSelectorCallbacks = []; var initSelectorCallbacks = []; function rootSelectors() { return rootSelectorCallbacks.map((fn) => fn()); } function allSelectors() { return rootSelectorCallbacks.concat(initSelectorCallbacks).map((fn) => fn()); } function addRootSelector(selectorCallback) { rootSelectorCallbacks.push(selectorCallback); } function addInitSelector(selectorCallback) { initSelectorCallbacks.push(selectorCallback); } function closestRoot(el, includeInitSelectors = false) { if (!el) return; const selectors = includeInitSelectors ? allSelectors() : rootSelectors(); if (selectors.some((selector) => el.matches(selector))) return el; if (!el.parentElement) return; return closestRoot(el.parentElement, includeInitSelectors); } function isRoot(el) { return rootSelectors().some((selector) => el.matches(selector)); } function initTree(el, walker = walk) { deferHandlingDirectives(() => { walker(el, (el2, skip) => { directives(el2, el2.attributes).forEach((handle) => handle()); el2._x_ignore && skip(); }); }); } function destroyTree(root) { walk(root, (el) => cleanupAttributes(el)); } // packages/alpinejs/src/utils/classes.js function setClasses(el, value) { if (Array.isArray(value)) { return setClassesFromString(el, value.join(" ")); } else if (typeof value === "object" && value !== null) { return setClassesFromObject(el, value); } else if (typeof value === "function") { return setClasses(el, value()); } return setClassesFromString(el, value); } function setClassesFromString(el, classString) { let split = (classString2) => classString2.split(" ").filter(Boolean); let missingClasses = (classString2) => classString2.split(" ").filter((i) => !el.classList.contains(i)).filter(Boolean); let addClassesAndReturnUndo = (classes) => { el.classList.add(...classes); return () => { el.classList.remove(...classes); }; }; classString = classString === true ? classString = "" : classString || ""; return addClassesAndReturnUndo(missingClasses(classString)); } function setClassesFromObject(el, classObject) { let split = (classString) => classString.split(" ").filter(Boolean); let forAdd = Object.entries(classObject).flatMap(([classString, bool]) => bool ? split(classString) : false).filter(Boolean); let forRemove = Object.entries(classObject).flatMap(([classString, bool]) => !bool ? split(classString) : false).filter(Boolean); let added = []; let removed = []; forRemove.forEach((i) => { if (el.classList.contains(i)) { el.classList.remove(i); removed.push(i); } }); forAdd.forEach((i) => { if (!el.classList.contains(i)) { el.classList.add(i); added.push(i); } }); return () => { removed.forEach((i) => el.classList.add(i)); added.forEach((i) => el.classList.remove(i)); }; } // packages/alpinejs/src/utils/styles.js function setStyles(el, value) { if (typeof value === "object" && value !== null) { return setStylesFromObject(el, value); } return setStylesFromString(el, value); } function setStylesFromObject(el, value) { let previousStyles = {}; Object.entries(value).forEach(([key, value2]) => { previousStyles[key] = el.style[key]; el.style.setProperty(kebabCase(key), value2); }); setTimeout(() => { if (el.style.length === 0) { el.removeAttribute("style"); } }); return () => { setStyles(el, previousStyles); }; } function setStylesFromString(el, value) { let cache = el.getAttribute("style", value); el.setAttribute("style", value); return () => { el.setAttribute("style", cache); }; } function kebabCase(subject) { return subject.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); } // packages/alpinejs/src/utils/once.js function once(callback, fallback = () => { }) { let called = false; return function() { if (!called) { called = true; callback.apply(this, arguments); } else { fallback.apply(this, arguments); } }; } // packages/alpinejs/src/directives/x-transition.js directive("transition", (el, {value, modifiers, expression}, {evaluate: evaluate2}) => { if (typeof expression === "function") expression = evaluate2(expression); if (!expression) { registerTransitionsFromHelper(el, modifiers, value); } else { registerTransitionsFromClassString(el, expression, value); } }); function registerTransitionsFromClassString(el, classString, stage) { registerTransitionObject(el, setClasses, ""); let directiveStorageMap = { enter: (classes) => { el._x_transition.enter.during = classes; }, "enter-start": (classes) => { el._x_transition.enter.start = classes; }, "enter-end": (classes) => { el._x_transition.enter.end = classes; }, leave: (classes) => { el._x_transition.leave.during = classes; }, "leave-start": (classes) => { el._x_transition.leave.start = classes; }, "leave-end": (classes) => { el._x_transition.leave.end = classes; } }; directiveStorageMap[stage](classString); } function registerTransitionsFromHelper(el, modifiers, stage) { registerTransitionObject(el, setStyles); let doesntSpecify = !modifiers.includes("in") && !modifiers.includes("out") && !stage; let transitioningIn = doesntSpecify || modifiers.includes("in") || ["enter"].includes(stage); let transitioningOut = doesntSpecify || modifiers.includes("out") || ["leave"].includes(stage); if (modifiers.includes("in") && !doesntSpecify) { modifiers = modifiers.filter((i, index) => index < modifiers.indexOf("out")); } if (modifiers.includes("out") && !doesntSpecify) { modifiers = modifiers.filter((i, index) => index > modifiers.indexOf("out")); } let wantsAll = !modifiers.includes("opacity") && !modifiers.includes("scale"); let wantsOpacity = wantsAll || modifiers.includes("opacity"); let wantsScale = wantsAll || modifiers.includes("scale"); let opacityValue = wantsOpacity ? 0 : 1; let scaleValue = wantsScale ? modifierValue(modifiers, "scale", 95) / 100 : 1; let delay = modifierValue(modifiers, "delay", 0); let origin = modifierValue(modifiers, "origin", "center"); let property = "opacity, transform"; let durationIn = modifierValue(modifiers, "duration", 150) / 1e3; let durationOut = modifierValue(modifiers, "duration", 75) / 1e3; let easing = `cubic-bezier(0.4, 0.0, 0.2, 1)`; if (transitioningIn) { el._x_transition.enter.during = { transformOrigin: origin, transitionDelay: delay, transitionProperty: property, transitionDuration: `${durationIn}s`, transitionTimingFunction: easing }; el._x_transition.enter.start = { opacity: opacityValue, transform: `scale(${scaleValue})` }; el._x_transition.enter.end = { opacity: 1, transform: `scale(1)` }; } if (transitioningOut) { el._x_transition.leave.during = { transformOrigin: origin, transitionDelay: delay, transitionProperty: property, transitionDuration: `${durationOut}s`, transitionTimingFunction: easing }; el._x_transition.leave.start = { opacity: 1, transform: `scale(1)` }; el._x_transition.leave.end = { opacity: opacityValue, transform: `scale(${scaleValue})` }; } } function registerTransitionObject(el, setFunction, defaultValue = {}) { if (!el._x_transition) el._x_transition = { enter: {during: defaultValue, start: defaultValue, end: defaultValue}, leave: {during: defaultValue, start: defaultValue, end: defaultValue}, in(before = () => { }, after = () => { }) { transition(el, setFunction, { during: this.enter.during, start: this.enter.start, end: this.enter.end }, before, after); }, out(before = () => { }, after = () => { }) { transition(el, setFunction, { during: this.leave.during, start: this.leave.start, end: this.leave.end }, before, after); } }; } window.Element.prototype._x_toggleAndCascadeWithTransitions = function(el, value, show, hide) { let clickAwayCompatibleShow = () => { document.visibilityState === "visible" ? requestAnimationFrame(show) : setTimeout(show); }; if (value) { el._x_transition ? el._x_transition.in(show) : clickAwayCompatibleShow(); return; } el._x_hidePromise = el._x_transition ? new Promise((resolve, reject) => { el._x_transition.out(() => { }, () => resolve(hide)); el._x_transitioning.beforeCancel(() => reject({isFromCancelledTransition: true})); }) : Promise.resolve(hide); queueMicrotask(() => { let closest = closestHide(el); if (closest) { if (!closest._x_hideChildren) closest._x_hideChildren = []; closest._x_hideChildren.push(el); } else { queueMicrotask(() => { let hideAfterChildren = (el2) => { let carry = Promise.all([ el2._x_hidePromise, ...(el2._x_hideChildren || []).map(hideAfterChildren) ]).then(([i]) => i()); delete el2._x_hidePromise; delete el2._x_hideChildren; return carry; }; hideAfterChildren(el).catch((e) => { if (!e.isFromCancelledTransition) throw e; }); }); } }); }; function closestHide(el) { let parent = el.parentNode; if (!parent) return; return parent._x_hidePromise ? parent : closestHide(parent); } function transition(el, setFunction, {during, start: start2, end} = {}, before = () => { }, after = () => { }) { if (el._x_transitioning) el._x_transitioning.cancel(); if (Object.keys(during).length === 0 && Object.keys(start2).length === 0 && Object.keys(end).length === 0) { before(); after(); return; } let undoStart, undoDuring, undoEnd; performTransition(el, { start() { undoStart = setFunction(el, start2); }, during() { undoDuring = setFunction(el, during); }, before, end() { undoStart(); undoEnd = setFunction(el, end); }, after, cleanup() { undoDuring(); undoEnd(); } }); } function performTransition(el, stages) { let interrupted, reachedBefore, reachedEnd; let finish = once(() => { mutateDom(() => { interrupted = true; if (!reachedBefore) stages.before(); if (!reachedEnd) { stages.end(); releaseNextTicks(); } stages.after(); if (el.isConnected) stages.cleanup(); delete el._x_transitioning; }); }); el._x_transitioning = { beforeCancels: [], beforeCancel(callback) { this.beforeCancels.push(callback); }, cancel: once(function() { while (this.beforeCancels.length) { this.beforeCancels.shift()(); } ; finish(); }), finish }; mutateDom(() => { stages.start(); stages.during(); }); holdNextTicks(); requestAnimationFrame(() => { if (interrupted) return; let duration = Number(getComputedStyle(el).transitionDuration.replace(/,.*/, "").replace("s", "")) * 1e3; let delay = Number(getComputedStyle(el).transitionDelay.replace(/,.*/, "").replace("s", "")) * 1e3; if (duration === 0) duration = Number(getComputedStyle(el).animationDuration.replace("s", "")) * 1e3; mutateDom(() => { stages.before(); }); reachedBefore = true; requestAnimationFrame(() => { if (interrupted) return; mutateDom(() => { stages.end(); }); releaseNextTicks(); setTimeout(el._x_transitioning.finish, duration + delay); reachedEnd = true; }); }); } function modifierValue(modifiers, key, fallback) { if (modifiers.indexOf(key) === -1) return fallback; const rawValue = modifiers[modifiers.indexOf(key) + 1]; if (!rawValue) return fallback; if (key === "scale") { if (isNaN(rawValue)) return fallback; } if (key === "duration") { let match = rawValue.match(/([0-9]+)ms/); if (match) return match[1]; } if (key === "origin") { if (["top", "right", "left", "center", "bottom"].includes(modifiers[modifiers.indexOf(key) + 2])) { return [rawValue, modifiers[modifiers.indexOf(key) + 2]].join(" "); } } return rawValue; } // packages/alpinejs/src/utils/debounce.js function debounce(func, wait) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; func.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; } // packages/alpinejs/src/utils/throttle.js function throttle(func, limit) { let inThrottle; return function() { let context = this, args = arguments; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } // packages/alpinejs/src/plugin.js function plugin(callback) { callback(alpine_default); } // packages/alpinejs/src/store.js var stores = {}; var isReactive = false; function store(name, value) { if (!isReactive) { stores = reactive(stores); isReactive = true; } if (value === void 0) { return stores[name]; } stores[name] = value; if (typeof value === "object" && value !== null && value.hasOwnProperty("init") && typeof value.init === "function") { stores[name].init(); } } function getStores() { return stores; } // packages/alpinejs/src/clone.js var isCloning = false; function skipDuringClone(callback) { return (...args) => isCloning || callback(...args); } function clone(oldEl, newEl) { newEl._x_dataStack = oldEl._x_dataStack; isCloning = true; dontRegisterReactiveSideEffects(() => { cloneTree(newEl); }); isCloning = false; } function cloneTree(el) { let hasRunThroughFirstEl = false; let shallowWalker = (el2, callback) => { walk(el2, (el3, skip) => { if (hasRunThroughFirstEl && isRoot(el3)) return skip(); hasRunThroughFirstEl = true; callback(el3, skip); }); }; initTree(el, shallowWalker); } function dontRegisterReactiveSideEffects(callback) { let cache = effect; overrideEffect((callback2, el) => { let storedEffect = cache(callback2); release(storedEffect); return () => { }; }); callback(); overrideEffect(cache); } // packages/alpinejs/src/datas.js var datas = {}; function data(name, callback) { datas[name] = callback; } function injectDataProviders(obj, context) { Object.entries(datas).forEach(([name, callback]) => { Object.defineProperty(obj, name, { get() { return (...args) => { return callback.bind(context)(...args); }; }, enumerable: false }); }); return obj; } // packages/alpinejs/src/alpine.js var Alpine = { get reactive() { return reactive; }, get release() { return release; }, get effect() { return effect; }, get raw() { return raw; }, version: "3.4.2", flushAndStopDeferringMutations, disableEffectScheduling, setReactivityEngine, addRootSelector, deferMutations, mapAttributes, evaluateLater, setEvaluator, closestRoot, interceptor, transition, setStyles, mutateDom, directive, throttle, debounce, evaluate, initTree, nextTick, prefix: setPrefix, plugin, magic, store, start, clone, data }; var alpine_default = Alpine; // packages/alpinejs/src/index.js var import_reactivity9 = __toModule(require_reactivity()); // packages/alpinejs/src/magics/$nextTick.js magic("nextTick", () => nextTick); // packages/alpinejs/src/magics/$dispatch.js magic("dispatch", (el) => dispatch.bind(dispatch, el)); // packages/alpinejs/src/magics/$watch.js magic("watch", (el) => (key, callback) => { let evaluate2 = evaluateLater(el, key); let firstTime = true; let oldValue; effect(() => evaluate2((value) => { let div = document.createElement("div"); div.dataset.throwAway = value; if (!firstTime) { queueMicrotask(() => { callback(value, oldValue); oldValue = value; }); } else { oldValue = value; } firstTime = false; })); }); // packages/alpinejs/src/magics/$store.js magic("store", getStores); // packages/alpinejs/src/magics/$root.js magic("root", (el) => closestRoot(el)); // packages/alpinejs/src/magics/$refs.js magic("refs", (el) => { if (el._x_refs_proxy) return el._x_refs_proxy; el._x_refs_proxy = mergeProxies(getArrayOfRefObject(el)); return el._x_refs_proxy; }); function getArrayOfRefObject(el) { let refObjects = []; let currentEl = el; while (currentEl) { if (currentEl._x_refs) refObjects.push(currentEl._x_refs); currentEl = currentEl.parentNode; } return refObjects; } // packages/alpinejs/src/magics/$el.js magic("el", (el) => el); // packages/alpinejs/src/directives/x-ignore.js var handler = () => { }; handler.inline = (el, {modifiers}, {cleanup}) => { modifiers.includes("self") ? el._x_ignoreSelf = true : el._x_ignore = true; cleanup(() => { modifiers.includes("self") ? delete el._x_ignoreSelf : delete el._x_ignore; }); }; directive("ignore", handler); // packages/alpinejs/src/directives/x-effect.js directive("effect", (el, {expression}, {effect: effect3}) => effect3(evaluateLater(el, expression))); // packages/alpinejs/src/utils/bind.js function bind(el, name, value, modifiers = []) { if (!el._x_bindings) el._x_bindings = reactive({}); el._x_bindings[name] = value; name = modifiers.includes("camel") ? camelCase(name) : name; switch (name) { case "value": bindInputValue(el, value); break; case "style": bindStyles(el, value); break; case "class": bindClasses(el, value); break; default: bindAttribute(el, name, value); break; } } function bindInputValue(el, value) { if (el.type === "radio") { if (el.attributes.value === void 0) { el.value = value; } if (window.fromModel) { el.checked = checkedAttrLooseCompare(el.value, value); } } else if (el.type === "checkbox") { if (Number.isInteger(value)) { el.value = value; } else if (!Number.isInteger(value) && !Array.isArray(value) && typeof value !== "boolean" && ![null, void 0].includes(value)) { el.value = String(value); } else { if (Array.isArray(value)) { el.checked = value.some((val) => checkedAttrLooseCompare(val, el.value)); } else { el.checked = !!value; } } } else if (el.tagName === "SELECT") { updateSelect(el, value); } else { if (el.value === value) return; el.value = value; } } function bindClasses(el, value) { if (el._x_undoAddedClasses) el._x_undoAddedClasses(); el._x_undoAddedClasses = setClasses(el, value); } function bindStyles(el, value) { if (el._x_undoAddedStyles) el._x_undoAddedStyles(); el._x_undoAddedStyles = setStyles(el, value); } function bindAttribute(el, name, value) { if ([null, void 0, false].includes(value) && attributeShouldntBePreservedIfFalsy(name)) { el.removeAttribute(name); } else { if (isBooleanAttr(name)) value = name; setIfChanged(el, name, value); } } function setIfChanged(el, attrName, value) { if (el.getAttribute(attrName) != value) { el.setAttribute(attrName, value); } } function updateSelect(el, value) { const arrayWrappedValue = [].concat(value).map((value2) => { return value2 + ""; }); Array.from(el.options).forEach((option) => { option.selected = arrayWrappedValue.includes(option.value); }); } function camelCase(subject) { return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase()); } function checkedAttrLooseCompare(valueA, valueB) { return valueA == valueB; } function isBooleanAttr(attrName) { const booleanAttributes = [ "disabled", "checked", "required", "readonly", "hidden", "open", "selected", "autofocus", "itemscope", "multiple", "novalidate", "allowfullscreen", "allowpaymentrequest", "formnovalidate", "autoplay", "controls", "loop", "muted", "playsinline", "default", "ismap", "reversed", "async", "defer", "nomodule" ]; return booleanAttributes.includes(attrName); } function attributeShouldntBePreservedIfFalsy(name) { return !["aria-pressed", "aria-checked", "aria-expanded"].includes(name); } // packages/alpinejs/src/utils/on.js function on(el, event, modifiers, callback) { let listenerTarget = el; let handler3 = (e) => callback(e); let options = {}; let wrapHandler = (callback2, wrapper) => (e) => wrapper(callback2, e); if (modifiers.includes("dot")) event = dotSyntax(event); if (modifiers.includes("camel")) event = camelCase2(event); if (modifiers.includes("passive")) options.passive = true; if (modifiers.includes("capture")) options.capture = true; if (modifiers.includes("window")) listenerTarget = window; if (modifiers.includes("document")) listenerTarget = document; if (modifiers.includes("prevent")) handler3 = wrapHandler(handler3, (next, e) => { e.preventDefault(); next(e); }); if (modifiers.includes("stop")) handler3 = wrapHandler(handler3, (next, e) => { e.stopPropagation(); next(e); }); if (modifiers.includes("self")) handler3 = wrapHandler(handler3, (next, e) => { e.target === el && next(e); }); if (modifiers.includes("away") || modifiers.includes("outside")) { listenerTarget = document; handler3 = wrapHandler(handler3, (next, e) => { if (el.contains(e.target)) return; if (el.offsetWidth < 1 && el.offsetHeight < 1) return; next(e); }); } handler3 = wrapHandler(handler3, (next, e) => { if (isKeyEvent(event)) { if (isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers)) { return; } } next(e); }); if (modifiers.includes("debounce")) { let nextModifier = modifiers[modifiers.indexOf("debounce") + 1] || "invalid-wait"; let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250; handler3 = debounce(handler3, wait); } if (modifiers.includes("throttle")) { let nextModifier = modifiers[modifiers.indexOf("throttle") + 1] || "invalid-wait"; let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250; handler3 = throttle(handler3, wait); } if (modifiers.includes("once")) { handler3 = wrapHandler(handler3, (next, e) => { next(e); listenerTarget.removeEventListener(event, handler3, options); }); } listenerTarget.addEventListener(event, handler3, options); return () => { listenerTarget.removeEventListener(event, handler3, options); }; } function dotSyntax(subject) { return subject.replace(/-/g, "."); } function camelCase2(subject) { return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase()); } function isNumeric(subject) { return !Array.isArray(subject) && !isNaN(subject); } function kebabCase2(subject) { return subject.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[_\s]/, "-").toLowerCase(); } function isKeyEvent(event) { return ["keydown", "keyup"].includes(event); } function isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers) { let keyModifiers = modifiers.filter((i) => { return !["window", "document", "prevent", "stop", "once"].includes(i); }); if (keyModifiers.includes("debounce")) { let debounceIndex = keyModifiers.indexOf("debounce"); keyModifiers.splice(debounceIndex, isNumeric((keyModifiers[debounceIndex + 1] || "invalid-wait").split("ms")[0]) ? 2 : 1); } if (keyModifiers.length === 0) return false; if (keyModifiers.length === 1 && keyToModifiers(e.key).includes(keyModifiers[0])) return false; const systemKeyModifiers = ["ctrl", "shift", "alt", "meta", "cmd", "super"]; const selectedSystemKeyModifiers = systemKeyModifiers.filter((modifier) => keyModifiers.includes(modifier)); keyModifiers = keyModifiers.filter((i) => !selectedSystemKeyModifiers.includes(i)); if (selectedSystemKeyModifiers.length > 0) { const activelyPressedKeyModifiers = selectedSystemKeyModifiers.filter((modifier) => { if (modifier === "cmd" || modifier === "super") modifier = "meta"; return e[`${modifier}Key`]; }); if (activelyPressedKeyModifiers.length === selectedSystemKeyModifiers.length) { if (keyToModifiers(e.key).includes(keyModifiers[0])) return false; } } return true; } function keyToModifiers(key) { if (!key) return []; key = kebabCase2(key); let modifierToKeyMap = { ctrl: "control", slash: "/", space: "-", spacebar: "-", cmd: "meta", esc: "escape", up: "arrow-up", down: "arrow-down", left: "arrow-left", right: "arrow-right", period: ".", equal: "=" }; modifierToKeyMap[key] = key; return Object.keys(modifierToKeyMap).map((modifier) => { if (modifierToKeyMap[modifier] === key) return modifier; }).filter((modifier) => modifier); } // packages/alpinejs/src/directives/x-model.js directive("model", (el, {modifiers, expression}, {effect: effect3, cleanup}) => { let evaluate2 = evaluateLater(el, expression); let assignmentExpression = `${expression} = rightSideOfExpression($event, ${expression})`; let evaluateAssignment = evaluateLater(el, assignmentExpression); var event = el.tagName.toLowerCase() === "select" || ["checkbox", "radio"].includes(el.type) || modifiers.includes("lazy") ? "change" : "input"; let assigmentFunction = generateAssignmentFunction(el, modifiers, expression); let removeListener = on(el, event, modifiers, (e) => { evaluateAssignment(() => { }, {scope: { $event: e, rightSideOfExpression: assigmentFunction }}); }); cleanup(() => removeListener()); el._x_forceModelUpdate = () => { evaluate2((value) => { if (value === void 0 && expression.match(/\./)) value = ""; window.fromModel = true; mutateDom(() => bind(el, "value", value)); delete window.fromModel; }); }; effect3(() => { if (modifiers.includes("unintrusive") && document.activeElement.isSameNode(el)) return; el._x_forceModelUpdate(); }); }); function generateAssignmentFunction(el, modifiers, expression) { if (el.type === "radio") { mutateDom(() => { if (!el.hasAttribute("name")) el.setAttribute("name", expression); }); } return (event, currentValue) => { return mutateDom(() => { if (event instanceof CustomEvent && event.detail !== void 0) { return event.detail || event.target.value; } else if (el.type === "checkbox") { if (Array.isArray(currentValue)) { let newValue = modifiers.includes("number") ? safeParseNumber(event.target.value) : event.target.value; return event.target.checked ? currentValue.concat([newValue]) : currentValue.filter((el2) => !checkedAttrLooseCompare2(el2, newValue)); } else { return event.target.checked; } } else if (el.tagName.toLowerCase() === "select" && el.multiple) { return modifiers.includes("number") ? Array.from(event.target.selectedOptions).map((option) => { let rawValue = option.value || option.text; return safeParseNumber(rawValue); }) : Array.from(event.target.selectedOptions).map((option) => { return option.value || option.text; }); } else { let rawValue = event.target.value; return modifiers.includes("number") ? safeParseNumber(rawValue) : modifiers.includes("trim") ? rawValue.trim() : rawValue; } }); }; } function safeParseNumber(rawValue) { let number = rawValue ? parseFloat(rawValue) : null; return isNumeric2(number) ? number : rawValue; } function checkedAttrLooseCompare2(valueA, valueB) { return valueA == valueB; } function isNumeric2(subject) { return !Array.isArray(subject) && !isNaN(subject); } // packages/alpinejs/src/directives/x-cloak.js directive("cloak", (el) => queueMicrotask(() => mutateDom(() => el.removeAttribute(prefix("cloak"))))); // packages/alpinejs/src/directives/x-init.js addInitSelector(() => `[${prefix("init")}]`); directive("init", skipDuringClone((el, {expression}) => { if (typeof expression === "string") { return !!expression.trim() && evaluate(el, expression, {}, false); } return evaluate(el, expression, {}, false); })); // packages/alpinejs/src/directives/x-text.js directive("text", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => { let evaluate2 = evaluateLater2(expression); effect3(() => { evaluate2((value) => { mutateDom(() => { el.textContent = value; }); }); }); }); // packages/alpinejs/src/directives/x-html.js directive("html", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => { let evaluate2 = evaluateLater2(expression); effect3(() => { evaluate2((value) => { el.innerHTML = value; }); }); }); // packages/alpinejs/src/directives/x-bind.js mapAttributes(startingWith(":", into(prefix("bind:")))); directive("bind", (el, {value, modifiers, expression, original}, {effect: effect3}) => { if (!value) return applyBindingsObject(el, expression, original, effect3); if (value === "key") return storeKeyForXFor(el, expression); let evaluate2 = evaluateLater(el, expression); effect3(() => evaluate2((result) => { if (result === void 0 && expression.match(/\./)) result = ""; mutateDom(() => bind(el, value, result, modifiers)); })); }); function applyBindingsObject(el, expression, original, effect3) { let getBindings = evaluateLater(el, expression); let cleanupRunners = []; effect3(() => { while (cleanupRunners.length) cleanupRunners.pop()(); getBindings((bindings) => { let attributes = Object.entries(bindings).map(([name, value]) => ({name, value})); attributesOnly(attributes).forEach(({name, value}, index) => { attributes[index] = { name: `x-bind:${name}`, value: `"${value}"` }; }); directives(el, attributes, original).map((handle) => { cleanupRunners.push(handle.runCleanups); handle(); }); }); }); } function storeKeyForXFor(el, expression) { el._x_keyExpression = expression; } // packages/alpinejs/src/directives/x-data.js addRootSelector(() => `[${prefix("data")}]`); directive("data", skipDuringClone((el, {expression}, {cleanup}) => { expression = expression === "" ? "{}" : expression; let magicContext = {}; injectMagics(magicContext, el); let dataProviderContext = {}; injectDataProviders(dataProviderContext, magicContext); let data2 = evaluate(el, expression, {scope: dataProviderContext}); injectMagics(data2, el); let reactiveData = reactive(data2); initInterceptors(reactiveData); let undo = addScopeToNode(el, reactiveData); reactiveData["init"] && evaluate(el, reactiveData["init"]); cleanup(() => { undo(); reactiveData["destroy"] && evaluate(el, reactiveData["destroy"]); }); })); // packages/alpinejs/src/directives/x-show.js directive("show", (el, {modifiers, expression}, {effect: effect3}) => { let evaluate2 = evaluateLater(el, expression); let hide = () => mutateDom(() => { el.style.display = "none"; el._x_isShown = false; }); let show = () => mutateDom(() => { if (el.style.length === 1 && el.style.display === "none") { el.removeAttribute("style"); } else { el.style.removeProperty("display"); } el._x_isShown = true; }); let clickAwayCompatibleShow = () => setTimeout(show); let toggle = once((value) => value ? show() : hide(), (value) => { if (typeof el._x_toggleAndCascadeWithTransitions === "function") { el._x_toggleAndCascadeWithTransitions(el, value, show, hide); } else { value ? clickAwayCompatibleShow() : hide(); } }); let oldValue; let firstTime = true; effect3(() => evaluate2((value) => { if (!firstTime && value === oldValue) return; if (modifiers.includes("immediate")) value ? clickAwayCompatibleShow() : hide(); toggle(value); oldValue = value; firstTime = false; })); }); // packages/alpinejs/src/directives/x-for.js directive("for", (el, {expression}, {effect: effect3, cleanup}) => { let iteratorNames = parseForExpression(expression); let evaluateItems = evaluateLater(el, iteratorNames.items); let evaluateKey = evaluateLater(el, el._x_keyExpression || "index"); el._x_prevKeys = []; el._x_lookup = {}; effect3(() => loop(el, iteratorNames, evaluateItems, evaluateKey)); cleanup(() => { Object.values(el._x_lookup).forEach((el2) => el2.remove()); delete el._x_prevKeys; delete el._x_lookup; }); }); function loop(el, iteratorNames, evaluateItems, evaluateKey) { let isObject = (i) => typeof i === "object" && !Array.isArray(i); let templateEl = el; evaluateItems((items) => { if (isNumeric3(items) && items >= 0) { items = Array.from(Array(items).keys(), (i) => i + 1); } if (items === void 0) items = []; let lookup = el._x_lookup; let prevKeys = el._x_prevKeys; let scopes = []; let keys = []; if (isObject(items)) { items = Object.entries(items).map(([key, value]) => { let scope = getIterationScopeVariables(iteratorNames, value, key, items); evaluateKey((value2) => keys.push(value2), {scope: {index: key, ...scope}}); scopes.push(scope); }); } else { for (let i = 0; i < items.length; i++) { let scope = getIterationScopeVariables(iteratorNames, items[i], i, items); evaluateKey((value) => keys.push(value), {scope: {index: i, ...scope}}); scopes.push(scope); } } let adds = []; let moves = []; let removes = []; let sames = []; for (let i = 0; i < prevKeys.length; i++) { let key = prevKeys[i]; if (keys.indexOf(key) === -1) removes.push(key); } prevKeys = prevKeys.filter((key) => !removes.includes(key)); let lastKey = "template"; for (let i = 0; i < keys.length; i++) { let key = keys[i]; let prevIndex = prevKeys.indexOf(key); if (prevIndex === -1) { prevKeys.splice(i, 0, key); adds.push([lastKey, i]); } else if (prevIndex !== i) { let keyInSpot = prevKeys.splice(i, 1)[0]; let keyForSpot = prevKeys.splice(prevIndex - 1, 1)[0]; prevKeys.splice(i, 0, keyForSpot); prevKeys.splice(prevIndex, 0, keyInSpot); moves.push([keyInSpot, keyForSpot]); } else { sames.push(key); } lastKey = key; } for (let i = 0; i < removes.length; i++) { let key = removes[i]; lookup[key].remove(); lookup[key] = null; delete lookup[key]; } for (let i = 0; i < moves.length; i++) { let [keyInSpot, keyForSpot] = moves[i]; let elInSpot = lookup[keyInSpot]; let elForSpot = lookup[keyForSpot]; let marker = document.createElement("div"); mutateDom(() => { elForSpot.after(marker); elInSpot.after(elForSpot); marker.before(elInSpot); marker.remove(); }); refreshScope(elForSpot, scopes[keys.indexOf(keyForSpot)]); } for (let i = 0; i < adds.length; i++) { let [lastKey2, index] = adds[i]; let lastEl = lastKey2 === "template" ? templateEl : lookup[lastKey2]; let scope = scopes[index]; let key = keys[index]; let clone2 = document.importNode(templateEl.content, true).firstElementChild; addScopeToNode(clone2, reactive(scope), templateEl); mutateDom(() => { lastEl.after(clone2); initTree(clone2); }); if (typeof key === "object") { warn("x-for key cannot be an object, it must be a string or an integer", templateEl); } lookup[key] = clone2; } for (let i = 0; i < sames.length; i++) { refreshScope(lookup[sames[i]], scopes[keys.indexOf(sames[i])]); } templateEl._x_prevKeys = keys; }); } function parseForExpression(expression) { let forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; let stripParensRE = /^\s*\(|\)\s*$/g; let forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; let inMatch = expression.match(forAliasRE); if (!inMatch) return; let res = {}; res.items = inMatch[2].trim(); let item = inMatch[1].replace(stripParensRE, "").trim(); let iteratorMatch = item.match(forIteratorRE); if (iteratorMatch) { res.item = item.replace(forIteratorRE, "").trim(); res.index = iteratorMatch[1].trim(); if (iteratorMatch[2]) { res.collection = iteratorMatch[2].trim(); } } else { res.item = item; } return res; } function getIterationScopeVariables(iteratorNames, item, index, items) { let scopeVariables = {}; if (/^\[.*\]$/.test(iteratorNames.item) && Array.isArray(item)) { let names = iteratorNames.item.replace("[", "").replace("]", "").split(",").map((i) => i.trim()); names.forEach((name, i) => { scopeVariables[name] = item[i]; }); } else if (/^\{.*\}$/.test(iteratorNames.item) && !Array.isArray(item) && typeof item === "object") { let names = iteratorNames.item.replace("{", "").replace("}", "").split(",").map((i) => i.trim()); names.forEach((name) => { scopeVariables[name] = item[name]; }); } else { scopeVariables[iteratorNames.item] = item; } if (iteratorNames.index) scopeVariables[iteratorNames.index] = index; if (iteratorNames.collection) scopeVariables[iteratorNames.collection] = items; return scopeVariables; } function isNumeric3(subject) { return !Array.isArray(subject) && !isNaN(subject); } // packages/alpinejs/src/directives/x-ref.js function handler2() { } handler2.inline = (el, {expression}, {cleanup}) => { let root = closestRoot(el); if (!root._x_refs) root._x_refs = {}; root._x_refs[expression] = el; cleanup(() => delete root._x_refs[expression]); }; directive("ref", handler2); // packages/alpinejs/src/directives/x-if.js directive("if", (el, {expression}, {effect: effect3, cleanup}) => { let evaluate2 = evaluateLater(el, expression); let show = () => { if (el._x_currentIfEl) return el._x_currentIfEl; let clone2 = el.content.cloneNode(true).firstElementChild; addScopeToNode(clone2, {}, el); mutateDom(() => { el.after(clone2); initTree(clone2); }); el._x_currentIfEl = clone2; el._x_undoIf = () => { clone2.remove(); delete el._x_currentIfEl; }; return clone2; }; let hide = () => { if (!el._x_undoIf) return; el._x_undoIf(); delete el._x_undoIf; }; effect3(() => evaluate2((value) => { value ? show() : hide(); })); cleanup(() => el._x_undoIf && el._x_undoIf()); }); // packages/alpinejs/src/directives/x-on.js mapAttributes(startingWith("@", into(prefix("on:")))); directive("on", skipDuringClone((el, {value, modifiers, expression}, {cleanup}) => { let evaluate2 = expression ? evaluateLater(el, expression) : () => { }; let removeListener = on(el, value, modifiers, (e) => { evaluate2(() => { }, {scope: {$event: e}, params: [e]}); }); cleanup(() => removeListener()); })); // packages/alpinejs/src/index.js alpine_default.setEvaluator(normalEvaluator); alpine_default.setReactivityEngine({reactive: import_reactivity9.reactive, effect: import_reactivity9.effect, release: import_reactivity9.stop, raw: import_reactivity9.toRaw}); var src_default = alpine_default; // packages/alpinejs/builds/module.js var module_default = src_default; /***/ }), /***/ "./node_modules/axios/index.js": /*!*************************************!*\ !*** ./node_modules/axios/index.js ***! \*************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(/*! ./lib/axios */ "./node_modules/axios/lib/axios.js"); /***/ }), /***/ "./node_modules/axios/lib/adapters/xhr.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/adapters/xhr.js ***! \************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var settle = __webpack_require__(/*! ./../core/settle */ "./node_modules/axios/lib/core/settle.js"); var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./node_modules/axios/lib/helpers/cookies.js"); var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./node_modules/axios/lib/core/buildFullPath.js"); var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./node_modules/axios/lib/helpers/parseHeaders.js"); var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js"); var createError = __webpack_require__(/*! ../core/createError */ "./node_modules/axios/lib/core/createError.js"); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; var responseType = config.responseType; if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } var fullPath = buildFullPath(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; function onloadend() { if (!request) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // Clean up request request = null; } if ('onloadend' in request) { // Use onloadend if available request.onloadend = onloadend; } else { // Listen for ready state to emulate onloadend request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // readystate handler is calling before onerror or ontimeout handlers, // so we should call onloadend on the next 'tick' setTimeout(onloadend); }; } // Handle browser request cancellation (as opposed to a manual cancellation) request.onabort = function handleAbort() { if (!request) { return; } reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(createError('Network Error', config, null, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(createError( timeoutErrorMessage, config, config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (!utils.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } // Add responseType to request if needed if (responseType && responseType !== 'json') { request.responseType = config.responseType; } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (!request) { return; } request.abort(); reject(cancel); // Clean up request request = null; }); } if (!requestData) { requestData = null; } // Send the request request.send(requestData); }); }; /***/ }), /***/ "./node_modules/axios/lib/axios.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/axios.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); var Axios = __webpack_require__(/*! ./core/Axios */ "./node_modules/axios/lib/core/Axios.js"); var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); var defaults = __webpack_require__(/*! ./defaults */ "./node_modules/axios/lib/defaults.js"); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); return instance; } // Create the default instance to be exported var axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios; // Factory for creating new instances axios.create = function create(instanceConfig) { return createInstance(mergeConfig(axios.defaults, instanceConfig)); }; // Expose Cancel & CancelToken axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./node_modules/axios/lib/cancel/CancelToken.js"); axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(/*! ./helpers/spread */ "./node_modules/axios/lib/helpers/spread.js"); // Expose isAxiosError axios.isAxiosError = __webpack_require__(/*! ./helpers/isAxiosError */ "./node_modules/axios/lib/helpers/isAxiosError.js"); module.exports = axios; // Allow use of default import syntax in TypeScript module.exports["default"] = axios; /***/ }), /***/ "./node_modules/axios/lib/cancel/Cancel.js": /*!*************************************************!*\ !*** ./node_modules/axios/lib/cancel/Cancel.js ***! \*************************************************/ /***/ ((module) => { "use strict"; /** * A `Cancel` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function Cancel(message) { this.message = message; } Cancel.prototype.toString = function toString() { return 'Cancel' + (this.message ? ': ' + this.message : ''); }; Cancel.prototype.__CANCEL__ = true; module.exports = Cancel; /***/ }), /***/ "./node_modules/axios/lib/cancel/CancelToken.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/cancel/CancelToken.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Cancel = __webpack_require__(/*! ./Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new Cancel(message); resolvePromise(token.reason); }); } /** * Throws a `Cancel` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; module.exports = CancelToken; /***/ }), /***/ "./node_modules/axios/lib/cancel/isCancel.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/cancel/isCancel.js ***! \***************************************************/ /***/ ((module) => { "use strict"; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; /***/ }), /***/ "./node_modules/axios/lib/core/Axios.js": /*!**********************************************!*\ !*** ./node_modules/axios/lib/core/Axios.js ***! \**********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./node_modules/axios/lib/core/InterceptorManager.js"); var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./node_modules/axios/lib/core/dispatchRequest.js"); var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); var validator = __webpack_require__(/*! ../helpers/validator */ "./node_modules/axios/lib/helpers/validator.js"); var validators = validator.validators; /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = arguments[1] || {}; config.url = arguments[0]; } else { config = config || {}; } config = mergeConfig(this.defaults, config); // Set config.method if (config.method) { config.method = config.method.toLowerCase(); } else if (this.defaults.method) { config.method = this.defaults.method.toLowerCase(); } else { config.method = 'get'; } var transitional = config.transitional; if (transitional !== undefined) { validator.assertOptions(transitional, { silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'), forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'), clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0') }, false); } // filter out skipped interceptors var requestInterceptorChain = []; var synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); var responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); var promise; if (!synchronousRequestInterceptors) { var chain = [dispatchRequest, undefined]; Array.prototype.unshift.apply(chain, requestInterceptorChain); chain = chain.concat(responseInterceptorChain); promise = Promise.resolve(config); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; } var newConfig = config; while (requestInterceptorChain.length) { var onFulfilled = requestInterceptorChain.shift(); var onRejected = requestInterceptorChain.shift(); try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected(error); break; } } try { promise = dispatchRequest(newConfig); } catch (error) { return Promise.reject(error); } while (responseInterceptorChain.length) { promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); } return promise; }; Axios.prototype.getUri = function getUri(config) { config = mergeConfig(this.defaults, config); return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: (config || {}).data })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: data })); }; }); module.exports = Axios; /***/ }), /***/ "./node_modules/axios/lib/core/InterceptorManager.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/core/InterceptorManager.js ***! \***********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : null }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function forEach(fn) { utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }), /***/ "./node_modules/axios/lib/core/buildFullPath.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/buildFullPath.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js"); var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./node_modules/axios/lib/helpers/combineURLs.js"); /** * Creates a new URL by combining the baseURL with the requestedURL, * only when the requestedURL is not already an absolute URL. * If the requestURL is absolute, this function returns the requestedURL untouched. * * @param {string} baseURL The base URL * @param {string} requestedURL Absolute or relative URL to combine * @returns {string} The combined full path */ module.exports = function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; }; /***/ }), /***/ "./node_modules/axios/lib/core/createError.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/createError.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var enhanceError = __webpack_require__(/*! ./enhanceError */ "./node_modules/axios/lib/core/enhanceError.js"); /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ module.exports = function createError(message, config, code, request, response) { var error = new Error(message); return enhanceError(error, config, code, request, response); }; /***/ }), /***/ "./node_modules/axios/lib/core/dispatchRequest.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/core/dispatchRequest.js ***! \********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var transformData = __webpack_require__(/*! ./transformData */ "./node_modules/axios/lib/core/transformData.js"); var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); var defaults = __webpack_require__(/*! ../defaults */ "./node_modules/axios/lib/defaults.js"); /** * Throws a `Cancel` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData.call( config, config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers ); utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData.call( config, response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData.call( config, reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; /***/ }), /***/ "./node_modules/axios/lib/core/enhanceError.js": /*!*****************************************************!*\ !*** ./node_modules/axios/lib/core/enhanceError.js ***! \*****************************************************/ /***/ ((module) => { "use strict"; /** * Update an Error with the specified config, error code, and response. * * @param {Error} error The error to update. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The error. */ module.exports = function enhanceError(error, config, code, request, response) { error.config = config; if (code) { error.code = code; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function toJSON() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code }; }; return error; }; /***/ }), /***/ "./node_modules/axios/lib/core/mergeConfig.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/mergeConfig.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. * * @param {Object} config1 * @param {Object} config2 * @returns {Object} New object resulting from merging config2 to config1 */ module.exports = function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; var config = {}; var valueFromConfig2Keys = ['url', 'method', 'data']; var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; var defaultToConfig2Keys = [ 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' ]; var directMergeKeys = ['validateStatus']; function getMergedValue(target, source) { if (utils.isPlainObject(target) && utils.isPlainObject(source)) { return utils.merge(target, source); } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } else if (utils.isArray(source)) { return source.slice(); } return source; } function mergeDeepProperties(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } } utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } }); utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } }); utils.forEach(directMergeKeys, function merge(prop) { if (prop in config2) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (prop in config1) { config[prop] = getMergedValue(undefined, config1[prop]); } }); var axiosKeys = valueFromConfig2Keys .concat(mergeDeepPropertiesKeys) .concat(defaultToConfig2Keys) .concat(directMergeKeys); var otherKeys = Object .keys(config1) .concat(Object.keys(config2)) .filter(function filterAxiosKeys(key) { return axiosKeys.indexOf(key) === -1; }); utils.forEach(otherKeys, mergeDeepProperties); return config; }; /***/ }), /***/ "./node_modules/axios/lib/core/settle.js": /*!***********************************************!*\ !*** ./node_modules/axios/lib/core/settle.js ***! \***********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var createError = __webpack_require__(/*! ./createError */ "./node_modules/axios/lib/core/createError.js"); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(createError( 'Request failed with status code ' + response.status, response.config, null, response.request, response )); } }; /***/ }), /***/ "./node_modules/axios/lib/core/transformData.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/transformData.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var defaults = __webpack_require__(/*! ./../defaults */ "./node_modules/axios/lib/defaults.js"); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { var context = this || defaults; /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { data = fn.call(context, data, headers); }); return data; }; /***/ }), /***/ "./node_modules/axios/lib/defaults.js": /*!********************************************!*\ !*** ./node_modules/axios/lib/defaults.js ***! \********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var process = __webpack_require__(/*! process/browser */ "./node_modules/process/browser.js"); var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./node_modules/axios/lib/helpers/normalizeHeaderName.js"); var enhanceError = __webpack_require__(/*! ./core/enhanceError */ "./node_modules/axios/lib/core/enhanceError.js"); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = __webpack_require__(/*! ./adapters/xhr */ "./node_modules/axios/lib/adapters/xhr.js"); } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = __webpack_require__(/*! ./adapters/http */ "./node_modules/axios/lib/adapters/xhr.js"); } return adapter; } function stringifySafely(rawValue, parser, encoder) { if (utils.isString(rawValue)) { try { (parser || JSON.parse)(rawValue); return utils.trim(rawValue); } catch (e) { if (e.name !== 'SyntaxError') { throw e; } } } return (encoder || JSON.stringify)(rawValue); } var defaults = { transitional: { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }, adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { setContentTypeIfUnset(headers, 'application/json'); return stringifySafely(data); } return data; }], transformResponse: [function transformResponse(data) { var transitional = this.transitional; var silentJSONParsing = transitional && transitional.silentJSONParsing; var forcedJSONParsing = transitional && transitional.forcedJSONParsing; var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { try { return JSON.parse(data); } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { throw enhanceError(e, this, 'E_JSON_PARSE'); } throw e; } } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } }; defaults.headers = { common: { 'Accept': 'application/json, text/plain, */*' } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; /***/ }), /***/ "./node_modules/axios/lib/helpers/bind.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/helpers/bind.js ***! \************************************************/ /***/ ((module) => { "use strict"; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/buildURL.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/helpers/buildURL.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function encode(val) { return encodeURIComponent(val). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { var hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/combineURLs.js": /*!*******************************************************!*\ !*** ./node_modules/axios/lib/helpers/combineURLs.js ***! \*******************************************************/ /***/ ((module) => { "use strict"; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/cookies.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/helpers/cookies.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js": /*!*********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***! \*********************************************************/ /***/ ((module) => { "use strict"; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/isAxiosError.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAxiosError.js ***! \********************************************************/ /***/ ((module) => { "use strict"; /** * Determines whether the payload is an error thrown by Axios * * @param {*} payload The value to test * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ module.exports = function isAxiosError(payload) { return (typeof payload === 'object') && (payload.isAxiosError === true); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***! \***********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js": /*!***************************************************************!*\ !*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***! \***************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); module.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/parseHeaders.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/parseHeaders.js ***! \********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/spread.js": /*!**************************************************!*\ !*** ./node_modules/axios/lib/helpers/spread.js ***! \**************************************************/ /***/ ((module) => { "use strict"; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/validator.js": /*!*****************************************************!*\ !*** ./node_modules/axios/lib/helpers/validator.js ***! \*****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var pkg = __webpack_require__(/*! ./../../package.json */ "./node_modules/axios/package.json"); var validators = {}; // eslint-disable-next-line func-names ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { validators[type] = function validator(thing) { return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; }; }); var deprecatedWarnings = {}; var currentVerArr = pkg.version.split('.'); /** * Compare package versions * @param {string} version * @param {string?} thanVersion * @returns {boolean} */ function isOlderVersion(version, thanVersion) { var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr; var destVer = version.split('.'); for (var i = 0; i < 3; i++) { if (pkgVersionArr[i] > destVer[i]) { return true; } else if (pkgVersionArr[i] < destVer[i]) { return false; } } return false; } /** * Transitional option validator * @param {function|boolean?} validator * @param {string?} version * @param {string} message * @returns {function} */ validators.transitional = function transitional(validator, version, message) { var isDeprecated = version && isOlderVersion(version); function formatMessage(opt, desc) { return '[Axios v' + pkg.version + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); } // eslint-disable-next-line func-names return function(value, opt, opts) { if (validator === false) { throw new Error(formatMessage(opt, ' has been removed in ' + version)); } if (isDeprecated && !deprecatedWarnings[opt]) { deprecatedWarnings[opt] = true; // eslint-disable-next-line no-console console.warn( formatMessage( opt, ' has been deprecated since v' + version + ' and will be removed in the near future' ) ); } return validator ? validator(value, opt, opts) : true; }; }; /** * Assert object's properties type * @param {object} options * @param {object} schema * @param {boolean?} allowUnknown */ function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { throw new TypeError('options must be an object'); } var keys = Object.keys(options); var i = keys.length; while (i-- > 0) { var opt = keys[i]; var validator = schema[opt]; if (validator) { var value = options[opt]; var result = value === undefined || validator(value, opt, options); if (result !== true) { throw new TypeError('option ' + opt + ' must be ' + result); } continue; } if (allowUnknown !== true) { throw Error('Unknown option ' + opt); } } } module.exports = { isOlderVersion: isOlderVersion, assertOptions: assertOptions, validators: validators }; /***/ }), /***/ "./node_modules/axios/lib/utils.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/utils.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is a Buffer * * @param {Object} val The value to test * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return (typeof FormData !== 'undefined') && (val instanceof FormData); } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a plain Object * * @param {Object} val The value to test * @return {boolean} True if value is a plain Object, otherwise false */ function isPlainObject(val) { if (toString.call(val) !== '[object Object]') { return false; } var prototype = Object.getPrototypeOf(val); return prototype === null || prototype === Object.prototype; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject(val) && isFunction(val.pipe); } /** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ function isURLSearchParams(val) { return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (isPlainObject(result[key]) && isPlainObject(val)) { result[key] = merge(result[key], val); } else if (isPlainObject(val)) { result[key] = merge({}, val); } else if (isArray(val)) { result[key] = val.slice(); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind(val, thisArg); } else { a[key] = val; } }); return a; } /** * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * * @param {string} content with BOM * @return {string} content value without BOM */ function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isPlainObject: isPlainObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, extend: extend, trim: trim, stripBOM: stripBOM }; /***/ }), /***/ "./resources/js/app.js": /*!*****************************!*\ !*** ./resources/js/app.js ***! \*****************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var choices_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! choices.js */ "./node_modules/choices.js/public/assets/scripts/choices.js"); /* harmony import */ var choices_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(choices_js__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var alpinejs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! alpinejs */ "./node_modules/alpinejs/dist/module.esm.js"); __webpack_require__(/*! ./bootstrap */ "./resources/js/bootstrap.js"); // choice.js // create multi-select with choice.js // Create multi-select element window.choices = function (element) { return new (choices_js__WEBPACK_IMPORTED_MODULE_0___default())(element, { maxItemCount: 4, removeItemButton: true }); }; // choice.js __webpack_require__(/*! alpinejs */ "./node_modules/alpinejs/dist/module.esm.js"); alpinejs__WEBPACK_IMPORTED_MODULE_1__["default"].start(); /***/ }), /***/ "./resources/js/bootstrap.js": /*!***********************************!*\ !*** ./resources/js/bootstrap.js ***! \***********************************/ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { window._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = __webpack_require__(/*! axios */ "./node_modules/axios/index.js"); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from 'laravel-echo'; // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: process.env.MIX_PUSHER_APP_KEY, // cluster: process.env.MIX_PUSHER_APP_CLUSTER, // forceTLS: true // }); /***/ }), /***/ "./node_modules/choices.js/public/assets/scripts/choices.js": /*!******************************************************************!*\ !*** ./node_modules/choices.js/public/assets/scripts/choices.js ***! \******************************************************************/ /***/ ((module) => { /*! choices.js v9.0.1 | © 2019 Josh Johnson | https://github.com/jshjohnson/Choices#readme */ (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(); else {} })(window, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __nested_webpack_require_633__(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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_633__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __nested_webpack_require_633__.m = modules; /******/ /******/ // expose the module cache /******/ __nested_webpack_require_633__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __nested_webpack_require_633__.d = function(exports, name, getter) { /******/ if(!__nested_webpack_require_633__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __nested_webpack_require_633__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __nested_webpack_require_633__.t = function(value, mode) { /******/ if(mode & 1) value = __nested_webpack_require_633__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __nested_webpack_require_633__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __nested_webpack_require_633__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __nested_webpack_require_633__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __nested_webpack_require_633__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __nested_webpack_require_633__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __nested_webpack_require_633__.p = "/public/assets/scripts/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __nested_webpack_require_633__(__nested_webpack_require_633__.s = 4); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isMergeableObject = function isMergeableObject(value) { return isNonNullObject(value) && !isSpecial(value) }; function isNonNullObject(value) { return !!value && typeof value === 'object' } function isSpecial(value) { var stringValue = Object.prototype.toString.call(value); return stringValue === '[object RegExp]' || stringValue === '[object Date]' || isReactElement(value) } // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 var canUseSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; function isReactElement(value) { return value.$$typeof === REACT_ELEMENT_TYPE } function emptyTarget(val) { return Array.isArray(val) ? [] : {} } function cloneUnlessOtherwiseSpecified(value, options) { return (options.clone !== false && options.isMergeableObject(value)) ? deepmerge(emptyTarget(value), value, options) : value } function defaultArrayMerge(target, source, options) { return target.concat(source).map(function(element) { return cloneUnlessOtherwiseSpecified(element, options) }) } function getMergeFunction(key, options) { if (!options.customMerge) { return deepmerge } var customMerge = options.customMerge(key); return typeof customMerge === 'function' ? customMerge : deepmerge } function getEnumerableOwnPropertySymbols(target) { return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) { return target.propertyIsEnumerable(symbol) }) : [] } function getKeys(target) { return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) } // Protects from prototype poisoning and unexpected merging up the prototype chain. function propertyIsUnsafe(target, key) { try { return (key in target) // Properties are safe to merge if they don't exist in the target yet, && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. } catch (unused) { // Counterintuitively, it's safe to merge any property on a target that causes the `in` operator to throw. // This happens when trying to copy an object in the source over a plain string in the target. return false } } function mergeObject(target, source, options) { var destination = {}; if (options.isMergeableObject(target)) { getKeys(target).forEach(function(key) { destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); }); } getKeys(source).forEach(function(key) { if (propertyIsUnsafe(target, key)) { return } if (!options.isMergeableObject(source[key]) || !target[key]) { destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); } else { destination[key] = getMergeFunction(key, options)(target[key], source[key], options); } }); return destination } function deepmerge(target, source, options) { options = options || {}; options.arrayMerge = options.arrayMerge || defaultArrayMerge; options.isMergeableObject = options.isMergeableObject || isMergeableObject; // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() // implementations can use it. The caller may not replace it. options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; var sourceIsArray = Array.isArray(source); var targetIsArray = Array.isArray(target); var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; if (!sourceAndTargetTypesMatch) { return cloneUnlessOtherwiseSpecified(source, options) } else if (sourceIsArray) { return options.arrayMerge(target, source, options) } else { return mergeObject(target, source, options) } } deepmerge.all = function deepmergeAll(array, options) { if (!Array.isArray(array)) { throw new Error('first argument should be an array') } return array.reduce(function(prev, next) { return deepmerge(prev, next, options) }, {}) }; var deepmerge_1 = deepmerge; module.exports = deepmerge_1; /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __nested_webpack_require_8347__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global, module) {/* harmony import */ var _ponyfill_js__WEBPACK_IMPORTED_MODULE_0__ = __nested_webpack_require_8347__(3); /* global window */ var root; if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof global !== 'undefined') { root = global; } else if (true) { root = module; } else {} var result = Object(_ponyfill_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(root); /* harmony default export */ __webpack_exports__["a"] = (result); /* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_8347__(5), __nested_webpack_require_8347__(6)(module))) /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /*! * Fuse.js v3.4.5 - Lightweight fuzzy-search (http://fusejs.io) * * Copyright (c) 2012-2017 Kirollos Risk (http://kiro.me) * All Rights Reserved. Apache Software License 2.0 * * http://www.apache.org/licenses/LICENSE-2.0 */ !function(e,t){ true?module.exports=t():0}(this,function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=1)}([function(e,t){e.exports=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)}},function(e,t,n){function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var i=n(2),a=n(8),s=n(0),c=function(){function e(t,n){var r=n.location,o=void 0===r?0:r,i=n.distance,s=void 0===i?100:i,c=n.threshold,h=void 0===c?.6:c,l=n.maxPatternLength,u=void 0===l?32:l,f=n.caseSensitive,d=void 0!==f&&f,v=n.tokenSeparator,p=void 0===v?/ +/g:v,g=n.findAllMatches,y=void 0!==g&&g,m=n.minMatchCharLength,k=void 0===m?1:m,S=n.id,x=void 0===S?null:S,b=n.keys,M=void 0===b?[]:b,_=n.shouldSort,L=void 0===_||_,w=n.getFn,A=void 0===w?a:w,C=n.sortFn,I=void 0===C?function(e,t){return e.score-t.score}:C,O=n.tokenize,j=void 0!==O&&O,P=n.matchAllTokens,F=void 0!==P&&P,T=n.includeMatches,z=void 0!==T&&T,E=n.includeScore,K=void 0!==E&&E,$=n.verbose,J=void 0!==$&&$;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.options={location:o,distance:s,threshold:h,maxPatternLength:u,isCaseSensitive:d,tokenSeparator:p,findAllMatches:y,minMatchCharLength:k,id:x,keys:M,includeMatches:z,includeScore:K,shouldSort:L,getFn:A,sortFn:I,verbose:J,tokenize:j,matchAllTokens:F},this.setCollection(t)}var t,n,c;return t=e,(n=[{key:"setCollection",value:function(e){return this.list=e,e}},{key:"search",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{limit:!1};this._log('---------\nSearch pattern: "'.concat(e,'"'));var n=this._prepareSearchers(e),r=n.tokenSearchers,o=n.fullSearcher,i=this._search(r,o),a=i.weights,s=i.results;return this._computeScore(a,s),this.options.shouldSort&&this._sort(s),t.limit&&"number"==typeof t.limit&&(s=s.slice(0,t.limit)),this._format(s)}},{key:"_prepareSearchers",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=[];if(this.options.tokenize)for(var n=e.split(this.options.tokenSeparator),r=0,o=n.length;r<o;r+=1)t.push(new i(n[r],this.options));return{tokenSearchers:t,fullSearcher:new i(e,this.options)}}},{key:"_search",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,n=this.list,r={},o=[];if("string"==typeof n[0]){for(var i=0,a=n.length;i<a;i+=1)this._analyze({key:"",value:n[i],record:i,index:i},{resultMap:r,results:o,tokenSearchers:e,fullSearcher:t});return{weights:null,results:o}}for(var s={},c=0,h=n.length;c<h;c+=1)for(var l=n[c],u=0,f=this.options.keys.length;u<f;u+=1){var d=this.options.keys[u];if("string"!=typeof d){if(s[d.name]={weight:1-d.weight||1},d.weight<=0||d.weight>1)throw new Error("Key weight has to be > 0 and <= 1");d=d.name}else s[d]={weight:1};this._analyze({key:d,value:this.options.getFn(l,d),record:l,index:c},{resultMap:r,results:o,tokenSearchers:e,fullSearcher:t})}return{weights:s,results:o}}},{key:"_analyze",value:function(e,t){var n=e.key,r=e.arrayIndex,o=void 0===r?-1:r,i=e.value,a=e.record,c=e.index,h=t.tokenSearchers,l=void 0===h?[]:h,u=t.fullSearcher,f=void 0===u?[]:u,d=t.resultMap,v=void 0===d?{}:d,p=t.results,g=void 0===p?[]:p;if(null!=i){var y=!1,m=-1,k=0;if("string"==typeof i){this._log("\nKey: ".concat(""===n?"-":n));var S=f.search(i);if(this._log('Full text: "'.concat(i,'", score: ').concat(S.score)),this.options.tokenize){for(var x=i.split(this.options.tokenSeparator),b=[],M=0;M<l.length;M+=1){var _=l[M];this._log('\nPattern: "'.concat(_.pattern,'"'));for(var L=!1,w=0;w<x.length;w+=1){var A=x[w],C=_.search(A),I={};C.isMatch?(I[A]=C.score,y=!0,L=!0,b.push(C.score)):(I[A]=1,this.options.matchAllTokens||b.push(1)),this._log('Token: "'.concat(A,'", score: ').concat(I[A]))}L&&(k+=1)}m=b[0];for(var O=b.length,j=1;j<O;j+=1)m+=b[j];m/=O,this._log("Token score average:",m)}var P=S.score;m>-1&&(P=(P+m)/2),this._log("Score average:",P);var F=!this.options.tokenize||!this.options.matchAllTokens||k>=l.length;if(this._log("\nCheck Matches: ".concat(F)),(y||S.isMatch)&&F){var T=v[c];T?T.output.push({key:n,arrayIndex:o,value:i,score:P,matchedIndices:S.matchedIndices}):(v[c]={item:a,output:[{key:n,arrayIndex:o,value:i,score:P,matchedIndices:S.matchedIndices}]},g.push(v[c]))}}else if(s(i))for(var z=0,E=i.length;z<E;z+=1)this._analyze({key:n,arrayIndex:z,value:i[z],record:a,index:c},{resultMap:v,results:g,tokenSearchers:l,fullSearcher:f})}}},{key:"_computeScore",value:function(e,t){this._log("\n\nComputing score:\n");for(var n=0,r=t.length;n<r;n+=1){for(var o=t[n].output,i=o.length,a=1,s=1,c=0;c<i;c+=1){var h=e?e[o[c].key].weight:1,l=(1===h?o[c].score:o[c].score||.001)*h;1!==h?s=Math.min(s,l):(o[c].nScore=l,a*=l)}t[n].score=1===s?a:s,this._log(t[n])}}},{key:"_sort",value:function(e){this._log("\n\nSorting...."),e.sort(this.options.sortFn)}},{key:"_format",value:function(e){var t=[];if(this.options.verbose){var n=[];this._log("\n\nOutput:\n\n",JSON.stringify(e,function(e,t){if("object"===r(t)&&null!==t){if(-1!==n.indexOf(t))return;n.push(t)}return t})),n=null}var o=[];this.options.includeMatches&&o.push(function(e,t){var n=e.output;t.matches=[];for(var r=0,o=n.length;r<o;r+=1){var i=n[r];if(0!==i.matchedIndices.length){var a={indices:i.matchedIndices,value:i.value};i.key&&(a.key=i.key),i.hasOwnProperty("arrayIndex")&&i.arrayIndex>-1&&(a.arrayIndex=i.arrayIndex),t.matches.push(a)}}}),this.options.includeScore&&o.push(function(e,t){t.score=e.score});for(var i=0,a=e.length;i<a;i+=1){var s=e[i];if(this.options.id&&(s.item=this.options.getFn(s.item,this.options.id)[0]),o.length){for(var c={item:s.item},h=0,l=o.length;h<l;h+=1)o[h](s,c);t.push(c)}else t.push(s.item)}return t}},{key:"_log",value:function(){var e;this.options.verbose&&(e=console).log.apply(e,arguments)}}])&&o(t.prototype,n),c&&o(t,c),e}();e.exports=c},function(e,t,n){function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var o=n(3),i=n(4),a=n(7),s=function(){function e(t,n){var r=n.location,o=void 0===r?0:r,i=n.distance,s=void 0===i?100:i,c=n.threshold,h=void 0===c?.6:c,l=n.maxPatternLength,u=void 0===l?32:l,f=n.isCaseSensitive,d=void 0!==f&&f,v=n.tokenSeparator,p=void 0===v?/ +/g:v,g=n.findAllMatches,y=void 0!==g&&g,m=n.minMatchCharLength,k=void 0===m?1:m;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.options={location:o,distance:s,threshold:h,maxPatternLength:u,isCaseSensitive:d,tokenSeparator:p,findAllMatches:y,minMatchCharLength:k},this.pattern=this.options.isCaseSensitive?t:t.toLowerCase(),this.pattern.length<=u&&(this.patternAlphabet=a(this.pattern))}var t,n,s;return t=e,(n=[{key:"search",value:function(e){if(this.options.isCaseSensitive||(e=e.toLowerCase()),this.pattern===e)return{isMatch:!0,score:0,matchedIndices:[[0,e.length-1]]};var t=this.options,n=t.maxPatternLength,r=t.tokenSeparator;if(this.pattern.length>n)return o(e,this.pattern,r);var a=this.options,s=a.location,c=a.distance,h=a.threshold,l=a.findAllMatches,u=a.minMatchCharLength;return i(e,this.pattern,this.patternAlphabet,{location:s,distance:c,threshold:h,findAllMatches:l,minMatchCharLength:u})}}])&&r(t.prototype,n),s&&r(t,s),e}();e.exports=s},function(e,t){var n=/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g;e.exports=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:/ +/g,o=new RegExp(t.replace(n,"\\$&").replace(r,"|")),i=e.match(o),a=!!i,s=[];if(a)for(var c=0,h=i.length;c<h;c+=1){var l=i[c];s.push([e.indexOf(l),l.length-1])}return{score:a?.5:1,isMatch:a,matchedIndices:s}}},function(e,t,n){var r=n(5),o=n(6);e.exports=function(e,t,n,i){for(var a=i.location,s=void 0===a?0:a,c=i.distance,h=void 0===c?100:c,l=i.threshold,u=void 0===l?.6:l,f=i.findAllMatches,d=void 0!==f&&f,v=i.minMatchCharLength,p=void 0===v?1:v,g=s,y=e.length,m=u,k=e.indexOf(t,g),S=t.length,x=[],b=0;b<y;b+=1)x[b]=0;if(-1!==k){var M=r(t,{errors:0,currentLocation:k,expectedLocation:g,distance:h});if(m=Math.min(M,m),-1!==(k=e.lastIndexOf(t,g+S))){var _=r(t,{errors:0,currentLocation:k,expectedLocation:g,distance:h});m=Math.min(_,m)}}k=-1;for(var L=[],w=1,A=S+y,C=1<<S-1,I=0;I<S;I+=1){for(var O=0,j=A;O<j;){r(t,{errors:I,currentLocation:g+j,expectedLocation:g,distance:h})<=m?O=j:A=j,j=Math.floor((A-O)/2+O)}A=j;var P=Math.max(1,g-j+1),F=d?y:Math.min(g+j,y)+S,T=Array(F+2);T[F+1]=(1<<I)-1;for(var z=F;z>=P;z-=1){var E=z-1,K=n[e.charAt(E)];if(K&&(x[E]=1),T[z]=(T[z+1]<<1|1)&K,0!==I&&(T[z]|=(L[z+1]|L[z])<<1|1|L[z+1]),T[z]&C&&(w=r(t,{errors:I,currentLocation:E,expectedLocation:g,distance:h}))<=m){if(m=w,(k=E)<=g)break;P=Math.max(1,2*g-k)}}if(r(t,{errors:I+1,currentLocation:g,expectedLocation:g,distance:h})>m)break;L=T}return{isMatch:k>=0,score:0===w?.001:w,matchedIndices:o(x,p)}}},function(e,t){e.exports=function(e,t){var n=t.errors,r=void 0===n?0:n,o=t.currentLocation,i=void 0===o?0:o,a=t.expectedLocation,s=void 0===a?0:a,c=t.distance,h=void 0===c?100:c,l=r/e.length,u=Math.abs(s-i);return h?l+u/h:u?1:l}},function(e,t){e.exports=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=[],r=-1,o=-1,i=0,a=e.length;i<a;i+=1){var s=e[i];s&&-1===r?r=i:s||-1===r||((o=i-1)-r+1>=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}},function(e,t){e.exports=function(e){for(var t={},n=e.length,r=0;r<n;r+=1)t[e.charAt(r)]=0;for(var o=0;o<n;o+=1)t[e.charAt(o)]|=1<<n-o-1;return t}},function(e,t,n){var r=n(0);e.exports=function(e,t){return function e(t,n,o){if(n){var i=n.indexOf("."),a=n,s=null;-1!==i&&(a=n.slice(0,i),s=n.slice(i+1));var c=t[a];if(null!=c)if(s||"string"!=typeof c&&"number"!=typeof c)if(r(c))for(var h=0,l=c.length;h<l;h+=1)e(c[h],s,o);else s&&e(c,s,o);else o.push(c.toString())}else o.push(t);return o}(e,t,[])}}])}); /***/ }), /* 3 */ /***/ (function(module, __webpack_exports__, __nested_webpack_require_20511__) { "use strict"; /* harmony export (binding) */ __nested_webpack_require_20511__.d(__webpack_exports__, "a", function() { return symbolObservablePonyfill; }); function symbolObservablePonyfill(root) { var result; var Symbol = root.Symbol; if (typeof Symbol === 'function') { if (Symbol.observable) { result = Symbol.observable; } else { result = Symbol('observable'); Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ }), /* 4 */ /***/ (function(module, exports, __nested_webpack_require_21049__) { module.exports = __nested_webpack_require_21049__(7); /***/ }), /* 5 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 6 */ /***/ (function(module, exports) { module.exports = function(originalModule) { if (!originalModule.webpackPolyfill) { var module = Object.create(originalModule); // module.parent = undefined by default if (!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); Object.defineProperty(module, "exports", { enumerable: true }); module.webpackPolyfill = 1; } return module; }; /***/ }), /* 7 */ /***/ (function(module, __webpack_exports__, __nested_webpack_require_22336__) { "use strict"; __nested_webpack_require_22336__.r(__webpack_exports__); // EXTERNAL MODULE: ./node_modules/fuse.js/dist/fuse.js var dist_fuse = __nested_webpack_require_22336__(2); var fuse_default = /*#__PURE__*/__nested_webpack_require_22336__.n(dist_fuse); // EXTERNAL MODULE: ./node_modules/deepmerge/dist/cjs.js var cjs = __nested_webpack_require_22336__(0); var cjs_default = /*#__PURE__*/__nested_webpack_require_22336__.n(cjs); // EXTERNAL MODULE: ./node_modules/symbol-observable/es/index.js var es = __nested_webpack_require_22336__(1); // CONCATENATED MODULE: ./node_modules/redux/es/redux.js /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var randomString = function randomString() { return Math.random().toString(36).substring(7).split('').join('.'); }; var ActionTypes = { INIT: "@@redux/INIT" + randomString(), REPLACE: "@@redux/REPLACE" + randomString(), PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); } }; /** * @param {any} obj The object to inspect. * @returns {boolean} True if the argument appears to be a plain object. */ function isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false; var proto = obj; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(obj) === proto; } /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} [enhancer] The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function.'); } if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; /** * This makes a shallow copy of currentListeners so we can use * nextListeners as a temporary list while dispatching. * * This prevents any bugs around consumers calling * subscribe/unsubscribe in the middle of a dispatch. */ function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { if (isDispatching) { throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.'); } return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected the listener to be a function.'); } if (isDispatching) { throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } if (isDispatching) { throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'); } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!isPlainObject(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; listener(); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. // Any reducers that existed in both the new and old rootReducer // will receive the previous state. This effectively populates // the new state tree with any relevant data from the old one. dispatch({ type: ActionTypes.REPLACE }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/tc39/proposal-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object' || observer === null) { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[es["a" /* default */]] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[es["a" /* default */]] = observable, _ref2; } /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); } catch (e) {} // eslint-disable-line no-empty } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionDescription = actionType && "action \"" + String(actionType) + "\"" || 'an action'; return "Given " + actionDescription + ", reducer \"" + key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined."; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!isPlainObject(inputState)) { return "The " + argumentName + " has unexpected type of \"" + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\""); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (action && action.type === ActionTypes.REPLACE) return; if (unexpectedKeys.length > 0) { return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored."); } } function assertReducerShape(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error("Reducer \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined."); } if (typeof reducer(undefined, { type: ActionTypes.PROBE_UNKNOWN_ACTION() }) === 'undefined') { throw new Error("Reducer \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle " + ActionTypes.INIT + " or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null."); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (false) {} if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same // keys multiple times. var unexpectedKeyCache; if (false) {} var shapeAssertionError; try { assertReducerShape(finalReducers); } catch (e) { shapeAssertionError = e; } return function combination(state, action) { if (state === void 0) { state = {}; } if (shapeAssertionError) { throw shapeAssertionError; } if (false) { var warningMessage; } var hasChanged = false; var nextState = {}; for (var _i = 0; _i < finalReducerKeys.length; _i++) { var _key = finalReducerKeys[_i]; var reducer = finalReducers[_key]; var previousStateForKey = state[_key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(_key, action); throw new Error(errorMessage); } nextState[_key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(this, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass an action creator as the first argument, * and get a dispatch wrapped function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error("bindActionCreators expected an object or a function, instead received " + (actionCreators === null ? 'null' : typeof actionCreators) + ". " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?"); } var boundActionCreators = {}; for (var key in actionCreators) { var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { keys.push.apply(keys, Object.getOwnPropertySymbols(object)); } if (enumerableOnly) keys = keys.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce(function (a, b) { return function () { return a(b.apply(void 0, arguments)); }; }); } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function () { var store = createStore.apply(void 0, arguments); var _dispatch = function dispatch() { throw new Error('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.'); }; var middlewareAPI = { getState: store.getState, dispatch: function dispatch() { return _dispatch.apply(void 0, arguments); } }; var chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = compose.apply(void 0, chain)(store.dispatch); return _objectSpread2({}, store, { dispatch: _dispatch }); }; }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (false) {} // CONCATENATED MODULE: ./src/scripts/reducers/items.js var defaultState = []; function items_items(state, action) { if (state === void 0) { state = defaultState; } switch (action.type) { case 'ADD_ITEM': { // Add object to items array var newState = [].concat(state, [{ id: action.id, choiceId: action.choiceId, groupId: action.groupId, value: action.value, label: action.label, active: true, highlighted: false, customProperties: action.customProperties, placeholder: action.placeholder || false, keyCode: null }]); return newState.map(function (obj) { var item = obj; item.highlighted = false; return item; }); } case 'REMOVE_ITEM': { // Set item to inactive return state.map(function (obj) { var item = obj; if (item.id === action.id) { item.active = false; } return item; }); } case 'HIGHLIGHT_ITEM': { return state.map(function (obj) { var item = obj; if (item.id === action.id) { item.highlighted = action.highlighted; } return item; }); } default: { return state; } } } // CONCATENATED MODULE: ./src/scripts/reducers/groups.js var groups_defaultState = []; function groups(state, action) { if (state === void 0) { state = groups_defaultState; } switch (action.type) { case 'ADD_GROUP': { return [].concat(state, [{ id: action.id, value: action.value, active: action.active, disabled: action.disabled }]); } case 'CLEAR_CHOICES': { return []; } default: { return state; } } } // CONCATENATED MODULE: ./src/scripts/reducers/choices.js var choices_defaultState = []; function choices_choices(state, action) { if (state === void 0) { state = choices_defaultState; } switch (action.type) { case 'ADD_CHOICE': { /* A disabled choice appears in the choice dropdown but cannot be selected A selected choice has been added to the passed input's value (added as an item) An active choice appears within the choice dropdown */ return [].concat(state, [{ id: action.id, elementId: action.elementId, groupId: action.groupId, value: action.value, label: action.label || action.value, disabled: action.disabled || false, selected: false, active: true, score: 9999, customProperties: action.customProperties, placeholder: action.placeholder || false, keyCode: null }]); } case 'ADD_ITEM': { // If all choices need to be activated if (action.activateOptions) { return state.map(function (obj) { var choice = obj; choice.active = action.active; return choice; }); } // When an item is added and it has an associated choice, // we want to disable it so it can't be chosen again if (action.choiceId > -1) { return state.map(function (obj) { var choice = obj; if (choice.id === parseInt(action.choiceId, 10)) { choice.selected = true; } return choice; }); } return state; } case 'REMOVE_ITEM': { // When an item is removed and it has an associated choice, // we want to re-enable it so it can be chosen again if (action.choiceId > -1) { return state.map(function (obj) { var choice = obj; if (choice.id === parseInt(action.choiceId, 10)) { choice.selected = false; } return choice; }); } return state; } case 'FILTER_CHOICES': { return state.map(function (obj) { var choice = obj; // Set active state based on whether choice is // within filtered results choice.active = action.results.some(function (_ref) { var item = _ref.item, score = _ref.score; if (item.id === choice.id) { choice.score = score; return true; } return false; }); return choice; }); } case 'ACTIVATE_CHOICES': { return state.map(function (obj) { var choice = obj; choice.active = action.active; return choice; }); } case 'CLEAR_CHOICES': { return choices_defaultState; } default: { return state; } } } // CONCATENATED MODULE: ./src/scripts/reducers/general.js var general_defaultState = { loading: false }; var general = function general(state, action) { if (state === void 0) { state = general_defaultState; } switch (action.type) { case 'SET_IS_LOADING': { return { loading: action.isLoading }; } default: { return state; } } }; /* harmony default export */ var reducers_general = (general); // CONCATENATED MODULE: ./src/scripts/lib/utils.js /** * @param {number} min * @param {number} max * @returns {number} */ var getRandomNumber = function getRandomNumber(min, max) { return Math.floor(Math.random() * (max - min) + min); }; /** * @param {number} length * @returns {string} */ var generateChars = function generateChars(length) { return Array.from({ length: length }, function () { return getRandomNumber(0, 36).toString(36); }).join(''); }; /** * @param {HTMLInputElement | HTMLSelectElement} element * @param {string} prefix * @returns {string} */ var generateId = function generateId(element, prefix) { var id = element.id || element.name && element.name + "-" + generateChars(2) || generateChars(4); id = id.replace(/(:|\.|\[|\]|,)/g, ''); id = prefix + "-" + id; return id; }; /** * @param {any} obj * @returns {string} */ var getType = function getType(obj) { return Object.prototype.toString.call(obj).slice(8, -1); }; /** * @param {string} type * @param {any} obj * @returns {boolean} */ var isType = function isType(type, obj) { return obj !== undefined && obj !== null && getType(obj) === type; }; /** * @param {HTMLElement} element * @param {HTMLElement} [wrapper={HTMLDivElement}] * @returns {HTMLElement} */ var utils_wrap = function wrap(element, wrapper) { if (wrapper === void 0) { wrapper = document.createElement('div'); } if (element.nextSibling) { element.parentNode.insertBefore(wrapper, element.nextSibling); } else { element.parentNode.appendChild(wrapper); } return wrapper.appendChild(element); }; /** * @param {Element} startEl * @param {string} selector * @param {1 | -1} direction * @returns {Element | undefined} */ var getAdjacentEl = function getAdjacentEl(startEl, selector, direction) { if (direction === void 0) { direction = 1; } if (!(startEl instanceof Element) || typeof selector !== 'string') { return undefined; } var prop = (direction > 0 ? 'next' : 'previous') + "ElementSibling"; var sibling = startEl[prop]; while (sibling) { if (sibling.matches(selector)) { return sibling; } sibling = sibling[prop]; } return sibling; }; /** * @param {Element} element * @param {Element} parent * @param {-1 | 1} direction * @returns {boolean} */ var isScrolledIntoView = function isScrolledIntoView(element, parent, direction) { if (direction === void 0) { direction = 1; } if (!element) { return false; } var isVisible; if (direction > 0) { // In view from bottom isVisible = parent.scrollTop + parent.offsetHeight >= element.offsetTop + element.offsetHeight; } else { // In view from top isVisible = element.offsetTop >= parent.scrollTop; } return isVisible; }; /** * @param {any} value * @returns {any} */ var sanitise = function sanitise(value) { if (typeof value !== 'string') { return value; } return value.replace(/&/g, '&amp;').replace(/>/g, '&rt;').replace(/</g, '&lt;').replace(/"/g, '&quot;'); }; /** * @returns {() => (str: string) => Element} */ var strToEl = function () { var tmpEl = document.createElement('div'); return function (str) { var cleanedInput = str.trim(); tmpEl.innerHTML = cleanedInput; var firldChild = tmpEl.children[0]; while (tmpEl.firstChild) { tmpEl.removeChild(tmpEl.firstChild); } return firldChild; }; }(); /** * @param {{ label?: string, value: string }} a * @param {{ label?: string, value: string }} b * @returns {number} */ var sortByAlpha = function sortByAlpha(_ref, _ref2) { var value = _ref.value, _ref$label = _ref.label, label = _ref$label === void 0 ? value : _ref$label; var value2 = _ref2.value, _ref2$label = _ref2.label, label2 = _ref2$label === void 0 ? value2 : _ref2$label; return label.localeCompare(label2, [], { sensitivity: 'base', ignorePunctuation: true, numeric: true }); }; /** * @param {{ score: number }} a * @param {{ score: number }} b */ var sortByScore = function sortByScore(a, b) { return a.score - b.score; }; /** * @param {HTMLElement} element * @param {string} type * @param {object} customArgs */ var dispatchEvent = function dispatchEvent(element, type, customArgs) { if (customArgs === void 0) { customArgs = null; } var event = new CustomEvent(type, { detail: customArgs, bubbles: true, cancelable: true }); return element.dispatchEvent(event); }; /** * @param {array} array * @param {any} value * @param {string} [key="value"] * @returns {boolean} */ var existsInArray = function existsInArray(array, value, key) { if (key === void 0) { key = 'value'; } return array.some(function (item) { if (typeof value === 'string') { return item[key] === value.trim(); } return item[key] === value; }); }; /** * @param {any} obj * @returns {any} */ var cloneObject = function cloneObject(obj) { return JSON.parse(JSON.stringify(obj)); }; /** * Returns an array of keys present on the first but missing on the second object * @param {object} a * @param {object} b * @returns {string[]} */ var diff = function diff(a, b) { var aKeys = Object.keys(a).sort(); var bKeys = Object.keys(b).sort(); return aKeys.filter(function (i) { return bKeys.indexOf(i) < 0; }); }; // CONCATENATED MODULE: ./src/scripts/reducers/index.js var appReducer = combineReducers({ items: items_items, groups: groups, choices: choices_choices, general: reducers_general }); var reducers_rootReducer = function rootReducer(passedState, action) { var state = passedState; // If we are clearing all items, groups and options we reassign // state and then pass that state to our proper reducer. This isn't // mutating our actual state // See: http://stackoverflow.com/a/35641992 if (action.type === 'CLEAR_ALL') { state = undefined; } else if (action.type === 'RESET_TO') { return cloneObject(action.state); } return appReducer(state, action); }; /* harmony default export */ var reducers = (reducers_rootReducer); // CONCATENATED MODULE: ./src/scripts/store/store.js function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * @typedef {import('../../../types/index').Choices.Choice} Choice * @typedef {import('../../../types/index').Choices.Group} Group * @typedef {import('../../../types/index').Choices.Item} Item */ var store_Store = /*#__PURE__*/ function () { function Store() { this._store = createStore(reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); } /** * Subscribe store to function call (wrapped Redux method) * @param {Function} onChange Function to trigger when state changes * @return */ var _proto = Store.prototype; _proto.subscribe = function subscribe(onChange) { this._store.subscribe(onChange); } /** * Dispatch event to store (wrapped Redux method) * @param {{ type: string, [x: string]: any }} action Action to trigger * @return */ ; _proto.dispatch = function dispatch(action) { this._store.dispatch(action); } /** * Get store object (wrapping Redux method) * @returns {object} State */ ; /** * Get loading state from store * @returns {boolean} Loading State */ _proto.isLoading = function isLoading() { return this.state.general.loading; } /** * Get single choice by it's ID * @param {string} id * @returns {Choice | undefined} Found choice */ ; _proto.getChoiceById = function getChoiceById(id) { return this.activeChoices.find(function (choice) { return choice.id === parseInt(id, 10); }); } /** * Get group by group id * @param {number} id Group ID * @returns {Group | undefined} Group data */ ; _proto.getGroupById = function getGroupById(id) { return this.groups.find(function (group) { return group.id === id; }); }; _createClass(Store, [{ key: "state", get: function get() { return this._store.getState(); } /** * Get items from store * @returns {Item[]} Item objects */ }, { key: "items", get: function get() { return this.state.items; } /** * Get active items from store * @returns {Item[]} Item objects */ }, { key: "activeItems", get: function get() { return this.items.filter(function (item) { return item.active === true; }); } /** * Get highlighted items from store * @returns {Item[]} Item objects */ }, { key: "highlightedActiveItems", get: function get() { return this.items.filter(function (item) { return item.active && item.highlighted; }); } /** * Get choices from store * @returns {Choice[]} Option objects */ }, { key: "choices", get: function get() { return this.state.choices; } /** * Get active choices from store * @returns {Choice[]} Option objects */ }, { key: "activeChoices", get: function get() { return this.choices.filter(function (choice) { return choice.active === true; }); } /** * Get selectable choices from store * @returns {Choice[]} Option objects */ }, { key: "selectableChoices", get: function get() { return this.choices.filter(function (choice) { return choice.disabled !== true; }); } /** * Get choices that can be searched (excluding placeholders) * @returns {Choice[]} Option objects */ }, { key: "searchableChoices", get: function get() { return this.selectableChoices.filter(function (choice) { return choice.placeholder !== true; }); } /** * Get placeholder choice from store * @returns {Choice | undefined} Found placeholder */ }, { key: "placeholderChoice", get: function get() { return [].concat(this.choices).reverse().find(function (choice) { return choice.placeholder === true; }); } /** * Get groups from store * @returns {Group[]} Group objects */ }, { key: "groups", get: function get() { return this.state.groups; } /** * Get active groups from store * @returns {Group[]} Group objects */ }, { key: "activeGroups", get: function get() { var groups = this.groups, choices = this.choices; return groups.filter(function (group) { var isActive = group.active === true && group.disabled === false; var hasActiveOptions = choices.some(function (choice) { return choice.active === true && choice.disabled === false; }); return isActive && hasActiveOptions; }, []); } }]); return Store; }(); // CONCATENATED MODULE: ./src/scripts/components/dropdown.js function dropdown_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function dropdown_createClass(Constructor, protoProps, staticProps) { if (protoProps) dropdown_defineProperties(Constructor.prototype, protoProps); if (staticProps) dropdown_defineProperties(Constructor, staticProps); return Constructor; } /** * @typedef {import('../../../types/index').Choices.passedElement} passedElement * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames */ var Dropdown = /*#__PURE__*/ function () { /** * @param {{ * element: HTMLElement, * type: passedElement['type'], * classNames: ClassNames, * }} args */ function Dropdown(_ref) { var element = _ref.element, type = _ref.type, classNames = _ref.classNames; this.element = element; this.classNames = classNames; this.type = type; this.isActive = false; } /** * Bottom position of dropdown in viewport coordinates * @returns {number} Vertical position */ var _proto = Dropdown.prototype; /** * Find element that matches passed selector * @param {string} selector * @returns {HTMLElement | null} */ _proto.getChild = function getChild(selector) { return this.element.querySelector(selector); } /** * Show dropdown to user by adding active state class * @returns {this} */ ; _proto.show = function show() { this.element.classList.add(this.classNames.activeState); this.element.setAttribute('aria-expanded', 'true'); this.isActive = true; return this; } /** * Hide dropdown from user * @returns {this} */ ; _proto.hide = function hide() { this.element.classList.remove(this.classNames.activeState); this.element.setAttribute('aria-expanded', 'false'); this.isActive = false; return this; }; dropdown_createClass(Dropdown, [{ key: "distanceFromTopWindow", get: function get() { return this.element.getBoundingClientRect().bottom; } }]); return Dropdown; }(); // CONCATENATED MODULE: ./src/scripts/constants.js /** * @typedef {import('../../types/index').Choices.ClassNames} ClassNames * @typedef {import('../../types/index').Choices.Options} Options */ /** @type {ClassNames} */ var DEFAULT_CLASSNAMES = { containerOuter: 'choices', containerInner: 'choices__inner', input: 'choices__input', inputCloned: 'choices__input--cloned', list: 'choices__list', listItems: 'choices__list--multiple', listSingle: 'choices__list--single', listDropdown: 'choices__list--dropdown', item: 'choices__item', itemSelectable: 'choices__item--selectable', itemDisabled: 'choices__item--disabled', itemChoice: 'choices__item--choice', placeholder: 'choices__placeholder', group: 'choices__group', groupHeading: 'choices__heading', button: 'choices__button', activeState: 'is-active', focusState: 'is-focused', openState: 'is-open', disabledState: 'is-disabled', highlightedState: 'is-highlighted', selectedState: 'is-selected', flippedState: 'is-flipped', loadingState: 'is-loading', noResults: 'has-no-results', noChoices: 'has-no-choices' }; /** @type {Options} */ var DEFAULT_CONFIG = { items: [], choices: [], silent: false, renderChoiceLimit: -1, maxItemCount: -1, addItems: true, addItemFilter: null, removeItems: true, removeItemButton: false, editItems: false, duplicateItemsAllowed: true, delimiter: ',', paste: true, searchEnabled: true, searchChoices: true, searchFloor: 1, searchResultLimit: 4, searchFields: ['label', 'value'], position: 'auto', resetScrollPosition: true, shouldSort: true, shouldSortItems: false, sorter: sortByAlpha, placeholder: true, placeholderValue: null, searchPlaceholderValue: null, prependValue: null, appendValue: null, renderSelectedChoices: 'auto', loadingText: 'Loading...', noResultsText: 'No results found', noChoicesText: 'No choices to choose from', itemSelectText: 'Press to select', uniqueItemText: 'Only unique values can be added', customAddItemText: 'Only values matching specific conditions can be added', addItemText: function addItemText(value) { return "Press Enter to add <b>\"" + sanitise(value) + "\"</b>"; }, maxItemText: function maxItemText(maxItemCount) { return "Only " + maxItemCount + " values can be added"; }, valueComparer: function valueComparer(value1, value2) { return value1 === value2; }, fuseOptions: { includeScore: true }, callbackOnInit: null, callbackOnCreateTemplates: null, classNames: DEFAULT_CLASSNAMES }; var EVENTS = { showDropdown: 'showDropdown', hideDropdown: 'hideDropdown', change: 'change', choice: 'choice', search: 'search', addItem: 'addItem', removeItem: 'removeItem', highlightItem: 'highlightItem', highlightChoice: 'highlightChoice' }; var ACTION_TYPES = { ADD_CHOICE: 'ADD_CHOICE', FILTER_CHOICES: 'FILTER_CHOICES', ACTIVATE_CHOICES: 'ACTIVATE_CHOICES', CLEAR_CHOICES: 'CLEAR_CHOICES', ADD_GROUP: 'ADD_GROUP', ADD_ITEM: 'ADD_ITEM', REMOVE_ITEM: 'REMOVE_ITEM', HIGHLIGHT_ITEM: 'HIGHLIGHT_ITEM', CLEAR_ALL: 'CLEAR_ALL' }; var KEY_CODES = { BACK_KEY: 46, DELETE_KEY: 8, ENTER_KEY: 13, A_KEY: 65, ESC_KEY: 27, UP_KEY: 38, DOWN_KEY: 40, PAGE_UP_KEY: 33, PAGE_DOWN_KEY: 34 }; var TEXT_TYPE = 'text'; var SELECT_ONE_TYPE = 'select-one'; var SELECT_MULTIPLE_TYPE = 'select-multiple'; var SCROLLING_SPEED = 4; // CONCATENATED MODULE: ./src/scripts/components/container.js /** * @typedef {import('../../../types/index').Choices.passedElement} passedElement * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames */ var container_Container = /*#__PURE__*/ function () { /** * @param {{ * element: HTMLElement, * type: passedElement['type'], * classNames: ClassNames, * position * }} args */ function Container(_ref) { var element = _ref.element, type = _ref.type, classNames = _ref.classNames, position = _ref.position; this.element = element; this.classNames = classNames; this.type = type; this.position = position; this.isOpen = false; this.isFlipped = false; this.isFocussed = false; this.isDisabled = false; this.isLoading = false; this._onFocus = this._onFocus.bind(this); this._onBlur = this._onBlur.bind(this); } var _proto = Container.prototype; _proto.addEventListeners = function addEventListeners() { this.element.addEventListener('focus', this._onFocus); this.element.addEventListener('blur', this._onBlur); }; _proto.removeEventListeners = function removeEventListeners() { this.element.removeEventListener('focus', this._onFocus); this.element.removeEventListener('blur', this._onBlur); } /** * Determine whether container should be flipped based on passed * dropdown position * @param {number} dropdownPos * @returns {boolean} */ ; _proto.shouldFlip = function shouldFlip(dropdownPos) { if (typeof dropdownPos !== 'number') { return false; } // If flip is enabled and the dropdown bottom position is // greater than the window height flip the dropdown. var shouldFlip = false; if (this.position === 'auto') { shouldFlip = !window.matchMedia("(min-height: " + (dropdownPos + 1) + "px)").matches; } else if (this.position === 'top') { shouldFlip = true; } return shouldFlip; } /** * @param {string} activeDescendantID */ ; _proto.setActiveDescendant = function setActiveDescendant(activeDescendantID) { this.element.setAttribute('aria-activedescendant', activeDescendantID); }; _proto.removeActiveDescendant = function removeActiveDescendant() { this.element.removeAttribute('aria-activedescendant'); } /** * @param {number} dropdownPos */ ; _proto.open = function open(dropdownPos) { this.element.classList.add(this.classNames.openState); this.element.setAttribute('aria-expanded', 'true'); this.isOpen = true; if (this.shouldFlip(dropdownPos)) { this.element.classList.add(this.classNames.flippedState); this.isFlipped = true; } }; _proto.close = function close() { this.element.classList.remove(this.classNames.openState); this.element.setAttribute('aria-expanded', 'false'); this.removeActiveDescendant(); this.isOpen = false; // A dropdown flips if it does not have space within the page if (this.isFlipped) { this.element.classList.remove(this.classNames.flippedState); this.isFlipped = false; } }; _proto.focus = function focus() { if (!this.isFocussed) { this.element.focus(); } }; _proto.addFocusState = function addFocusState() { this.element.classList.add(this.classNames.focusState); }; _proto.removeFocusState = function removeFocusState() { this.element.classList.remove(this.classNames.focusState); }; _proto.enable = function enable() { this.element.classList.remove(this.classNames.disabledState); this.element.removeAttribute('aria-disabled'); if (this.type === SELECT_ONE_TYPE) { this.element.setAttribute('tabindex', '0'); } this.isDisabled = false; }; _proto.disable = function disable() { this.element.classList.add(this.classNames.disabledState); this.element.setAttribute('aria-disabled', 'true'); if (this.type === SELECT_ONE_TYPE) { this.element.setAttribute('tabindex', '-1'); } this.isDisabled = true; } /** * @param {HTMLElement} element */ ; _proto.wrap = function wrap(element) { utils_wrap(element, this.element); } /** * @param {Element} element */ ; _proto.unwrap = function unwrap(element) { // Move passed element outside this element this.element.parentNode.insertBefore(element, this.element); // Remove this element this.element.parentNode.removeChild(this.element); }; _proto.addLoadingState = function addLoadingState() { this.element.classList.add(this.classNames.loadingState); this.element.setAttribute('aria-busy', 'true'); this.isLoading = true; }; _proto.removeLoadingState = function removeLoadingState() { this.element.classList.remove(this.classNames.loadingState); this.element.removeAttribute('aria-busy'); this.isLoading = false; }; _proto._onFocus = function _onFocus() { this.isFocussed = true; }; _proto._onBlur = function _onBlur() { this.isFocussed = false; }; return Container; }(); // CONCATENATED MODULE: ./src/scripts/components/input.js function input_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function input_createClass(Constructor, protoProps, staticProps) { if (protoProps) input_defineProperties(Constructor.prototype, protoProps); if (staticProps) input_defineProperties(Constructor, staticProps); return Constructor; } /** * @typedef {import('../../../types/index').Choices.passedElement} passedElement * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames */ var input_Input = /*#__PURE__*/ function () { /** * @param {{ * element: HTMLInputElement, * type: passedElement['type'], * classNames: ClassNames, * preventPaste: boolean * }} args */ function Input(_ref) { var element = _ref.element, type = _ref.type, classNames = _ref.classNames, preventPaste = _ref.preventPaste; this.element = element; this.type = type; this.classNames = classNames; this.preventPaste = preventPaste; this.isFocussed = this.element === document.activeElement; this.isDisabled = element.disabled; this._onPaste = this._onPaste.bind(this); this._onInput = this._onInput.bind(this); this._onFocus = this._onFocus.bind(this); this._onBlur = this._onBlur.bind(this); } /** * @param {string} placeholder */ var _proto = Input.prototype; _proto.addEventListeners = function addEventListeners() { this.element.addEventListener('paste', this._onPaste); this.element.addEventListener('input', this._onInput, { passive: true }); this.element.addEventListener('focus', this._onFocus, { passive: true }); this.element.addEventListener('blur', this._onBlur, { passive: true }); }; _proto.removeEventListeners = function removeEventListeners() { this.element.removeEventListener('input', this._onInput, { passive: true }); this.element.removeEventListener('paste', this._onPaste); this.element.removeEventListener('focus', this._onFocus, { passive: true }); this.element.removeEventListener('blur', this._onBlur, { passive: true }); }; _proto.enable = function enable() { this.element.removeAttribute('disabled'); this.isDisabled = false; }; _proto.disable = function disable() { this.element.setAttribute('disabled', ''); this.isDisabled = true; }; _proto.focus = function focus() { if (!this.isFocussed) { this.element.focus(); } }; _proto.blur = function blur() { if (this.isFocussed) { this.element.blur(); } } /** * Set value of input to blank * @param {boolean} setWidth * @returns {this} */ ; _proto.clear = function clear(setWidth) { if (setWidth === void 0) { setWidth = true; } if (this.element.value) { this.element.value = ''; } if (setWidth) { this.setWidth(); } return this; } /** * Set the correct input width based on placeholder * value or input value */ ; _proto.setWidth = function setWidth() { // Resize input to contents or placeholder var _this$element = this.element, style = _this$element.style, value = _this$element.value, placeholder = _this$element.placeholder; style.minWidth = placeholder.length + 1 + "ch"; style.width = value.length + 1 + "ch"; } /** * @param {string} activeDescendantID */ ; _proto.setActiveDescendant = function setActiveDescendant(activeDescendantID) { this.element.setAttribute('aria-activedescendant', activeDescendantID); }; _proto.removeActiveDescendant = function removeActiveDescendant() { this.element.removeAttribute('aria-activedescendant'); }; _proto._onInput = function _onInput() { if (this.type !== SELECT_ONE_TYPE) { this.setWidth(); } } /** * @param {Event} event */ ; _proto._onPaste = function _onPaste(event) { if (this.preventPaste) { event.preventDefault(); } }; _proto._onFocus = function _onFocus() { this.isFocussed = true; }; _proto._onBlur = function _onBlur() { this.isFocussed = false; }; input_createClass(Input, [{ key: "placeholder", set: function set(placeholder) { this.element.placeholder = placeholder; } /** * @returns {string} */ }, { key: "value", get: function get() { return sanitise(this.element.value); } /** * @param {string} value */ , set: function set(value) { this.element.value = value; } }]); return Input; }(); // CONCATENATED MODULE: ./src/scripts/components/list.js /** * @typedef {import('../../../types/index').Choices.Choice} Choice */ var list_List = /*#__PURE__*/ function () { /** * @param {{ element: HTMLElement }} args */ function List(_ref) { var element = _ref.element; this.element = element; this.scrollPos = this.element.scrollTop; this.height = this.element.offsetHeight; } var _proto = List.prototype; _proto.clear = function clear() { this.element.innerHTML = ''; } /** * @param {Element | DocumentFragment} node */ ; _proto.append = function append(node) { this.element.appendChild(node); } /** * @param {string} selector * @returns {Element | null} */ ; _proto.getChild = function getChild(selector) { return this.element.querySelector(selector); } /** * @returns {boolean} */ ; _proto.hasChildren = function hasChildren() { return this.element.hasChildNodes(); }; _proto.scrollToTop = function scrollToTop() { this.element.scrollTop = 0; } /** * @param {Element} element * @param {1 | -1} direction */ ; _proto.scrollToChildElement = function scrollToChildElement(element, direction) { var _this = this; if (!element) { return; } var listHeight = this.element.offsetHeight; // Scroll position of dropdown var listScrollPosition = this.element.scrollTop + listHeight; var elementHeight = element.offsetHeight; // Distance from bottom of element to top of parent var elementPos = element.offsetTop + elementHeight; // Difference between the element and scroll position var destination = direction > 0 ? this.element.scrollTop + elementPos - listScrollPosition : element.offsetTop; requestAnimationFrame(function () { _this._animateScroll(destination, direction); }); } /** * @param {number} scrollPos * @param {number} strength * @param {number} destination */ ; _proto._scrollDown = function _scrollDown(scrollPos, strength, destination) { var easing = (destination - scrollPos) / strength; var distance = easing > 1 ? easing : 1; this.element.scrollTop = scrollPos + distance; } /** * @param {number} scrollPos * @param {number} strength * @param {number} destination */ ; _proto._scrollUp = function _scrollUp(scrollPos, strength, destination) { var easing = (scrollPos - destination) / strength; var distance = easing > 1 ? easing : 1; this.element.scrollTop = scrollPos - distance; } /** * @param {*} destination * @param {*} direction */ ; _proto._animateScroll = function _animateScroll(destination, direction) { var _this2 = this; var strength = SCROLLING_SPEED; var choiceListScrollTop = this.element.scrollTop; var continueAnimation = false; if (direction > 0) { this._scrollDown(choiceListScrollTop, strength, destination); if (choiceListScrollTop < destination) { continueAnimation = true; } } else { this._scrollUp(choiceListScrollTop, strength, destination); if (choiceListScrollTop > destination) { continueAnimation = true; } } if (continueAnimation) { requestAnimationFrame(function () { _this2._animateScroll(destination, direction); }); } }; return List; }(); // CONCATENATED MODULE: ./src/scripts/components/wrapped-element.js function wrapped_element_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function wrapped_element_createClass(Constructor, protoProps, staticProps) { if (protoProps) wrapped_element_defineProperties(Constructor.prototype, protoProps); if (staticProps) wrapped_element_defineProperties(Constructor, staticProps); return Constructor; } /** * @typedef {import('../../../types/index').Choices.passedElement} passedElement * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames */ var wrapped_element_WrappedElement = /*#__PURE__*/ function () { /** * @param {{ * element: HTMLInputElement | HTMLSelectElement, * classNames: ClassNames, * }} args */ function WrappedElement(_ref) { var element = _ref.element, classNames = _ref.classNames; this.element = element; this.classNames = classNames; if (!(element instanceof HTMLInputElement) && !(element instanceof HTMLSelectElement)) { throw new TypeError('Invalid element passed'); } this.isDisabled = false; } var _proto = WrappedElement.prototype; _proto.conceal = function conceal() { // Hide passed input this.element.classList.add(this.classNames.input); this.element.hidden = true; // Remove element from tab index this.element.tabIndex = -1; // Backup original styles if any var origStyle = this.element.getAttribute('style'); if (origStyle) { this.element.setAttribute('data-choice-orig-style', origStyle); } this.element.setAttribute('data-choice', 'active'); }; _proto.reveal = function reveal() { // Reinstate passed element this.element.classList.remove(this.classNames.input); this.element.hidden = false; this.element.removeAttribute('tabindex'); // Recover original styles if any var origStyle = this.element.getAttribute('data-choice-orig-style'); if (origStyle) { this.element.removeAttribute('data-choice-orig-style'); this.element.setAttribute('style', origStyle); } else { this.element.removeAttribute('style'); } this.element.removeAttribute('data-choice'); // Re-assign values - this is weird, I know // @todo Figure out why we need to do this this.element.value = this.element.value; // eslint-disable-line no-self-assign }; _proto.enable = function enable() { this.element.removeAttribute('disabled'); this.element.disabled = false; this.isDisabled = false; }; _proto.disable = function disable() { this.element.setAttribute('disabled', ''); this.element.disabled = true; this.isDisabled = true; }; _proto.triggerEvent = function triggerEvent(eventType, data) { dispatchEvent(this.element, eventType, data); }; wrapped_element_createClass(WrappedElement, [{ key: "isActive", get: function get() { return this.element.dataset.choice === 'active'; } }, { key: "dir", get: function get() { return this.element.dir; } }, { key: "value", get: function get() { return this.element.value; }, set: function set(value) { // you must define setter here otherwise it will be readonly property this.element.value = value; } }]); return WrappedElement; }(); // CONCATENATED MODULE: ./src/scripts/components/wrapped-input.js function wrapped_input_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function wrapped_input_createClass(Constructor, protoProps, staticProps) { if (protoProps) wrapped_input_defineProperties(Constructor.prototype, protoProps); if (staticProps) wrapped_input_defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames * @typedef {import('../../../types/index').Choices.Item} Item */ var WrappedInput = /*#__PURE__*/ function (_WrappedElement) { _inheritsLoose(WrappedInput, _WrappedElement); /** * @param {{ * element: HTMLInputElement, * classNames: ClassNames, * delimiter: string * }} args */ function WrappedInput(_ref) { var _this; var element = _ref.element, classNames = _ref.classNames, delimiter = _ref.delimiter; _this = _WrappedElement.call(this, { element: element, classNames: classNames }) || this; _this.delimiter = delimiter; return _this; } /** * @returns {string} */ wrapped_input_createClass(WrappedInput, [{ key: "value", get: function get() { return this.element.value; } /** * @param {Item[]} items */ , set: function set(items) { var itemValues = items.map(function (_ref2) { var value = _ref2.value; return value; }); var joinedValues = itemValues.join(this.delimiter); this.element.setAttribute('value', joinedValues); this.element.value = joinedValues; } }]); return WrappedInput; }(wrapped_element_WrappedElement); // CONCATENATED MODULE: ./src/scripts/components/wrapped-select.js function wrapped_select_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function wrapped_select_createClass(Constructor, protoProps, staticProps) { if (protoProps) wrapped_select_defineProperties(Constructor.prototype, protoProps); if (staticProps) wrapped_select_defineProperties(Constructor, staticProps); return Constructor; } function wrapped_select_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * @typedef {import('../../../types/index').Choices.ClassNames} ClassNames * @typedef {import('../../../types/index').Choices.Item} Item * @typedef {import('../../../types/index').Choices.Choice} Choice */ var WrappedSelect = /*#__PURE__*/ function (_WrappedElement) { wrapped_select_inheritsLoose(WrappedSelect, _WrappedElement); /** * @param {{ * element: HTMLSelectElement, * classNames: ClassNames, * delimiter: string * template: function * }} args */ function WrappedSelect(_ref) { var _this; var element = _ref.element, classNames = _ref.classNames, template = _ref.template; _this = _WrappedElement.call(this, { element: element, classNames: classNames }) || this; _this.template = template; return _this; } var _proto = WrappedSelect.prototype; /** * @param {DocumentFragment} fragment */ _proto.appendDocFragment = function appendDocFragment(fragment) { this.element.innerHTML = ''; this.element.appendChild(fragment); }; wrapped_select_createClass(WrappedSelect, [{ key: "placeholderOption", get: function get() { return this.element.querySelector('option[value=""]') || // Backward compatibility layer for the non-standard placeholder attribute supported in older versions. this.element.querySelector('option[placeholder]'); } /** * @returns {Element[]} */ }, { key: "optionGroups", get: function get() { return Array.from(this.element.getElementsByTagName('OPTGROUP')); } /** * @returns {Item[] | Choice[]} */ }, { key: "options", get: function get() { return Array.from(this.element.options); } /** * @param {Item[] | Choice[]} options */ , set: function set(options) { var _this2 = this; var fragment = document.createDocumentFragment(); var addOptionToFragment = function addOptionToFragment(data) { // Create a standard select option var option = _this2.template(data); // Append it to fragment fragment.appendChild(option); }; // Add each list item to list options.forEach(function (optionData) { return addOptionToFragment(optionData); }); this.appendDocFragment(fragment); } }]); return WrappedSelect; }(wrapped_element_WrappedElement); // CONCATENATED MODULE: ./src/scripts/components/index.js // CONCATENATED MODULE: ./src/scripts/templates.js /** * Helpers to create HTML elements used by Choices * Can be overridden by providing `callbackOnCreateTemplates` option * @typedef {import('../../types/index').Choices.Templates} Templates * @typedef {import('../../types/index').Choices.ClassNames} ClassNames * @typedef {import('../../types/index').Choices.Options} Options * @typedef {import('../../types/index').Choices.Item} Item * @typedef {import('../../types/index').Choices.Choice} Choice * @typedef {import('../../types/index').Choices.Group} Group */ var TEMPLATES = /** @type {Templates} */ { /** * @param {Partial<ClassNames>} classNames * @param {"ltr" | "rtl" | "auto"} dir * @param {boolean} isSelectElement * @param {boolean} isSelectOneElement * @param {boolean} searchEnabled * @param {"select-one" | "select-multiple" | "text"} passedElementType */ containerOuter: function containerOuter(_ref, dir, isSelectElement, isSelectOneElement, searchEnabled, passedElementType) { var _containerOuter = _ref.containerOuter; var div = Object.assign(document.createElement('div'), { className: _containerOuter }); div.dataset.type = passedElementType; if (dir) { div.dir = dir; } if (isSelectOneElement) { div.tabIndex = 0; } if (isSelectElement) { div.setAttribute('role', searchEnabled ? 'combobox' : 'listbox'); if (searchEnabled) { div.setAttribute('aria-autocomplete', 'list'); } } div.setAttribute('aria-haspopup', 'true'); div.setAttribute('aria-expanded', 'false'); return div; }, /** * @param {Partial<ClassNames>} classNames */ containerInner: function containerInner(_ref2) { var _containerInner = _ref2.containerInner; return Object.assign(document.createElement('div'), { className: _containerInner }); }, /** * @param {Partial<ClassNames>} classNames * @param {boolean} isSelectOneElement */ itemList: function itemList(_ref3, isSelectOneElement) { var list = _ref3.list, listSingle = _ref3.listSingle, listItems = _ref3.listItems; return Object.assign(document.createElement('div'), { className: list + " " + (isSelectOneElement ? listSingle : listItems) }); }, /** * @param {Partial<ClassNames>} classNames * @param {string} value */ placeholder: function placeholder(_ref4, value) { var _placeholder = _ref4.placeholder; return Object.assign(document.createElement('div'), { className: _placeholder, innerHTML: value }); }, /** * @param {Partial<ClassNames>} classNames * @param {Item} item * @param {boolean} removeItemButton */ item: function item(_ref5, _ref6, removeItemButton) { var _item = _ref5.item, button = _ref5.button, highlightedState = _ref5.highlightedState, itemSelectable = _ref5.itemSelectable, placeholder = _ref5.placeholder; var id = _ref6.id, value = _ref6.value, label = _ref6.label, customProperties = _ref6.customProperties, active = _ref6.active, disabled = _ref6.disabled, highlighted = _ref6.highlighted, isPlaceholder = _ref6.placeholder; var div = Object.assign(document.createElement('div'), { className: _item, innerHTML: label }); Object.assign(div.dataset, { item: '', id: id, value: value, customProperties: customProperties }); if (active) { div.setAttribute('aria-selected', 'true'); } if (disabled) { div.setAttribute('aria-disabled', 'true'); } if (isPlaceholder) { div.classList.add(placeholder); } div.classList.add(highlighted ? highlightedState : itemSelectable); if (removeItemButton) { if (disabled) { div.classList.remove(itemSelectable); } div.dataset.deletable = ''; /** @todo This MUST be localizable, not hardcoded! */ var REMOVE_ITEM_TEXT = 'Remove item'; var removeButton = Object.assign(document.createElement('button'), { type: 'button', className: button, innerHTML: REMOVE_ITEM_TEXT }); removeButton.setAttribute('aria-label', REMOVE_ITEM_TEXT + ": '" + value + "'"); removeButton.dataset.button = ''; div.appendChild(removeButton); } return div; }, /** * @param {Partial<ClassNames>} classNames * @param {boolean} isSelectOneElement */ choiceList: function choiceList(_ref7, isSelectOneElement) { var list = _ref7.list; var div = Object.assign(document.createElement('div'), { className: list }); if (!isSelectOneElement) { div.setAttribute('aria-multiselectable', 'true'); } div.setAttribute('role', 'listbox'); return div; }, /** * @param {Partial<ClassNames>} classNames * @param {Group} group */ choiceGroup: function choiceGroup(_ref8, _ref9) { var group = _ref8.group, groupHeading = _ref8.groupHeading, itemDisabled = _ref8.itemDisabled; var id = _ref9.id, value = _ref9.value, disabled = _ref9.disabled; var div = Object.assign(document.createElement('div'), { className: group + " " + (disabled ? itemDisabled : '') }); div.setAttribute('role', 'group'); Object.assign(div.dataset, { group: '', id: id, value: value }); if (disabled) { div.setAttribute('aria-disabled', 'true'); } div.appendChild(Object.assign(document.createElement('div'), { className: groupHeading, innerHTML: value })); return div; }, /** * @param {Partial<ClassNames>} classNames * @param {Choice} choice * @param {Options['itemSelectText']} selectText */ choice: function choice(_ref10, _ref11, selectText) { var item = _ref10.item, itemChoice = _ref10.itemChoice, itemSelectable = _ref10.itemSelectable, selectedState = _ref10.selectedState, itemDisabled = _ref10.itemDisabled, placeholder = _ref10.placeholder; var id = _ref11.id, value = _ref11.value, label = _ref11.label, groupId = _ref11.groupId, elementId = _ref11.elementId, isDisabled = _ref11.disabled, isSelected = _ref11.selected, isPlaceholder = _ref11.placeholder; var div = Object.assign(document.createElement('div'), { id: elementId, innerHTML: label, className: item + " " + itemChoice }); if (isSelected) { div.classList.add(selectedState); } if (isPlaceholder) { div.classList.add(placeholder); } div.setAttribute('role', groupId > 0 ? 'treeitem' : 'option'); Object.assign(div.dataset, { choice: '', id: id, value: value, selectText: selectText }); if (isDisabled) { div.classList.add(itemDisabled); div.dataset.choiceDisabled = ''; div.setAttribute('aria-disabled', 'true'); } else { div.classList.add(itemSelectable); div.dataset.choiceSelectable = ''; } return div; }, /** * @param {Partial<ClassNames>} classNames * @param {string} placeholderValue */ input: function input(_ref12, placeholderValue) { var _input = _ref12.input, inputCloned = _ref12.inputCloned; var inp = Object.assign(document.createElement('input'), { type: 'text', className: _input + " " + inputCloned, autocomplete: 'off', autocapitalize: 'off', spellcheck: false }); inp.setAttribute('role', 'textbox'); inp.setAttribute('aria-autocomplete', 'list'); inp.setAttribute('aria-label', placeholderValue); return inp; }, /** * @param {Partial<ClassNames>} classNames */ dropdown: function dropdown(_ref13) { var list = _ref13.list, listDropdown = _ref13.listDropdown; var div = document.createElement('div'); div.classList.add(list, listDropdown); div.setAttribute('aria-expanded', 'false'); return div; }, /** * * @param {Partial<ClassNames>} classNames * @param {string} innerHTML * @param {"no-choices" | "no-results" | ""} type */ notice: function notice(_ref14, innerHTML, type) { var item = _ref14.item, itemChoice = _ref14.itemChoice, noResults = _ref14.noResults, noChoices = _ref14.noChoices; if (type === void 0) { type = ''; } var classes = [item, itemChoice]; if (type === 'no-choices') { classes.push(noChoices); } else if (type === 'no-results') { classes.push(noResults); } return Object.assign(document.createElement('div'), { innerHTML: innerHTML, className: classes.join(' ') }); }, /** * @param {Item} option */ option: function option(_ref15) { var label = _ref15.label, value = _ref15.value, customProperties = _ref15.customProperties, active = _ref15.active, disabled = _ref15.disabled; var opt = new Option(label, value, false, active); if (customProperties) { opt.dataset.customProperties = customProperties; } opt.disabled = disabled; return opt; } }; /* harmony default export */ var templates = (TEMPLATES); // CONCATENATED MODULE: ./src/scripts/actions/choices.js /** * @typedef {import('redux').Action} Action * @typedef {import('../../../types/index').Choices.Choice} Choice */ /** * @argument {Choice} choice * @returns {Action & Choice} */ var choices_addChoice = function addChoice(_ref) { var value = _ref.value, label = _ref.label, id = _ref.id, groupId = _ref.groupId, disabled = _ref.disabled, elementId = _ref.elementId, customProperties = _ref.customProperties, placeholder = _ref.placeholder, keyCode = _ref.keyCode; return { type: ACTION_TYPES.ADD_CHOICE, value: value, label: label, id: id, groupId: groupId, disabled: disabled, elementId: elementId, customProperties: customProperties, placeholder: placeholder, keyCode: keyCode }; }; /** * @argument {Choice[]} results * @returns {Action & { results: Choice[] }} */ var choices_filterChoices = function filterChoices(results) { return { type: ACTION_TYPES.FILTER_CHOICES, results: results }; }; /** * @argument {boolean} active * @returns {Action & { active: boolean }} */ var choices_activateChoices = function activateChoices(active) { if (active === void 0) { active = true; } return { type: ACTION_TYPES.ACTIVATE_CHOICES, active: active }; }; /** * @returns {Action} */ var choices_clearChoices = function clearChoices() { return { type: ACTION_TYPES.CLEAR_CHOICES }; }; // CONCATENATED MODULE: ./src/scripts/actions/items.js /** * @typedef {import('redux').Action} Action * @typedef {import('../../../types/index').Choices.Item} Item */ /** * @param {Item} item * @returns {Action & Item} */ var items_addItem = function addItem(_ref) { var value = _ref.value, label = _ref.label, id = _ref.id, choiceId = _ref.choiceId, groupId = _ref.groupId, customProperties = _ref.customProperties, placeholder = _ref.placeholder, keyCode = _ref.keyCode; return { type: ACTION_TYPES.ADD_ITEM, value: value, label: label, id: id, choiceId: choiceId, groupId: groupId, customProperties: customProperties, placeholder: placeholder, keyCode: keyCode }; }; /** * @param {string} id * @param {string} choiceId * @returns {Action & { id: string, choiceId: string }} */ var items_removeItem = function removeItem(id, choiceId) { return { type: ACTION_TYPES.REMOVE_ITEM, id: id, choiceId: choiceId }; }; /** * @param {string} id * @param {boolean} highlighted * @returns {Action & { id: string, highlighted: boolean }} */ var items_highlightItem = function highlightItem(id, highlighted) { return { type: ACTION_TYPES.HIGHLIGHT_ITEM, id: id, highlighted: highlighted }; }; // CONCATENATED MODULE: ./src/scripts/actions/groups.js /** * @typedef {import('redux').Action} Action * @typedef {import('../../../types/index').Choices.Group} Group */ /** * @param {Group} group * @returns {Action & Group} */ var groups_addGroup = function addGroup(_ref) { var value = _ref.value, id = _ref.id, active = _ref.active, disabled = _ref.disabled; return { type: ACTION_TYPES.ADD_GROUP, value: value, id: id, active: active, disabled: disabled }; }; // CONCATENATED MODULE: ./src/scripts/actions/misc.js /** * @typedef {import('redux').Action} Action */ /** * @returns {Action} */ var clearAll = function clearAll() { return { type: 'CLEAR_ALL' }; }; /** * @param {any} state * @returns {Action & { state: object }} */ var resetTo = function resetTo(state) { return { type: 'RESET_TO', state: state }; }; /** * @param {boolean} isLoading * @returns {Action & { isLoading: boolean }} */ var setIsLoading = function setIsLoading(isLoading) { return { type: 'SET_IS_LOADING', isLoading: isLoading }; }; // CONCATENATED MODULE: ./src/scripts/choices.js function choices_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function choices_createClass(Constructor, protoProps, staticProps) { if (protoProps) choices_defineProperties(Constructor.prototype, protoProps); if (staticProps) choices_defineProperties(Constructor, staticProps); return Constructor; } /** @see {@link http://browserhacks.com/#hack-acea075d0ac6954f275a70023906050c} */ var IS_IE11 = '-ms-scroll-limit' in document.documentElement.style && '-ms-ime-align' in document.documentElement.style; /** * @typedef {import('../../types/index').Choices.Choice} Choice * @typedef {import('../../types/index').Choices.Item} Item * @typedef {import('../../types/index').Choices.Group} Group * @typedef {import('../../types/index').Choices.Options} Options */ /** @type {Partial<Options>} */ var USER_DEFAULTS = {}; /** * Choices * @author Josh Johnson<josh@joshuajohnson.co.uk> */ var choices_Choices = /*#__PURE__*/ function () { choices_createClass(Choices, null, [{ key: "defaults", get: function get() { return Object.preventExtensions({ get options() { return USER_DEFAULTS; }, get templates() { return TEMPLATES; } }); } /** * @param {string | HTMLInputElement | HTMLSelectElement} element * @param {Partial<Options>} userConfig */ }]); function Choices(element, userConfig) { var _this = this; if (element === void 0) { element = '[data-choice]'; } if (userConfig === void 0) { userConfig = {}; } /** @type {Partial<Options>} */ this.config = cjs_default.a.all([DEFAULT_CONFIG, Choices.defaults.options, userConfig], // When merging array configs, replace with a copy of the userConfig array, // instead of concatenating with the default array { arrayMerge: function arrayMerge(_, sourceArray) { return [].concat(sourceArray); } }); var invalidConfigOptions = diff(this.config, DEFAULT_CONFIG); if (invalidConfigOptions.length) { console.warn('Unknown config option(s) passed', invalidConfigOptions.join(', ')); } var passedElement = typeof element === 'string' ? document.querySelector(element) : element; if (!(passedElement instanceof HTMLInputElement || passedElement instanceof HTMLSelectElement)) { throw TypeError('Expected one of the following types text|select-one|select-multiple'); } this._isTextElement = passedElement.type === TEXT_TYPE; this._isSelectOneElement = passedElement.type === SELECT_ONE_TYPE; this._isSelectMultipleElement = passedElement.type === SELECT_MULTIPLE_TYPE; this._isSelectElement = this._isSelectOneElement || this._isSelectMultipleElement; this.config.searchEnabled = this._isSelectMultipleElement || this.config.searchEnabled; if (!['auto', 'always'].includes(this.config.renderSelectedChoices)) { this.config.renderSelectedChoices = 'auto'; } if (userConfig.addItemFilter && typeof userConfig.addItemFilter !== 'function') { var re = userConfig.addItemFilter instanceof RegExp ? userConfig.addItemFilter : new RegExp(userConfig.addItemFilter); this.config.addItemFilter = re.test.bind(re); } if (this._isTextElement) { this.passedElement = new WrappedInput({ element: passedElement, classNames: this.config.classNames, delimiter: this.config.delimiter }); } else { this.passedElement = new WrappedSelect({ element: passedElement, classNames: this.config.classNames, template: function template(data) { return _this._templates.option(data); } }); } this.initialised = false; this._store = new store_Store(); this._initialState = {}; this._currentState = {}; this._prevState = {}; this._currentValue = ''; this._canSearch = this.config.searchEnabled; this._isScrollingOnIe = false; this._highlightPosition = 0; this._wasTap = true; this._placeholderValue = this._generatePlaceholderValue(); this._baseId = generateId(this.passedElement.element, 'choices-'); /** * setting direction in cases where it's explicitly set on passedElement * or when calculated direction is different from the document * @type {HTMLElement['dir']} */ this._direction = this.passedElement.dir; if (!this._direction) { var _window$getComputedSt = window.getComputedStyle(this.passedElement.element), elementDirection = _window$getComputedSt.direction; var _window$getComputedSt2 = window.getComputedStyle(document.documentElement), documentDirection = _window$getComputedSt2.direction; if (elementDirection !== documentDirection) { this._direction = elementDirection; } } this._idNames = { itemChoice: 'item-choice' }; // Assign preset groups from passed element this._presetGroups = this.passedElement.optionGroups; // Assign preset options from passed element this._presetOptions = this.passedElement.options; // Assign preset choices from passed object this._presetChoices = this.config.choices; // Assign preset items from passed object first this._presetItems = this.config.items; // Add any values passed from attribute if (this.passedElement.value) { this._presetItems = this._presetItems.concat(this.passedElement.value.split(this.config.delimiter)); } // Create array of choices from option elements if (this.passedElement.options) { this.passedElement.options.forEach(function (o) { _this._presetChoices.push({ value: o.value, label: o.innerHTML, selected: o.selected, disabled: o.disabled || o.parentNode.disabled, placeholder: o.value === '' || o.hasAttribute('placeholder'), customProperties: o.getAttribute('data-custom-properties') }); }); } this._render = this._render.bind(this); this._onFocus = this._onFocus.bind(this); this._onBlur = this._onBlur.bind(this); this._onKeyUp = this._onKeyUp.bind(this); this._onKeyDown = this._onKeyDown.bind(this); this._onClick = this._onClick.bind(this); this._onTouchMove = this._onTouchMove.bind(this); this._onTouchEnd = this._onTouchEnd.bind(this); this._onMouseDown = this._onMouseDown.bind(this); this._onMouseOver = this._onMouseOver.bind(this); this._onFormReset = this._onFormReset.bind(this); this._onAKey = this._onAKey.bind(this); this._onEnterKey = this._onEnterKey.bind(this); this._onEscapeKey = this._onEscapeKey.bind(this); this._onDirectionKey = this._onDirectionKey.bind(this); this._onDeleteKey = this._onDeleteKey.bind(this); // If element has already been initialised with Choices, fail silently if (this.passedElement.isActive) { if (!this.config.silent) { console.warn('Trying to initialise Choices on element already initialised'); } this.initialised = true; return; } // Let's go this.init(); } var _proto = Choices.prototype; _proto.init = function init() { if (this.initialised) { return; } this._createTemplates(); this._createElements(); this._createStructure(); // Set initial state (We need to clone the state because some reducers // modify the inner objects properties in the state) 🤢 this._initialState = cloneObject(this._store.state); this._store.subscribe(this._render); this._render(); this._addEventListeners(); var shouldDisable = !this.config.addItems || this.passedElement.element.hasAttribute('disabled'); if (shouldDisable) { this.disable(); } this.initialised = true; var callbackOnInit = this.config.callbackOnInit; // Run callback if it is a function if (callbackOnInit && typeof callbackOnInit === 'function') { callbackOnInit.call(this); } }; _proto.destroy = function destroy() { if (!this.initialised) { return; } this._removeEventListeners(); this.passedElement.reveal(); this.containerOuter.unwrap(this.passedElement.element); this.clearStore(); if (this._isSelectElement) { this.passedElement.options = this._presetOptions; } this._templates = null; this.initialised = false; }; _proto.enable = function enable() { if (this.passedElement.isDisabled) { this.passedElement.enable(); } if (this.containerOuter.isDisabled) { this._addEventListeners(); this.input.enable(); this.containerOuter.enable(); } return this; }; _proto.disable = function disable() { if (!this.passedElement.isDisabled) { this.passedElement.disable(); } if (!this.containerOuter.isDisabled) { this._removeEventListeners(); this.input.disable(); this.containerOuter.disable(); } return this; }; _proto.highlightItem = function highlightItem(item, runEvent) { if (runEvent === void 0) { runEvent = true; } if (!item) { return this; } var id = item.id, _item$groupId = item.groupId, groupId = _item$groupId === void 0 ? -1 : _item$groupId, _item$value = item.value, value = _item$value === void 0 ? '' : _item$value, _item$label = item.label, label = _item$label === void 0 ? '' : _item$label; var group = groupId >= 0 ? this._store.getGroupById(groupId) : null; this._store.dispatch(items_highlightItem(id, true)); if (runEvent) { this.passedElement.triggerEvent(EVENTS.highlightItem, { id: id, value: value, label: label, groupValue: group && group.value ? group.value : null }); } return this; }; _proto.unhighlightItem = function unhighlightItem(item) { if (!item) { return this; } var id = item.id, _item$groupId2 = item.groupId, groupId = _item$groupId2 === void 0 ? -1 : _item$groupId2, _item$value2 = item.value, value = _item$value2 === void 0 ? '' : _item$value2, _item$label2 = item.label, label = _item$label2 === void 0 ? '' : _item$label2; var group = groupId >= 0 ? this._store.getGroupById(groupId) : null; this._store.dispatch(items_highlightItem(id, false)); this.passedElement.triggerEvent(EVENTS.highlightItem, { id: id, value: value, label: label, groupValue: group && group.value ? group.value : null }); return this; }; _proto.highlightAll = function highlightAll() { var _this2 = this; this._store.items.forEach(function (item) { return _this2.highlightItem(item); }); return this; }; _proto.unhighlightAll = function unhighlightAll() { var _this3 = this; this._store.items.forEach(function (item) { return _this3.unhighlightItem(item); }); return this; }; _proto.removeActiveItemsByValue = function removeActiveItemsByValue(value) { var _this4 = this; this._store.activeItems.filter(function (item) { return item.value === value; }).forEach(function (item) { return _this4._removeItem(item); }); return this; }; _proto.removeActiveItems = function removeActiveItems(excludedId) { var _this5 = this; this._store.activeItems.filter(function (_ref) { var id = _ref.id; return id !== excludedId; }).forEach(function (item) { return _this5._removeItem(item); }); return this; }; _proto.removeHighlightedItems = function removeHighlightedItems(runEvent) { var _this6 = this; if (runEvent === void 0) { runEvent = false; } this._store.highlightedActiveItems.forEach(function (item) { _this6._removeItem(item); // If this action was performed by the user // trigger the event if (runEvent) { _this6._triggerChange(item.value); } }); return this; }; _proto.showDropdown = function showDropdown(preventInputFocus) { var _this7 = this; if (this.dropdown.isActive) { return this; } requestAnimationFrame(function () { _this7.dropdown.show(); _this7.containerOuter.open(_this7.dropdown.distanceFromTopWindow); if (!preventInputFocus && _this7._canSearch) { _this7.input.focus(); } _this7.passedElement.triggerEvent(EVENTS.showDropdown, {}); }); return this; }; _proto.hideDropdown = function hideDropdown(preventInputBlur) { var _this8 = this; if (!this.dropdown.isActive) { return this; } requestAnimationFrame(function () { _this8.dropdown.hide(); _this8.containerOuter.close(); if (!preventInputBlur && _this8._canSearch) { _this8.input.removeActiveDescendant(); _this8.input.blur(); } _this8.passedElement.triggerEvent(EVENTS.hideDropdown, {}); }); return this; }; _proto.getValue = function getValue(valueOnly) { if (valueOnly === void 0) { valueOnly = false; } var values = this._store.activeItems.reduce(function (selectedItems, item) { var itemValue = valueOnly ? item.value : item; selectedItems.push(itemValue); return selectedItems; }, []); return this._isSelectOneElement ? values[0] : values; } /** * @param {string[] | import('../../types/index').Choices.Item[]} items */ ; _proto.setValue = function setValue(items) { var _this9 = this; if (!this.initialised) { return this; } items.forEach(function (value) { return _this9._setChoiceOrItem(value); }); return this; }; _proto.setChoiceByValue = function setChoiceByValue(value) { var _this10 = this; if (!this.initialised || this._isTextElement) { return this; } // If only one value has been passed, convert to array var choiceValue = Array.isArray(value) ? value : [value]; // Loop through each value and choiceValue.forEach(function (val) { return _this10._findAndSelectChoiceByValue(val); }); return this; } /** * Set choices of select input via an array of objects (or function that returns array of object or promise of it), * a value field name and a label field name. * This behaves the same as passing items via the choices option but can be called after initialising Choices. * This can also be used to add groups of choices (see example 2); Optionally pass a true `replaceChoices` value to remove any existing choices. * Optionally pass a `customProperties` object to add additional data to your choices (useful when searching/filtering etc). * * **Input types affected:** select-one, select-multiple * * @template {Choice[] | ((instance: Choices) => object[] | Promise<object[]>)} T * @param {T} [choicesArrayOrFetcher] * @param {string} [value = 'value'] - name of `value` field * @param {string} [label = 'label'] - name of 'label' field * @param {boolean} [replaceChoices = false] - whether to replace of add choices * @returns {this | Promise<this>} * * @example * ```js * const example = new Choices(element); * * example.setChoices([ * {value: 'One', label: 'Label One', disabled: true}, * {value: 'Two', label: 'Label Two', selected: true}, * {value: 'Three', label: 'Label Three'}, * ], 'value', 'label', false); * ``` * * @example * ```js * const example = new Choices(element); * * example.setChoices(async () => { * try { * const items = await fetch('/items'); * return items.json() * } catch(err) { * console.error(err) * } * }); * ``` * * @example * ```js * const example = new Choices(element); * * example.setChoices([{ * label: 'Group one', * id: 1, * disabled: false, * choices: [ * {value: 'Child One', label: 'Child One', selected: true}, * {value: 'Child Two', label: 'Child Two', disabled: true}, * {value: 'Child Three', label: 'Child Three'}, * ] * }, * { * label: 'Group two', * id: 2, * disabled: false, * choices: [ * {value: 'Child Four', label: 'Child Four', disabled: true}, * {value: 'Child Five', label: 'Child Five'}, * {value: 'Child Six', label: 'Child Six', customProperties: { * description: 'Custom description about child six', * random: 'Another random custom property' * }}, * ] * }], 'value', 'label', false); * ``` */ ; _proto.setChoices = function setChoices(choicesArrayOrFetcher, value, label, replaceChoices) { var _this11 = this; if (choicesArrayOrFetcher === void 0) { choicesArrayOrFetcher = []; } if (value === void 0) { value = 'value'; } if (label === void 0) { label = 'label'; } if (replaceChoices === void 0) { replaceChoices = false; } if (!this.initialised) { throw new ReferenceError("setChoices was called on a non-initialized instance of Choices"); } if (!this._isSelectElement) { throw new TypeError("setChoices can't be used with INPUT based Choices"); } if (typeof value !== 'string' || !value) { throw new TypeError("value parameter must be a name of 'value' field in passed objects"); } // Clear choices if needed if (replaceChoices) { this.clearChoices(); } if (typeof choicesArrayOrFetcher === 'function') { // it's a choices fetcher function var fetcher = choicesArrayOrFetcher(this); if (typeof Promise === 'function' && fetcher instanceof Promise) { // that's a promise // eslint-disable-next-line compat/compat return new Promise(function (resolve) { return requestAnimationFrame(resolve); }).then(function () { return _this11._handleLoadingState(true); }).then(function () { return fetcher; }).then(function (data) { return _this11.setChoices(data, value, label, replaceChoices); }).catch(function (err) { if (!_this11.config.silent) { console.error(err); } }).then(function () { return _this11._handleLoadingState(false); }).then(function () { return _this11; }); } // function returned something else than promise, let's check if it's an array of choices if (!Array.isArray(fetcher)) { throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: " + typeof fetcher); } // recursion with results, it's sync and choices were cleared already return this.setChoices(fetcher, value, label, false); } if (!Array.isArray(choicesArrayOrFetcher)) { throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices"); } this.containerOuter.removeLoadingState(); this._startLoading(); choicesArrayOrFetcher.forEach(function (groupOrChoice) { if (groupOrChoice.choices) { _this11._addGroup({ id: parseInt(groupOrChoice.id, 10) || null, group: groupOrChoice, valueKey: value, labelKey: label }); } else { _this11._addChoice({ value: groupOrChoice[value], label: groupOrChoice[label], isSelected: groupOrChoice.selected, isDisabled: groupOrChoice.disabled, customProperties: groupOrChoice.customProperties, placeholder: groupOrChoice.placeholder }); } }); this._stopLoading(); return this; }; _proto.clearChoices = function clearChoices() { this._store.dispatch(choices_clearChoices()); return this; }; _proto.clearStore = function clearStore() { this._store.dispatch(clearAll()); return this; }; _proto.clearInput = function clearInput() { var shouldSetInputWidth = !this._isSelectOneElement; this.input.clear(shouldSetInputWidth); if (!this._isTextElement && this._canSearch) { this._isSearching = false; this._store.dispatch(choices_activateChoices(true)); } return this; }; _proto._render = function _render() { if (this._store.isLoading()) { return; } this._currentState = this._store.state; var stateChanged = this._currentState.choices !== this._prevState.choices || this._currentState.groups !== this._prevState.groups || this._currentState.items !== this._prevState.items; var shouldRenderChoices = this._isSelectElement; var shouldRenderItems = this._currentState.items !== this._prevState.items; if (!stateChanged) { return; } if (shouldRenderChoices) { this._renderChoices(); } if (shouldRenderItems) { this._renderItems(); } this._prevState = this._currentState; }; _proto._renderChoices = function _renderChoices() { var _this12 = this; var _this$_store = this._store, activeGroups = _this$_store.activeGroups, activeChoices = _this$_store.activeChoices; var choiceListFragment = document.createDocumentFragment(); this.choiceList.clear(); if (this.config.resetScrollPosition) { requestAnimationFrame(function () { return _this12.choiceList.scrollToTop(); }); } // If we have grouped options if (activeGroups.length >= 1 && !this._isSearching) { // If we have a placeholder choice along with groups var activePlaceholders = activeChoices.filter(function (activeChoice) { return activeChoice.placeholder === true && activeChoice.groupId === -1; }); if (activePlaceholders.length >= 1) { choiceListFragment = this._createChoicesFragment(activePlaceholders, choiceListFragment); } choiceListFragment = this._createGroupsFragment(activeGroups, activeChoices, choiceListFragment); } else if (activeChoices.length >= 1) { choiceListFragment = this._createChoicesFragment(activeChoices, choiceListFragment); } // If we have choices to show if (choiceListFragment.childNodes && choiceListFragment.childNodes.length > 0) { var activeItems = this._store.activeItems; var canAddItem = this._canAddItem(activeItems, this.input.value); // ...and we can select them if (canAddItem.response) { // ...append them and highlight the first choice this.choiceList.append(choiceListFragment); this._highlightChoice(); } else { // ...otherwise show a notice this.choiceList.append(this._getTemplate('notice', canAddItem.notice)); } } else { // Otherwise show a notice var dropdownItem; var notice; if (this._isSearching) { notice = typeof this.config.noResultsText === 'function' ? this.config.noResultsText() : this.config.noResultsText; dropdownItem = this._getTemplate('notice', notice, 'no-results'); } else { notice = typeof this.config.noChoicesText === 'function' ? this.config.noChoicesText() : this.config.noChoicesText; dropdownItem = this._getTemplate('notice', notice, 'no-choices'); } this.choiceList.append(dropdownItem); } }; _proto._renderItems = function _renderItems() { var activeItems = this._store.activeItems || []; this.itemList.clear(); // Create a fragment to store our list items // (so we don't have to update the DOM for each item) var itemListFragment = this._createItemsFragment(activeItems); // If we have items to add, append them if (itemListFragment.childNodes) { this.itemList.append(itemListFragment); } }; _proto._createGroupsFragment = function _createGroupsFragment(groups, choices, fragment) { var _this13 = this; if (fragment === void 0) { fragment = document.createDocumentFragment(); } var getGroupChoices = function getGroupChoices(group) { return choices.filter(function (choice) { if (_this13._isSelectOneElement) { return choice.groupId === group.id; } return choice.groupId === group.id && (_this13.config.renderSelectedChoices === 'always' || !choice.selected); }); }; // If sorting is enabled, filter groups if (this.config.shouldSort) { groups.sort(this.config.sorter); } groups.forEach(function (group) { var groupChoices = getGroupChoices(group); if (groupChoices.length >= 1) { var dropdownGroup = _this13._getTemplate('choiceGroup', group); fragment.appendChild(dropdownGroup); _this13._createChoicesFragment(groupChoices, fragment, true); } }); return fragment; }; _proto._createChoicesFragment = function _createChoicesFragment(choices, fragment, withinGroup) { var _this14 = this; if (fragment === void 0) { fragment = document.createDocumentFragment(); } if (withinGroup === void 0) { withinGroup = false; } // Create a fragment to store our list items (so we don't have to update the DOM for each item) var _this$config = this.config, renderSelectedChoices = _this$config.renderSelectedChoices, searchResultLimit = _this$config.searchResultLimit, renderChoiceLimit = _this$config.renderChoiceLimit; var filter = this._isSearching ? sortByScore : this.config.sorter; var appendChoice = function appendChoice(choice) { var shouldRender = renderSelectedChoices === 'auto' ? _this14._isSelectOneElement || !choice.selected : true; if (shouldRender) { var dropdownItem = _this14._getTemplate('choice', choice, _this14.config.itemSelectText); fragment.appendChild(dropdownItem); } }; var rendererableChoices = choices; if (renderSelectedChoices === 'auto' && !this._isSelectOneElement) { rendererableChoices = choices.filter(function (choice) { return !choice.selected; }); } // Split array into placeholders and "normal" choices var _rendererableChoices$ = rendererableChoices.reduce(function (acc, choice) { if (choice.placeholder) { acc.placeholderChoices.push(choice); } else { acc.normalChoices.push(choice); } return acc; }, { placeholderChoices: [], normalChoices: [] }), placeholderChoices = _rendererableChoices$.placeholderChoices, normalChoices = _rendererableChoices$.normalChoices; // If sorting is enabled or the user is searching, filter choices if (this.config.shouldSort || this._isSearching) { normalChoices.sort(filter); } var choiceLimit = rendererableChoices.length; // Prepend placeholeder var sortedChoices = this._isSelectOneElement ? [].concat(placeholderChoices, normalChoices) : normalChoices; if (this._isSearching) { choiceLimit = searchResultLimit; } else if (renderChoiceLimit && renderChoiceLimit > 0 && !withinGroup) { choiceLimit = renderChoiceLimit; } // Add each choice to dropdown within range for (var i = 0; i < choiceLimit; i += 1) { if (sortedChoices[i]) { appendChoice(sortedChoices[i]); } } return fragment; }; _proto._createItemsFragment = function _createItemsFragment(items, fragment) { var _this15 = this; if (fragment === void 0) { fragment = document.createDocumentFragment(); } // Create fragment to add elements to var _this$config2 = this.config, shouldSortItems = _this$config2.shouldSortItems, sorter = _this$config2.sorter, removeItemButton = _this$config2.removeItemButton; // If sorting is enabled, filter items if (shouldSortItems && !this._isSelectOneElement) { items.sort(sorter); } if (this._isTextElement) { // Update the value of the hidden input this.passedElement.value = items; } else { // Update the options of the hidden input this.passedElement.options = items; } var addItemToFragment = function addItemToFragment(item) { // Create new list element var listItem = _this15._getTemplate('item', item, removeItemButton); // Append it to list fragment.appendChild(listItem); }; // Add each list item to list items.forEach(addItemToFragment); return fragment; }; _proto._triggerChange = function _triggerChange(value) { if (value === undefined || value === null) { return; } this.passedElement.triggerEvent(EVENTS.change, { value: value }); }; _proto._selectPlaceholderChoice = function _selectPlaceholderChoice() { var placeholderChoice = this._store.placeholderChoice; if (placeholderChoice) { this._addItem({ value: placeholderChoice.value, label: placeholderChoice.label, choiceId: placeholderChoice.id, groupId: placeholderChoice.groupId, placeholder: placeholderChoice.placeholder }); this._triggerChange(placeholderChoice.value); } }; _proto._handleButtonAction = function _handleButtonAction(activeItems, element) { if (!activeItems || !element || !this.config.removeItems || !this.config.removeItemButton) { return; } var itemId = element.parentNode.getAttribute('data-id'); var itemToRemove = activeItems.find(function (item) { return item.id === parseInt(itemId, 10); }); // Remove item associated with button this._removeItem(itemToRemove); this._triggerChange(itemToRemove.value); if (this._isSelectOneElement) { this._selectPlaceholderChoice(); } }; _proto._handleItemAction = function _handleItemAction(activeItems, element, hasShiftKey) { var _this16 = this; if (hasShiftKey === void 0) { hasShiftKey = false; } if (!activeItems || !element || !this.config.removeItems || this._isSelectOneElement) { return; } var passedId = element.getAttribute('data-id'); // We only want to select one item with a click // so we deselect any items that aren't the target // unless shift is being pressed activeItems.forEach(function (item) { if (item.id === parseInt(passedId, 10) && !item.highlighted) { _this16.highlightItem(item); } else if (!hasShiftKey && item.highlighted) { _this16.unhighlightItem(item); } }); // Focus input as without focus, a user cannot do anything with a // highlighted item this.input.focus(); }; _proto._handleChoiceAction = function _handleChoiceAction(activeItems, element) { if (!activeItems || !element) { return; } // If we are clicking on an option var id = element.dataset.id; var choice = this._store.getChoiceById(id); if (!choice) { return; } var passedKeyCode = activeItems[0] && activeItems[0].keyCode ? activeItems[0].keyCode : null; var hasActiveDropdown = this.dropdown.isActive; // Update choice keyCode choice.keyCode = passedKeyCode; this.passedElement.triggerEvent(EVENTS.choice, { choice: choice }); if (!choice.selected && !choice.disabled) { var canAddItem = this._canAddItem(activeItems, choice.value); if (canAddItem.response) { this._addItem({ value: choice.value, label: choice.label, choiceId: choice.id, groupId: choice.groupId, customProperties: choice.customProperties, placeholder: choice.placeholder, keyCode: choice.keyCode }); this._triggerChange(choice.value); } } this.clearInput(); // We want to close the dropdown if we are dealing with a single select box if (hasActiveDropdown && this._isSelectOneElement) { this.hideDropdown(true); this.containerOuter.focus(); } }; _proto._handleBackspace = function _handleBackspace(activeItems) { if (!this.config.removeItems || !activeItems) { return; } var lastItem = activeItems[activeItems.length - 1]; var hasHighlightedItems = activeItems.some(function (item) { return item.highlighted; }); // If editing the last item is allowed and there are not other selected items, // we can edit the item value. Otherwise if we can remove items, remove all selected items if (this.config.editItems && !hasHighlightedItems && lastItem) { this.input.value = lastItem.value; this.input.setWidth(); this._removeItem(lastItem); this._triggerChange(lastItem.value); } else { if (!hasHighlightedItems) { // Highlight last item if none already highlighted this.highlightItem(lastItem, false); } this.removeHighlightedItems(true); } }; _proto._startLoading = function _startLoading() { this._store.dispatch(setIsLoading(true)); }; _proto._stopLoading = function _stopLoading() { this._store.dispatch(setIsLoading(false)); }; _proto._handleLoadingState = function _handleLoadingState(setLoading) { if (setLoading === void 0) { setLoading = true; } var placeholderItem = this.itemList.getChild("." + this.config.classNames.placeholder); if (setLoading) { this.disable(); this.containerOuter.addLoadingState(); if (this._isSelectOneElement) { if (!placeholderItem) { placeholderItem = this._getTemplate('placeholder', this.config.loadingText); this.itemList.append(placeholderItem); } else { placeholderItem.innerHTML = this.config.loadingText; } } else { this.input.placeholder = this.config.loadingText; } } else { this.enable(); this.containerOuter.removeLoadingState(); if (this._isSelectOneElement) { placeholderItem.innerHTML = this._placeholderValue || ''; } else { this.input.placeholder = this._placeholderValue || ''; } } }; _proto._handleSearch = function _handleSearch(value) { if (!value || !this.input.isFocussed) { return; } var choices = this._store.choices; var _this$config3 = this.config, searchFloor = _this$config3.searchFloor, searchChoices = _this$config3.searchChoices; var hasUnactiveChoices = choices.some(function (option) { return !option.active; }); // Check that we have a value to search and the input was an alphanumeric character if (value && value.length >= searchFloor) { var resultCount = searchChoices ? this._searchChoices(value) : 0; // Trigger search event this.passedElement.triggerEvent(EVENTS.search, { value: value, resultCount: resultCount }); } else if (hasUnactiveChoices) { // Otherwise reset choices to active this._isSearching = false; this._store.dispatch(choices_activateChoices(true)); } }; _proto._canAddItem = function _canAddItem(activeItems, value) { var canAddItem = true; var notice = typeof this.config.addItemText === 'function' ? this.config.addItemText(value) : this.config.addItemText; if (!this._isSelectOneElement) { var isDuplicateValue = existsInArray(activeItems, value); if (this.config.maxItemCount > 0 && this.config.maxItemCount <= activeItems.length) { // If there is a max entry limit and we have reached that limit // don't update canAddItem = false; notice = typeof this.config.maxItemText === 'function' ? this.config.maxItemText(this.config.maxItemCount) : this.config.maxItemText; } if (!this.config.duplicateItemsAllowed && isDuplicateValue && canAddItem) { canAddItem = false; notice = typeof this.config.uniqueItemText === 'function' ? this.config.uniqueItemText(value) : this.config.uniqueItemText; } if (this._isTextElement && this.config.addItems && canAddItem && typeof this.config.addItemFilter === 'function' && !this.config.addItemFilter(value)) { canAddItem = false; notice = typeof this.config.customAddItemText === 'function' ? this.config.customAddItemText(value) : this.config.customAddItemText; } } return { response: canAddItem, notice: notice }; }; _proto._searchChoices = function _searchChoices(value) { var newValue = typeof value === 'string' ? value.trim() : value; var currentValue = typeof this._currentValue === 'string' ? this._currentValue.trim() : this._currentValue; if (newValue.length < 1 && newValue === currentValue + " ") { return 0; } // If new value matches the desired length and is not the same as the current value with a space var haystack = this._store.searchableChoices; var needle = newValue; var keys = [].concat(this.config.searchFields); var options = Object.assign(this.config.fuseOptions, { keys: keys }); var fuse = new fuse_default.a(haystack, options); var results = fuse.search(needle); this._currentValue = newValue; this._highlightPosition = 0; this._isSearching = true; this._store.dispatch(choices_filterChoices(results)); return results.length; }; _proto._addEventListeners = function _addEventListeners() { var _document = document, documentElement = _document.documentElement; // capture events - can cancel event processing or propagation documentElement.addEventListener('touchend', this._onTouchEnd, true); this.containerOuter.element.addEventListener('keydown', this._onKeyDown, true); this.containerOuter.element.addEventListener('mousedown', this._onMouseDown, true); // passive events - doesn't call `preventDefault` or `stopPropagation` documentElement.addEventListener('click', this._onClick, { passive: true }); documentElement.addEventListener('touchmove', this._onTouchMove, { passive: true }); this.dropdown.element.addEventListener('mouseover', this._onMouseOver, { passive: true }); if (this._isSelectOneElement) { this.containerOuter.element.addEventListener('focus', this._onFocus, { passive: true }); this.containerOuter.element.addEventListener('blur', this._onBlur, { passive: true }); } this.input.element.addEventListener('keyup', this._onKeyUp, { passive: true }); this.input.element.addEventListener('focus', this._onFocus, { passive: true }); this.input.element.addEventListener('blur', this._onBlur, { passive: true }); if (this.input.element.form) { this.input.element.form.addEventListener('reset', this._onFormReset, { passive: true }); } this.input.addEventListeners(); }; _proto._removeEventListeners = function _removeEventListeners() { var _document2 = document, documentElement = _document2.documentElement; documentElement.removeEventListener('touchend', this._onTouchEnd, true); this.containerOuter.element.removeEventListener('keydown', this._onKeyDown, true); this.containerOuter.element.removeEventListener('mousedown', this._onMouseDown, true); documentElement.removeEventListener('click', this._onClick); documentElement.removeEventListener('touchmove', this._onTouchMove); this.dropdown.element.removeEventListener('mouseover', this._onMouseOver); if (this._isSelectOneElement) { this.containerOuter.element.removeEventListener('focus', this._onFocus); this.containerOuter.element.removeEventListener('blur', this._onBlur); } this.input.element.removeEventListener('keyup', this._onKeyUp); this.input.element.removeEventListener('focus', this._onFocus); this.input.element.removeEventListener('blur', this._onBlur); if (this.input.element.form) { this.input.element.form.removeEventListener('reset', this._onFormReset); } this.input.removeEventListeners(); } /** * @param {KeyboardEvent} event */ ; _proto._onKeyDown = function _onKeyDown(event) { var _keyDownActions; var target = event.target, keyCode = event.keyCode, ctrlKey = event.ctrlKey, metaKey = event.metaKey; var activeItems = this._store.activeItems; var hasFocusedInput = this.input.isFocussed; var hasActiveDropdown = this.dropdown.isActive; var hasItems = this.itemList.hasChildren(); var keyString = String.fromCharCode(keyCode); var BACK_KEY = KEY_CODES.BACK_KEY, DELETE_KEY = KEY_CODES.DELETE_KEY, ENTER_KEY = KEY_CODES.ENTER_KEY, A_KEY = KEY_CODES.A_KEY, ESC_KEY = KEY_CODES.ESC_KEY, UP_KEY = KEY_CODES.UP_KEY, DOWN_KEY = KEY_CODES.DOWN_KEY, PAGE_UP_KEY = KEY_CODES.PAGE_UP_KEY, PAGE_DOWN_KEY = KEY_CODES.PAGE_DOWN_KEY; var hasCtrlDownKeyPressed = ctrlKey || metaKey; // If a user is typing and the dropdown is not active if (!this._isTextElement && /[a-zA-Z0-9-_ ]/.test(keyString)) { this.showDropdown(); } // Map keys to key actions var keyDownActions = (_keyDownActions = {}, _keyDownActions[A_KEY] = this._onAKey, _keyDownActions[ENTER_KEY] = this._onEnterKey, _keyDownActions[ESC_KEY] = this._onEscapeKey, _keyDownActions[UP_KEY] = this._onDirectionKey, _keyDownActions[PAGE_UP_KEY] = this._onDirectionKey, _keyDownActions[DOWN_KEY] = this._onDirectionKey, _keyDownActions[PAGE_DOWN_KEY] = this._onDirectionKey, _keyDownActions[DELETE_KEY] = this._onDeleteKey, _keyDownActions[BACK_KEY] = this._onDeleteKey, _keyDownActions); // If keycode has a function, run it if (keyDownActions[keyCode]) { keyDownActions[keyCode]({ event: event, target: target, keyCode: keyCode, metaKey: metaKey, activeItems: activeItems, hasFocusedInput: hasFocusedInput, hasActiveDropdown: hasActiveDropdown, hasItems: hasItems, hasCtrlDownKeyPressed: hasCtrlDownKeyPressed }); } }; _proto._onKeyUp = function _onKeyUp(_ref2) { var target = _ref2.target, keyCode = _ref2.keyCode; var value = this.input.value; var activeItems = this._store.activeItems; var canAddItem = this._canAddItem(activeItems, value); var backKey = KEY_CODES.BACK_KEY, deleteKey = KEY_CODES.DELETE_KEY; // We are typing into a text input and have a value, we want to show a dropdown // notice. Otherwise hide the dropdown if (this._isTextElement) { var canShowDropdownNotice = canAddItem.notice && value; if (canShowDropdownNotice) { var dropdownItem = this._getTemplate('notice', canAddItem.notice); this.dropdown.element.innerHTML = dropdownItem.outerHTML; this.showDropdown(true); } else { this.hideDropdown(true); } } else { var userHasRemovedValue = (keyCode === backKey || keyCode === deleteKey) && !target.value; var canReactivateChoices = !this._isTextElement && this._isSearching; var canSearch = this._canSearch && canAddItem.response; if (userHasRemovedValue && canReactivateChoices) { this._isSearching = false; this._store.dispatch(choices_activateChoices(true)); } else if (canSearch) { this._handleSearch(this.input.value); } } this._canSearch = this.config.searchEnabled; }; _proto._onAKey = function _onAKey(_ref3) { var hasItems = _ref3.hasItems, hasCtrlDownKeyPressed = _ref3.hasCtrlDownKeyPressed; // If CTRL + A or CMD + A have been pressed and there are items to select if (hasCtrlDownKeyPressed && hasItems) { this._canSearch = false; var shouldHightlightAll = this.config.removeItems && !this.input.value && this.input.element === document.activeElement; if (shouldHightlightAll) { this.highlightAll(); } } }; _proto._onEnterKey = function _onEnterKey(_ref4) { var event = _ref4.event, target = _ref4.target, activeItems = _ref4.activeItems, hasActiveDropdown = _ref4.hasActiveDropdown; var enterKey = KEY_CODES.ENTER_KEY; var targetWasButton = target.hasAttribute('data-button'); if (this._isTextElement && target.value) { var value = this.input.value; var canAddItem = this._canAddItem(activeItems, value); if (canAddItem.response) { this.hideDropdown(true); this._addItem({ value: value }); this._triggerChange(value); this.clearInput(); } } if (targetWasButton) { this._handleButtonAction(activeItems, target); event.preventDefault(); } if (hasActiveDropdown) { var highlightedChoice = this.dropdown.getChild("." + this.config.classNames.highlightedState); if (highlightedChoice) { // add enter keyCode value if (activeItems[0]) { activeItems[0].keyCode = enterKey; // eslint-disable-line no-param-reassign } this._handleChoiceAction(activeItems, highlightedChoice); } event.preventDefault(); } else if (this._isSelectOneElement) { this.showDropdown(); event.preventDefault(); } }; _proto._onEscapeKey = function _onEscapeKey(_ref5) { var hasActiveDropdown = _ref5.hasActiveDropdown; if (hasActiveDropdown) { this.hideDropdown(true); this.containerOuter.focus(); } }; _proto._onDirectionKey = function _onDirectionKey(_ref6) { var event = _ref6.event, hasActiveDropdown = _ref6.hasActiveDropdown, keyCode = _ref6.keyCode, metaKey = _ref6.metaKey; var downKey = KEY_CODES.DOWN_KEY, pageUpKey = KEY_CODES.PAGE_UP_KEY, pageDownKey = KEY_CODES.PAGE_DOWN_KEY; // If up or down key is pressed, traverse through options if (hasActiveDropdown || this._isSelectOneElement) { this.showDropdown(); this._canSearch = false; var directionInt = keyCode === downKey || keyCode === pageDownKey ? 1 : -1; var skipKey = metaKey || keyCode === pageDownKey || keyCode === pageUpKey; var selectableChoiceIdentifier = '[data-choice-selectable]'; var nextEl; if (skipKey) { if (directionInt > 0) { nextEl = this.dropdown.element.querySelector(selectableChoiceIdentifier + ":last-of-type"); } else { nextEl = this.dropdown.element.querySelector(selectableChoiceIdentifier); } } else { var currentEl = this.dropdown.element.querySelector("." + this.config.classNames.highlightedState); if (currentEl) { nextEl = getAdjacentEl(currentEl, selectableChoiceIdentifier, directionInt); } else { nextEl = this.dropdown.element.querySelector(selectableChoiceIdentifier); } } if (nextEl) { // We prevent default to stop the cursor moving // when pressing the arrow if (!isScrolledIntoView(nextEl, this.choiceList.element, directionInt)) { this.choiceList.scrollToChildElement(nextEl, directionInt); } this._highlightChoice(nextEl); } // Prevent default to maintain cursor position whilst // traversing dropdown options event.preventDefault(); } }; _proto._onDeleteKey = function _onDeleteKey(_ref7) { var event = _ref7.event, target = _ref7.target, hasFocusedInput = _ref7.hasFocusedInput, activeItems = _ref7.activeItems; // If backspace or delete key is pressed and the input has no value if (hasFocusedInput && !target.value && !this._isSelectOneElement) { this._handleBackspace(activeItems); event.preventDefault(); } }; _proto._onTouchMove = function _onTouchMove() { if (this._wasTap) { this._wasTap = false; } }; _proto._onTouchEnd = function _onTouchEnd(event) { var _ref8 = event || event.touches[0], target = _ref8.target; var touchWasWithinContainer = this._wasTap && this.containerOuter.element.contains(target); if (touchWasWithinContainer) { var containerWasExactTarget = target === this.containerOuter.element || target === this.containerInner.element; if (containerWasExactTarget) { if (this._isTextElement) { this.input.focus(); } else if (this._isSelectMultipleElement) { this.showDropdown(); } } // Prevents focus event firing event.stopPropagation(); } this._wasTap = true; } /** * Handles mousedown event in capture mode for containetOuter.element * @param {MouseEvent} event */ ; _proto._onMouseDown = function _onMouseDown(event) { var target = event.target; if (!(target instanceof HTMLElement)) { return; } // If we have our mouse down on the scrollbar and are on IE11... if (IS_IE11 && this.choiceList.element.contains(target)) { // check if click was on a scrollbar area var firstChoice = /** @type {HTMLElement} */ this.choiceList.element.firstElementChild; var isOnScrollbar = this._direction === 'ltr' ? event.offsetX >= firstChoice.offsetWidth : event.offsetX < firstChoice.offsetLeft; this._isScrollingOnIe = isOnScrollbar; } if (target === this.input.element) { return; } var item = target.closest('[data-button],[data-item],[data-choice]'); if (item instanceof HTMLElement) { var hasShiftKey = event.shiftKey; var activeItems = this._store.activeItems; var dataset = item.dataset; if ('button' in dataset) { this._handleButtonAction(activeItems, item); } else if ('item' in dataset) { this._handleItemAction(activeItems, item, hasShiftKey); } else if ('choice' in dataset) { this._handleChoiceAction(activeItems, item); } } event.preventDefault(); } /** * Handles mouseover event over this.dropdown * @param {MouseEvent} event */ ; _proto._onMouseOver = function _onMouseOver(_ref9) { var target = _ref9.target; if (target instanceof HTMLElement && 'choice' in target.dataset) { this._highlightChoice(target); } }; _proto._onClick = function _onClick(_ref10) { var target = _ref10.target; var clickWasWithinContainer = this.containerOuter.element.contains(target); if (clickWasWithinContainer) { if (!this.dropdown.isActive && !this.containerOuter.isDisabled) { if (this._isTextElement) { if (document.activeElement !== this.input.element) { this.input.focus(); } } else { this.showDropdown(); this.containerOuter.focus(); } } else if (this._isSelectOneElement && target !== this.input.element && !this.dropdown.element.contains(target)) { this.hideDropdown(); } } else { var hasHighlightedItems = this._store.highlightedActiveItems.length > 0; if (hasHighlightedItems) { this.unhighlightAll(); } this.containerOuter.removeFocusState(); this.hideDropdown(true); } }; _proto._onFocus = function _onFocus(_ref11) { var _this17 = this, _focusActions; var target = _ref11.target; var focusWasWithinContainer = this.containerOuter.element.contains(target); if (!focusWasWithinContainer) { return; } var focusActions = (_focusActions = {}, _focusActions[TEXT_TYPE] = function () { if (target === _this17.input.element) { _this17.containerOuter.addFocusState(); } }, _focusActions[SELECT_ONE_TYPE] = function () { _this17.containerOuter.addFocusState(); if (target === _this17.input.element) { _this17.showDropdown(true); } }, _focusActions[SELECT_MULTIPLE_TYPE] = function () { if (target === _this17.input.element) { _this17.showDropdown(true); // If element is a select box, the focused element is the container and the dropdown // isn't already open, focus and show dropdown _this17.containerOuter.addFocusState(); } }, _focusActions); focusActions[this.passedElement.element.type](); }; _proto._onBlur = function _onBlur(_ref12) { var _this18 = this; var target = _ref12.target; var blurWasWithinContainer = this.containerOuter.element.contains(target); if (blurWasWithinContainer && !this._isScrollingOnIe) { var _blurActions; var activeItems = this._store.activeItems; var hasHighlightedItems = activeItems.some(function (item) { return item.highlighted; }); var blurActions = (_blurActions = {}, _blurActions[TEXT_TYPE] = function () { if (target === _this18.input.element) { _this18.containerOuter.removeFocusState(); if (hasHighlightedItems) { _this18.unhighlightAll(); } _this18.hideDropdown(true); } }, _blurActions[SELECT_ONE_TYPE] = function () { _this18.containerOuter.removeFocusState(); if (target === _this18.input.element || target === _this18.containerOuter.element && !_this18._canSearch) { _this18.hideDropdown(true); } }, _blurActions[SELECT_MULTIPLE_TYPE] = function () { if (target === _this18.input.element) { _this18.containerOuter.removeFocusState(); _this18.hideDropdown(true); if (hasHighlightedItems) { _this18.unhighlightAll(); } } }, _blurActions); blurActions[this.passedElement.element.type](); } else { // On IE11, clicking the scollbar blurs our input and thus // closes the dropdown. To stop this, we refocus our input // if we know we are on IE *and* are scrolling. this._isScrollingOnIe = false; this.input.element.focus(); } }; _proto._onFormReset = function _onFormReset() { this._store.dispatch(resetTo(this._initialState)); }; _proto._highlightChoice = function _highlightChoice(el) { var _this19 = this; if (el === void 0) { el = null; } var choices = Array.from(this.dropdown.element.querySelectorAll('[data-choice-selectable]')); if (!choices.length) { return; } var passedEl = el; var highlightedChoices = Array.from(this.dropdown.element.querySelectorAll("." + this.config.classNames.highlightedState)); // Remove any highlighted choices highlightedChoices.forEach(function (choice) { choice.classList.remove(_this19.config.classNames.highlightedState); choice.setAttribute('aria-selected', 'false'); }); if (passedEl) { this._highlightPosition = choices.indexOf(passedEl); } else { // Highlight choice based on last known highlight location if (choices.length > this._highlightPosition) { // If we have an option to highlight passedEl = choices[this._highlightPosition]; } else { // Otherwise highlight the option before passedEl = choices[choices.length - 1]; } if (!passedEl) { passedEl = choices[0]; } } passedEl.classList.add(this.config.classNames.highlightedState); passedEl.setAttribute('aria-selected', 'true'); this.passedElement.triggerEvent(EVENTS.highlightChoice, { el: passedEl }); if (this.dropdown.isActive) { // IE11 ignores aria-label and blocks virtual keyboard // if aria-activedescendant is set without a dropdown this.input.setActiveDescendant(passedEl.id); this.containerOuter.setActiveDescendant(passedEl.id); } }; _proto._addItem = function _addItem(_ref13) { var value = _ref13.value, _ref13$label = _ref13.label, label = _ref13$label === void 0 ? null : _ref13$label, _ref13$choiceId = _ref13.choiceId, choiceId = _ref13$choiceId === void 0 ? -1 : _ref13$choiceId, _ref13$groupId = _ref13.groupId, groupId = _ref13$groupId === void 0 ? -1 : _ref13$groupId, _ref13$customProperti = _ref13.customProperties, customProperties = _ref13$customProperti === void 0 ? null : _ref13$customProperti, _ref13$placeholder = _ref13.placeholder, placeholder = _ref13$placeholder === void 0 ? false : _ref13$placeholder, _ref13$keyCode = _ref13.keyCode, keyCode = _ref13$keyCode === void 0 ? null : _ref13$keyCode; var passedValue = typeof value === 'string' ? value.trim() : value; var passedKeyCode = keyCode; var passedCustomProperties = customProperties; var items = this._store.items; var passedLabel = label || passedValue; var passedOptionId = choiceId || -1; var group = groupId >= 0 ? this._store.getGroupById(groupId) : null; var id = items ? items.length + 1 : 1; // If a prepended value has been passed, prepend it if (this.config.prependValue) { passedValue = this.config.prependValue + passedValue.toString(); } // If an appended value has been passed, append it if (this.config.appendValue) { passedValue += this.config.appendValue.toString(); } this._store.dispatch(items_addItem({ value: passedValue, label: passedLabel, id: id, choiceId: passedOptionId, groupId: groupId, customProperties: customProperties, placeholder: placeholder, keyCode: passedKeyCode })); if (this._isSelectOneElement) { this.removeActiveItems(id); } // Trigger change event this.passedElement.triggerEvent(EVENTS.addItem, { id: id, value: passedValue, label: passedLabel, customProperties: passedCustomProperties, groupValue: group && group.value ? group.value : undefined, keyCode: passedKeyCode }); return this; }; _proto._removeItem = function _removeItem(item) { if (!item || !isType('Object', item)) { return this; } var id = item.id, value = item.value, label = item.label, choiceId = item.choiceId, groupId = item.groupId; var group = groupId >= 0 ? this._store.getGroupById(groupId) : null; this._store.dispatch(items_removeItem(id, choiceId)); if (group && group.value) { this.passedElement.triggerEvent(EVENTS.removeItem, { id: id, value: value, label: label, groupValue: group.value }); } else { this.passedElement.triggerEvent(EVENTS.removeItem, { id: id, value: value, label: label }); } return this; }; _proto._addChoice = function _addChoice(_ref14) { var value = _ref14.value, _ref14$label = _ref14.label, label = _ref14$label === void 0 ? null : _ref14$label, _ref14$isSelected = _ref14.isSelected, isSelected = _ref14$isSelected === void 0 ? false : _ref14$isSelected, _ref14$isDisabled = _ref14.isDisabled, isDisabled = _ref14$isDisabled === void 0 ? false : _ref14$isDisabled, _ref14$groupId = _ref14.groupId, groupId = _ref14$groupId === void 0 ? -1 : _ref14$groupId, _ref14$customProperti = _ref14.customProperties, customProperties = _ref14$customProperti === void 0 ? null : _ref14$customProperti, _ref14$placeholder = _ref14.placeholder, placeholder = _ref14$placeholder === void 0 ? false : _ref14$placeholder, _ref14$keyCode = _ref14.keyCode, keyCode = _ref14$keyCode === void 0 ? null : _ref14$keyCode; if (typeof value === 'undefined' || value === null) { return; } // Generate unique id var choices = this._store.choices; var choiceLabel = label || value; var choiceId = choices ? choices.length + 1 : 1; var choiceElementId = this._baseId + "-" + this._idNames.itemChoice + "-" + choiceId; this._store.dispatch(choices_addChoice({ id: choiceId, groupId: groupId, elementId: choiceElementId, value: value, label: choiceLabel, disabled: isDisabled, customProperties: customProperties, placeholder: placeholder, keyCode: keyCode })); if (isSelected) { this._addItem({ value: value, label: choiceLabel, choiceId: choiceId, customProperties: customProperties, placeholder: placeholder, keyCode: keyCode }); } }; _proto._addGroup = function _addGroup(_ref15) { var _this20 = this; var group = _ref15.group, id = _ref15.id, _ref15$valueKey = _ref15.valueKey, valueKey = _ref15$valueKey === void 0 ? 'value' : _ref15$valueKey, _ref15$labelKey = _ref15.labelKey, labelKey = _ref15$labelKey === void 0 ? 'label' : _ref15$labelKey; var groupChoices = isType('Object', group) ? group.choices : Array.from(group.getElementsByTagName('OPTION')); var groupId = id || Math.floor(new Date().valueOf() * Math.random()); var isDisabled = group.disabled ? group.disabled : false; if (groupChoices) { this._store.dispatch(groups_addGroup({ value: group.label, id: groupId, active: true, disabled: isDisabled })); var addGroupChoices = function addGroupChoices(choice) { var isOptDisabled = choice.disabled || choice.parentNode && choice.parentNode.disabled; _this20._addChoice({ value: choice[valueKey], label: isType('Object', choice) ? choice[labelKey] : choice.innerHTML, isSelected: choice.selected, isDisabled: isOptDisabled, groupId: groupId, customProperties: choice.customProperties, placeholder: choice.placeholder }); }; groupChoices.forEach(addGroupChoices); } else { this._store.dispatch(groups_addGroup({ value: group.label, id: group.id, active: false, disabled: group.disabled })); } }; _proto._getTemplate = function _getTemplate(template) { var _this$_templates$temp; if (!template) { return null; } var classNames = this.config.classNames; for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return (_this$_templates$temp = this._templates[template]).call.apply(_this$_templates$temp, [this, classNames].concat(args)); }; _proto._createTemplates = function _createTemplates() { var callbackOnCreateTemplates = this.config.callbackOnCreateTemplates; var userTemplates = {}; if (callbackOnCreateTemplates && typeof callbackOnCreateTemplates === 'function') { userTemplates = callbackOnCreateTemplates.call(this, strToEl); } this._templates = cjs_default()(TEMPLATES, userTemplates); }; _proto._createElements = function _createElements() { this.containerOuter = new container_Container({ element: this._getTemplate('containerOuter', this._direction, this._isSelectElement, this._isSelectOneElement, this.config.searchEnabled, this.passedElement.element.type), classNames: this.config.classNames, type: this.passedElement.element.type, position: this.config.position }); this.containerInner = new container_Container({ element: this._getTemplate('containerInner'), classNames: this.config.classNames, type: this.passedElement.element.type, position: this.config.position }); this.input = new input_Input({ element: this._getTemplate('input', this._placeholderValue), classNames: this.config.classNames, type: this.passedElement.element.type, preventPaste: !this.config.paste }); this.choiceList = new list_List({ element: this._getTemplate('choiceList', this._isSelectOneElement) }); this.itemList = new list_List({ element: this._getTemplate('itemList', this._isSelectOneElement) }); this.dropdown = new Dropdown({ element: this._getTemplate('dropdown'), classNames: this.config.classNames, type: this.passedElement.element.type }); }; _proto._createStructure = function _createStructure() { // Hide original element this.passedElement.conceal(); // Wrap input in container preserving DOM ordering this.containerInner.wrap(this.passedElement.element); // Wrapper inner container with outer container this.containerOuter.wrap(this.containerInner.element); if (this._isSelectOneElement) { this.input.placeholder = this.config.searchPlaceholderValue || ''; } else if (this._placeholderValue) { this.input.placeholder = this._placeholderValue; this.input.setWidth(); } this.containerOuter.element.appendChild(this.containerInner.element); this.containerOuter.element.appendChild(this.dropdown.element); this.containerInner.element.appendChild(this.itemList.element); if (!this._isTextElement) { this.dropdown.element.appendChild(this.choiceList.element); } if (!this._isSelectOneElement) { this.containerInner.element.appendChild(this.input.element); } else if (this.config.searchEnabled) { this.dropdown.element.insertBefore(this.input.element, this.dropdown.element.firstChild); } if (this._isSelectElement) { this._highlightPosition = 0; this._isSearching = false; this._startLoading(); if (this._presetGroups.length) { this._addPredefinedGroups(this._presetGroups); } else { this._addPredefinedChoices(this._presetChoices); } this._stopLoading(); } if (this._isTextElement) { this._addPredefinedItems(this._presetItems); } }; _proto._addPredefinedGroups = function _addPredefinedGroups(groups) { var _this21 = this; // If we have a placeholder option var placeholderChoice = this.passedElement.placeholderOption; if (placeholderChoice && placeholderChoice.parentNode.tagName === 'SELECT') { this._addChoice({ value: placeholderChoice.value, label: placeholderChoice.innerHTML, isSelected: placeholderChoice.selected, isDisabled: placeholderChoice.disabled, placeholder: true }); } groups.forEach(function (group) { return _this21._addGroup({ group: group, id: group.id || null }); }); }; _proto._addPredefinedChoices = function _addPredefinedChoices(choices) { var _this22 = this; // If sorting is enabled or the user is searching, filter choices if (this.config.shouldSort) { choices.sort(this.config.sorter); } var hasSelectedChoice = choices.some(function (choice) { return choice.selected; }); var firstEnabledChoiceIndex = choices.findIndex(function (choice) { return choice.disabled === undefined || !choice.disabled; }); choices.forEach(function (choice, index) { var value = choice.value, label = choice.label, customProperties = choice.customProperties, placeholder = choice.placeholder; if (_this22._isSelectElement) { // If the choice is actually a group if (choice.choices) { _this22._addGroup({ group: choice, id: choice.id || null }); } else { /** * If there is a selected choice already or the choice is not the first in * the array, add each choice normally. * * Otherwise we pre-select the first enabled choice in the array ("select-one" only) */ var shouldPreselect = _this22._isSelectOneElement && !hasSelectedChoice && index === firstEnabledChoiceIndex; var isSelected = shouldPreselect ? true : choice.selected; var isDisabled = choice.disabled; _this22._addChoice({ value: value, label: label, isSelected: isSelected, isDisabled: isDisabled, customProperties: customProperties, placeholder: placeholder }); } } else { _this22._addChoice({ value: value, label: label, isSelected: choice.selected, isDisabled: choice.disabled, customProperties: customProperties, placeholder: placeholder }); } }); } /** * @param {Item[]} items */ ; _proto._addPredefinedItems = function _addPredefinedItems(items) { var _this23 = this; items.forEach(function (item) { if (typeof item === 'object' && item.value) { _this23._addItem({ value: item.value, label: item.label, choiceId: item.id, customProperties: item.customProperties, placeholder: item.placeholder }); } if (typeof item === 'string') { _this23._addItem({ value: item }); } }); }; _proto._setChoiceOrItem = function _setChoiceOrItem(item) { var _this24 = this; var itemType = getType(item).toLowerCase(); var handleType = { object: function object() { if (!item.value) { return; } // If we are dealing with a select input, we need to create an option first // that is then selected. For text inputs we can just add items normally. if (!_this24._isTextElement) { _this24._addChoice({ value: item.value, label: item.label, isSelected: true, isDisabled: false, customProperties: item.customProperties, placeholder: item.placeholder }); } else { _this24._addItem({ value: item.value, label: item.label, choiceId: item.id, customProperties: item.customProperties, placeholder: item.placeholder }); } }, string: function string() { if (!_this24._isTextElement) { _this24._addChoice({ value: item, label: item, isSelected: true, isDisabled: false }); } else { _this24._addItem({ value: item }); } } }; handleType[itemType](); }; _proto._findAndSelectChoiceByValue = function _findAndSelectChoiceByValue(val) { var _this25 = this; var choices = this._store.choices; // Check 'value' property exists and the choice isn't already selected var foundChoice = choices.find(function (choice) { return _this25.config.valueComparer(choice.value, val); }); if (foundChoice && !foundChoice.selected) { this._addItem({ value: foundChoice.value, label: foundChoice.label, choiceId: foundChoice.id, groupId: foundChoice.groupId, customProperties: foundChoice.customProperties, placeholder: foundChoice.placeholder, keyCode: foundChoice.keyCode }); } }; _proto._generatePlaceholderValue = function _generatePlaceholderValue() { if (this._isSelectElement) { var placeholderOption = this.passedElement.placeholderOption; return placeholderOption ? placeholderOption.text : false; } var _this$config4 = this.config, placeholder = _this$config4.placeholder, placeholderValue = _this$config4.placeholderValue; var dataset = this.passedElement.element.dataset; if (placeholder) { if (placeholderValue) { return placeholderValue; } if (dataset.placeholder) { return dataset.placeholder; } } return false; }; return Choices; }(); /* harmony default export */ var scripts_choices = __webpack_exports__["default"] = (choices_Choices); /***/ }) /******/ ])["default"]; }); /***/ }), /***/ "./node_modules/lodash/lodash.js": /*!***************************************!*\ !*** ./node_modules/lodash/lodash.js ***! \***************************************/ /***/ (function(module, exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); var __WEBPACK_AMD_DEFINE_RESULT__;/** * @license * Lodash <https://lodash.com/> * Copyright OpenJS Foundation and other contributors <https://openjsf.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.21'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function', INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', 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 match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading whitespace. */ var reTrimStart = /^\s+/; /** Used to match a single whitespace character. */ var reWhitespace = /\s/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** * Used to validate the `validate` option in `_.template` variable. * * Forbids characters which could potentially change the meaning of the function argument definition: * - "()," (modification of function parameters) * - "=" (default value) * - "[]{}" (destructuring of function parameters) * - "/" (beginning of a comment) * - whitespace */ var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** 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[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @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 == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @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 == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @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 == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * 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 accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` 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; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.trim`. * * @private * @param {string} string The string to trim. * @returns {string} Returns the trimmed string. */ function baseTrim(string) { return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedEndIndex(string) { var index = string.length; while (index-- && reWhitespace.test(string.charAt(index))) {} return index; } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} 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; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `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(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @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 baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @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 object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(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 stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} 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 `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { stack || (stack = new Stack); if (isObject(srcValue)) { baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { iteratees = arrayMap(iteratees, function(iteratee) { if (isArray(iteratee)) { return function(value) { return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); } } return iteratee; }); } else { iteratees = [identity]; } var index = -1; iteratees = arrayMap(iteratees, baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * 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 accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @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. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return object; } if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * 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; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; 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; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection 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 baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { var low = 0, high = array == null ? 0 : array.length; if (high === 0) { return 0; } value = iteratee(value); var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * 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) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @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 index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision && nativeIsFinite(number)) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Check that cyclic values are equal. var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * 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} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Check that cyclic values are equal. var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !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)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property 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 = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * 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 = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * 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) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given 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) ) { return eq(object[index], value); } return false; } /** * 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) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * 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); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key === 'constructor' && typeof object[key] === 'function') { return; } if (key == '__proto__') { return; } return object[key]; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @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 == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @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 slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] * * // Combining several predicates using `_.overEvery` or `_.overSome`. * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); * // => objects for ['fred', 'barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 30 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * 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://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @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 = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @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(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @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 (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = baseTrim(value); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @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'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @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) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @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 = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES template literal delimiter as an "interpolate" delimiter. * // Disable support by replacing the "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. // The sourceURL gets injected into the source that's eval-ed, so be careful // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in // and escape the comment, thus injecting code that gets evaled. var sourceURL = '//# sourceURL=' + (hasOwnProperty.call(options, 'sourceURL') ? (options.sourceURL + '').replace(/\s/g, ' ') : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = hasOwnProperty.call(options, 'variable') && options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Throw an error if a forbidden character was found in `variable`, to prevent // potential command injection attacks. else if (reForbiddenIdentifierChars.test(variable)) { throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT); } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return baseTrim(string); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.slice(0, trimmedEndIndex(string) + 1); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = baseRest(function(func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. */ var bindAll = flatRest(function(object, methodNames) { arrayEach(methodNames, function(key) { key = toKey(key); baseAssignValue(object, key, bind(object[key], object)); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.stubTrue, _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return baseRest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * **Note:** The created function is equivalent to `_.conformsTo` with * `source` partially applied. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 2, 'b': 1 }, * { 'a': 1, 'b': 2 } * ]; * * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); * // => [{ 'a': 1, 'b': 2 }] */ function conforms(source) { return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } /** * Checks `value` to determine whether a default value should be returned in * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, * or `undefined`. * * @static * @memberOf _ * @since 4.14.0 * @category Util * @param {*} value The value to check. * @param {*} defaultValue The default value. * @returns {*} Returns the resolved value. * @example * * _.defaultTo(1, 10); * // => 1 * * _.defaultTo(undefined, 10); * // => 10 */ function defaultTo(value, defaultValue) { return (value == null || value !== value) ? defaultValue : value; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow([_.add, square]); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight([square, _.add]); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. * * **Note:** The created function is equivalent to `_.isMatch` with `source` * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); * // => [{ 'a': 4, 'b': 5, 'c': 6 }] * * // Checking for several possible values * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] */ function matches(source) { return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** Partial comparisons will match empty array and empty object * `srcValue` values against any array or object value, respectively. See * `_.isEqual` for a list of supported value comparisons. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.find(objects, _.matchesProperty('a', 4)); * // => { 'a': 4, 'b': 5, 'c': 6 } * * // Checking for several possible values * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = baseRest(function(path, args) { return function(object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = baseRest(function(object, args) { return function(path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options={}] The options object. * @param {boolean} [options.chain=true] Specify whether mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === this) { root._ = oldDash; } return this; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } /** * Creates a function that gets the argument at index `n`. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return baseRest(function(args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over([Math.max, Math.min]); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false * * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }]) * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]]) */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /** * This method returns a new empty object. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Object} Returns the new empty object. * @example * * var objects = _.times(2, _.stubObject); * * console.log(objects); * // => [{}, {}] * * console.log(objects[0] === objects[1]); * // => false */ function stubObject() { return {}; } /** * This method returns an empty string. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {string} Returns the empty string. * @example * * _.times(2, _.stubString); * // => ['', ''] */ function stubString() { return ''; } /** * This method returns `true`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `true`. * @example * * _.times(2, _.stubTrue); * // => [true, true] */ function stubTrue() { return true; } /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(0)); * // => [0, 0, 0, 0] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function(augend, addend) { return augend + addend; }, 0); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor; }, 1); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return (array && array.length) ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return (array && array.length) ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand; }, 1); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend; }, 0); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, getIteratee(iteratee, 2)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }()), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = (this.__filtered__ && !index) ? new LazyWrapper(this) : this.clone(); if (result.__filtered__) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } return this.map(function(value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function(predicate) { return this.filter(negate(getIteratee(predicate))); }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this, args); } result = this.thru(interceptor); return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = lodashFunc.name + ''; if (!hasOwnProperty.call(realNames, key)) { realNames[key] = []; } realNames[key].push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add lazy aliases. lodash.prototype.first = lodash.prototype.head; if (symIterator) { lodash.prototype[symIterator] = wrapperToIterator; } return lodash; }); /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers, like r.js, check for condition patterns like: if (true) { // Expose Lodash on the global object to prevent errors when Lodash is // loaded by a script tag in the presence of an AMD loader. // See http://requirejs.org/docs/errors.html#mismatch for more details. // Use `_.noConflict` to remove Lodash from the global object. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return _; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } // Check for `exports` after `define` in case a build optimizer adds it. else {} }.call(this)); /***/ }), /***/ "./resources/css/app.css": /*!*******************************!*\ !*** ./resources/css/app.css ***! \*******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /***/ }), /***/ "./node_modules/process/browser.js": /*!*****************************************!*\ !*** ./node_modules/process/browser.js ***! \*****************************************/ /***/ ((module) => { // 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 defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; 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); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; 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.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } 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; }; /***/ }), /***/ "./node_modules/axios/package.json": /*!*****************************************!*\ !*** ./node_modules/axios/package.json ***! \*****************************************/ /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"name":"axios","version":"0.21.4","description":"Promise based HTTP client for the browser and node.js","main":"index.js","scripts":{"test":"grunt test","start":"node ./sandbox/server.js","build":"NODE_ENV=production grunt build","preversion":"npm test","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json","postversion":"git push && git push --tags","examples":"node ./examples/server.js","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js","fix":"eslint --fix lib/**/*.js"},"repository":{"type":"git","url":"https://github.com/axios/axios.git"},"keywords":["xhr","http","ajax","promise","node"],"author":"Matt Zabriskie","license":"MIT","bugs":{"url":"https://github.com/axios/axios/issues"},"homepage":"https://axios-http.com","devDependencies":{"coveralls":"^3.0.0","es6-promise":"^4.2.4","grunt":"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","mocha":"^8.2.1","sinon":"^4.5.0","terser-webpack-plugin":"^4.2.3","typescript":"^4.0.5","url-search-params":"^0.10.0","webpack":"^4.44.2","webpack-dev-server":"^3.11.0"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"jsdelivr":"dist/axios.min.js","unpkg":"dist/axios.min.js","typings":"./index.d.ts","dependencies":{"follow-redirects":"^1.14.0"},"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}]}'); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ id: moduleId, /******/ loaded: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_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 = __webpack_modules__; /******/ /************************************************************************/ /******/ /* webpack/runtime/chunk loaded */ /******/ (() => { /******/ var deferred = []; /******/ __webpack_require__.O = (result, chunkIds, fn, priority) => { /******/ if(chunkIds) { /******/ priority = priority || 0; /******/ for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1]; /******/ deferred[i] = [chunkIds, fn, priority]; /******/ return; /******/ } /******/ var notFulfilled = Infinity; /******/ for (var i = 0; i < deferred.length; i++) { /******/ var [chunkIds, fn, priority] = deferred[i]; /******/ var fulfilled = true; /******/ for (var j = 0; j < chunkIds.length; j++) { /******/ if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) { /******/ chunkIds.splice(j--, 1); /******/ } else { /******/ fulfilled = false; /******/ if(priority < notFulfilled) notFulfilled = priority; /******/ } /******/ } /******/ if(fulfilled) { /******/ deferred.splice(i--, 1) /******/ var r = fn(); /******/ if (r !== undefined) result = r; /******/ } /******/ } /******/ return result; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/node module decorator */ /******/ (() => { /******/ __webpack_require__.nmd = (module) => { /******/ module.paths = []; /******/ if (!module.children) module.children = []; /******/ return module; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/jsonp chunk loading */ /******/ (() => { /******/ // no baseURI /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ "/js/app": 0, /******/ "css/app": 0 /******/ }; /******/ /******/ // no chunk on demand loading /******/ /******/ // no prefetching /******/ /******/ // no preloaded /******/ /******/ // no HMR /******/ /******/ // no HMR manifest /******/ /******/ __webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0); /******/ /******/ // install a JSONP callback for chunk loading /******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => { /******/ var [chunkIds, moreModules, runtime] = data; /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0; /******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) { /******/ for(moduleId in moreModules) { /******/ if(__webpack_require__.o(moreModules, moduleId)) { /******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(runtime) var result = runtime(__webpack_require__); /******/ } /******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { /******/ installedChunks[chunkId][0](); /******/ } /******/ installedChunks[chunkIds[i]] = 0; /******/ } /******/ return __webpack_require__.O(result); /******/ } /******/ /******/ var chunkLoadingGlobal = self["webpackChunk"] = self["webpackChunk"] || []; /******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); /******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); /******/ })(); /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module depends on other loaded chunks and execution need to be delayed /******/ __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/js/app.js"))) /******/ var __webpack_exports__ = __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/css/app.css"))) /******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__); /******/ /******/ })() ;
// THIS FILE IS AUTO GENERATED var GenIcon = require('../lib').GenIcon module.exports.SiGoogleearth = function SiGoogleearth (props) { return GenIcon({"tag":"svg","attr":{"role":"img","viewBox":"0 0 24 24"},"child":[{"tag":"title","attr":{},"child":[]},{"tag":"path","attr":{"d":"M12 0c-1.326 0-2.597.22-3.787.613 4.94-1.243 8.575 1.72 11.096 5.606 1.725 2.695 2.813 2.83 4.207 2.412A11.956 11.956 0 0012 0zM7.658 2.156c-1.644.019-3.295.775-4.931 2.207A11.967 11.967 0 000 12c.184-2.823 2.163-5.128 4.87-5.07 2.104.044 4.648 1.518 7.13 5.289 4.87 7.468 10.917 5.483 11.863 1.51.081-.566.137-1.14.137-1.729 0-.176-.02-.347-.027-.521-1.645 1.725-4.899 2.35-8.264-2.97-2.59-4.363-5.31-6.383-8.05-6.353zM3.33 13.236c-1.675.13-2.657 1.804-2.242 3.756A11.955 11.955 0 0012 24c4.215 0 7.898-2.149 10.037-5.412v-.043c-2.836 3.49-8.946 4.255-13.855-2.182-1.814-2.386-3.544-3.228-4.852-3.127Z"}}]})(props); };
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var paginate = require('mongoose-paginate-v2'); var autopopulate = require('mongoose-autopopulate'); var schema = new Schema({ streamId: String, channelId: String, eventType: Number, duration: Number, fileId: String, fileFormat: String, videoUrl: String, fileSize: String, startTime: Number, endTime: Number, videoId: String, streamParam: String, groupId: Number, publish: Boolean, //创建时间 createAt: { type: Date, default: Date.now }, live: { type: Schema.Types.ObjectId, ref: 'live', autopopulate: true } }); schema.plugin(autopopulate); schema.plugin(paginate); module.exports = mongoose.model('video', schema);
import * as React from "react" function SvgComponent(props) { return <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="scarlab scarlab-rupee-square" {...props}> <path d="M3 12C3 4.5885 4.5885 3 12 3C19.4115 3 21 4.5885 21 12C21 19.4115 19.4115 21 12 21C4.5885 21 3 19.4115 3 12Z" /> <path d="M12 17L9.12186 14.1219V14.1219C9.07689 14.0769 9.11206 13.9992 9.17562 13.9971C13.9993 13.8351 13.9408 7 9 7H15" /> <path d="M9 10.5H15" /> </svg> } export default SvgComponent
const router = require('express').Router(); const apiRoutes = require('./api'); const dashboardRoutes = require('./dashboard-routes.js'); const homeRoutes = require('./home-routes'); router.use('/', homeRoutes); router.use('/dashboard', dashboardRoutes); router.use('/api', apiRoutes); module.exports = router;
<<<<<<< Updated upstream // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require webuploader ======= alert("hello"); >>>>>>> Stashed changes
(window.webpackJsonp=window.webpackJsonp||[]).push([[316],{3928:function(e,t,r){"use strict";r.r(t),r.d(t,"icon",(function(){return c}));r(6),r(7);var n=r(0);function a(){return(a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function l(e,t){if(null==e)return{};var r,n,a=function(e,t){if(null==e)return{};var r,n,a={},l=Object.keys(e);for(n=0;n<l.length;n++)r=l[n],t.indexOf(r)>=0||(a[r]=e[r]);return a}(e,t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(n=0;n<l.length;n++)r=l[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}var c=function(e){var t=e.title,r=e.titleId,c=l(e,["title","titleId"]);return n.createElement("svg",a({width:16,height:16,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":r},c),t?n.createElement("title",{id:r},t):null,n.createElement("g",{fillRule:"evenodd",transform:"translate(0 2)"},n.createElement("path",{fillRule:"nonzero",d:"M2 6a1 1 0 01-1-1V2a1 1 0 011-1h12a1 1 0 011 1v3a1 1 0 01-1 1H2zm13 2v3a1 1 0 01-1 1H2a1 1 0 01-1-1V8a1 1 0 011-1h12a1 1 0 011 1zm1-3V2a2 2 0 00-2-2H2a2 2 0 00-2 2v3c0 .601.271 1.133.69 1.5C.271 6.867 0 7.399 0 8v3a2 2 0 002 2h12a2 2 0 002-2V8c0-.601-.271-1.133-.689-1.5.418-.367.689-.899.689-1.5z"}),n.createElement("circle",{cx:4.5,cy:9.5,r:1.5}),n.createElement("circle",{cx:4.5,cy:3.5,r:1.5}),n.createElement("path",{d:"M12 8h1v3h-1zM10 8h1v3h-1zM12 2h1v3h-1zM10 2h1v3h-1z"})))}}}]); //# sourceMappingURL=icon.storage-js.min.js.map
/* * jsrsasign(all) 8.0.20 (2020-06-24) (c) 2010-2020 Kenji Urushima | kjur.github.com/jsrsasign/license */ var window = {} /*! Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ if(YAHOO===undefined){var YAHOO={}}YAHOO.lang={extend:function(g,h,f){if(!h||!g){throw new Error("YAHOO.lang.extend failed, please check that all dependencies are included.")}var d=function(){};d.prototype=h.prototype;g.prototype=new d();g.prototype.constructor=g;g.superclass=h.prototype;if(h.prototype.constructor==Object.prototype.constructor){h.prototype.constructor=h}if(f){var b;for(b in f){g.prototype[b]=f[b]}var e=function(){},c=["toString","valueOf"];try{if(/MSIE/.test(navigator.userAgent)){e=function(j,i){for(b=0;b<c.length;b=b+1){var l=c[b],k=i[l];if(typeof k==="function"&&k!=Object.prototype[l]){j[l]=k}}}}}catch(a){}e(g.prototype,f)}}}; /*! CryptoJS v3.1.2 core-fix.js * code.google.com/p/crypto-js * (c) 2009-2013 by Jeff Mott. All rights reserved. * code.google.com/p/crypto-js/wiki/License * THIS IS FIX of 'core.js' to fix Hmac issue. * https://code.google.com/p/crypto-js/issues/detail?id=84 * https://crypto-js.googlecode.com/svn-history/r667/branches/3.x/src/core.js */ var CryptoJS=CryptoJS||(function(e,g){var a={};var b=a.lib={};var j=b.Base=(function(){function n(){}return{extend:function(p){n.prototype=this;var o=new n();if(p){o.mixIn(p)}if(!o.hasOwnProperty("init")){o.init=function(){o.$super.init.apply(this,arguments)}}o.init.prototype=o;o.$super=this;return o},create:function(){var o=this.extend();o.init.apply(o,arguments);return o},init:function(){},mixIn:function(p){for(var o in p){if(p.hasOwnProperty(o)){this[o]=p[o]}}if(p.hasOwnProperty("toString")){this.toString=p.toString}},clone:function(){return this.init.prototype.extend(this)}}}());var l=b.WordArray=j.extend({init:function(o,n){o=this.words=o||[];if(n!=g){this.sigBytes=n}else{this.sigBytes=o.length*4}},toString:function(n){return(n||h).stringify(this)},concat:function(t){var q=this.words;var p=t.words;var n=this.sigBytes;var s=t.sigBytes;this.clamp();if(n%4){for(var r=0;r<s;r++){var o=(p[r>>>2]>>>(24-(r%4)*8))&255;q[(n+r)>>>2]|=o<<(24-((n+r)%4)*8)}}else{for(var r=0;r<s;r+=4){q[(n+r)>>>2]=p[r>>>2]}}this.sigBytes+=s;return this},clamp:function(){var o=this.words;var n=this.sigBytes;o[n>>>2]&=4294967295<<(32-(n%4)*8);o.length=e.ceil(n/4)},clone:function(){var n=j.clone.call(this);n.words=this.words.slice(0);return n},random:function(p){var o=[];for(var n=0;n<p;n+=4){o.push((e.random()*4294967296)|0)}return new l.init(o,p)}});var m=a.enc={};var h=m.Hex={stringify:function(p){var r=p.words;var o=p.sigBytes;var q=[];for(var n=0;n<o;n++){var s=(r[n>>>2]>>>(24-(n%4)*8))&255;q.push((s>>>4).toString(16));q.push((s&15).toString(16))}return q.join("")},parse:function(p){var n=p.length;var q=[];for(var o=0;o<n;o+=2){q[o>>>3]|=parseInt(p.substr(o,2),16)<<(24-(o%8)*4)}return new l.init(q,n/2)}};var d=m.Latin1={stringify:function(q){var r=q.words;var p=q.sigBytes;var n=[];for(var o=0;o<p;o++){var s=(r[o>>>2]>>>(24-(o%4)*8))&255;n.push(String.fromCharCode(s))}return n.join("")},parse:function(p){var n=p.length;var q=[];for(var o=0;o<n;o++){q[o>>>2]|=(p.charCodeAt(o)&255)<<(24-(o%4)*8)}return new l.init(q,n)}};var c=m.Utf8={stringify:function(n){try{return decodeURIComponent(escape(d.stringify(n)))}catch(o){throw new Error("Malformed UTF-8 data")}},parse:function(n){return d.parse(unescape(encodeURIComponent(n)))}};var i=b.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=new l.init();this._nDataBytes=0},_append:function(n){if(typeof n=="string"){n=c.parse(n)}this._data.concat(n);this._nDataBytes+=n.sigBytes},_process:function(w){var q=this._data;var x=q.words;var n=q.sigBytes;var t=this.blockSize;var v=t*4;var u=n/v;if(w){u=e.ceil(u)}else{u=e.max((u|0)-this._minBufferSize,0)}var s=u*t;var r=e.min(s*4,n);if(s){for(var p=0;p<s;p+=t){this._doProcessBlock(x,p)}var o=x.splice(0,s);q.sigBytes-=r}return new l.init(o,r)},clone:function(){var n=j.clone.call(this);n._data=this._data.clone();return n},_minBufferSize:0});var f=b.Hasher=i.extend({cfg:j.extend(),init:function(n){this.cfg=this.cfg.extend(n);this.reset()},reset:function(){i.reset.call(this);this._doReset()},update:function(n){this._append(n);this._process();return this},finalize:function(n){if(n){this._append(n)}var o=this._doFinalize();return o},blockSize:512/32,_createHelper:function(n){return function(p,o){return new n.init(o).finalize(p)}},_createHmacHelper:function(n){return function(p,o){return new k.HMAC.init(n,o).finalize(p)}}});var k=a.algo={};return a}(Math)); /* CryptoJS v3.1.2 x64-core-min.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(g){var a=CryptoJS,f=a.lib,e=f.Base,h=f.WordArray,a=a.x64={};a.Word=e.extend({init:function(b,c){this.high=b;this.low=c}});a.WordArray=e.extend({init:function(b,c){b=this.words=b||[];this.sigBytes=c!=g?c:8*b.length},toX32:function(){for(var b=this.words,c=b.length,a=[],d=0;d<c;d++){var e=b[d];a.push(e.high);a.push(e.low)}return h.create(a,this.sigBytes)},clone:function(){for(var b=e.clone.call(this),c=b.words=this.words.slice(0),a=c.length,d=0;d<a;d++)c[d]=c[d].clone();return b}})})(); /* CryptoJS v3.1.2 cipher-core.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ CryptoJS.lib.Cipher||function(u){var g=CryptoJS,f=g.lib,k=f.Base,l=f.WordArray,q=f.BufferedBlockAlgorithm,r=g.enc.Base64,v=g.algo.EvpKDF,n=f.Cipher=q.extend({cfg:k.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c);this._xformMode=a;this._key=b;this.reset()},reset:function(){q.reset.call(this);this._doReset()},process:function(a){this._append(a); return this._process()},finalize:function(a){a&&this._append(a);return this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(a){return{encrypt:function(b,c,d){return("string"==typeof c?s:j).encrypt(a,b,c,d)},decrypt:function(b,c,d){return("string"==typeof c?s:j).decrypt(a,b,c,d)}}}});f.StreamCipher=n.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var m=g.mode={},t=function(a,b,c){var d=this._iv;d?this._iv=u:d=this._prevBlock;for(var e= 0;e<c;e++)a[b+e]^=d[e]},h=(f.BlockCipherMode=k.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a;this._iv=b}})).extend();h.Encryptor=h.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize;t.call(this,a,b,d);c.encryptBlock(a,b);this._prevBlock=a.slice(b,b+d)}});h.Decryptor=h.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=a.slice(b,b+d);c.decryptBlock(a, b);t.call(this,a,b,d);this._prevBlock=e}});m=m.CBC=h;h=(g.pad={}).Pkcs7={pad:function(a,b){for(var c=4*b,c=c-a.sigBytes%c,d=c<<24|c<<16|c<<8|c,e=[],f=0;f<c;f+=4)e.push(d);c=l.create(e,c);a.concat(c)},unpad:function(a){a.sigBytes-=a.words[a.sigBytes-1>>>2]&255}};f.BlockCipher=n.extend({cfg:n.cfg.extend({mode:m,padding:h}),reset:function(){n.reset.call(this);var a=this.cfg,b=a.iv,a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var c=a.createEncryptor;else c=a.createDecryptor,this._minBufferSize=1; this._mode=c.call(a,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!0),a.unpad(b);return b},blockSize:4});var p=f.CipherParams=k.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),m=(g.format={}).OpenSSL={stringify:function(a){var b=a.ciphertext;a=a.salt; return(a?l.create([1398893684,1701076831]).concat(a).concat(b):b).toString(r)},parse:function(a){a=r.parse(a);var b=a.words;if(1398893684==b[0]&&1701076831==b[1]){var c=l.create(b.slice(2,4));b.splice(0,4);a.sigBytes-=16}return p.create({ciphertext:a,salt:c})}},j=f.SerializableCipher=k.extend({cfg:k.extend({format:m}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d);b=e.finalize(b);e=e.cfg;return p.create({ciphertext:b,key:c,iv:e.iv,algorithm:a,mode:e.mode,padding:e.padding, blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);return a.createDecryptor(c,d).finalize(b.ciphertext)},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),g=(g.kdf={}).OpenSSL={execute:function(a,b,c,d){d||(d=l.random(8));a=v.create({keySize:b+c}).compute(a,d);c=l.create(a.words.slice(b),4*c);a.sigBytes=4*b;return p.create({key:a,iv:c,salt:d})}},s=f.PasswordBasedCipher=j.extend({cfg:j.cfg.extend({kdf:g}),encrypt:function(a, b,c,d){d=this.cfg.extend(d);c=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=c.iv;a=j.encrypt.call(this,a,b,c.key,d);a.mixIn(c);return a},decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);c=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=c.iv;return j.decrypt.call(this,a,b,c.key,d)}})}(); /* CryptoJS v3.1.2 aes.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(){for(var q=CryptoJS,x=q.lib.BlockCipher,r=q.algo,j=[],y=[],z=[],A=[],B=[],C=[],s=[],u=[],v=[],w=[],g=[],k=0;256>k;k++)g[k]=128>k?k<<1:k<<1^283;for(var n=0,l=0,k=0;256>k;k++){var f=l^l<<1^l<<2^l<<3^l<<4,f=f>>>8^f&255^99;j[n]=f;y[f]=n;var t=g[n],D=g[t],E=g[D],b=257*g[f]^16843008*f;z[n]=b<<24|b>>>8;A[n]=b<<16|b>>>16;B[n]=b<<8|b>>>24;C[n]=b;b=16843009*E^65537*D^257*t^16843008*n;s[f]=b<<24|b>>>8;u[f]=b<<16|b>>>16;v[f]=b<<8|b>>>24;w[f]=b;n?(n=t^g[g[g[E^t]]],l^=g[g[l]]):n=l=1}var F=[0,1,2,4,8, 16,32,64,128,27,54],r=r.AES=x.extend({_doReset:function(){for(var c=this._key,e=c.words,a=c.sigBytes/4,c=4*((this._nRounds=a+6)+1),b=this._keySchedule=[],h=0;h<c;h++)if(h<a)b[h]=e[h];else{var d=b[h-1];h%a?6<a&&4==h%a&&(d=j[d>>>24]<<24|j[d>>>16&255]<<16|j[d>>>8&255]<<8|j[d&255]):(d=d<<8|d>>>24,d=j[d>>>24]<<24|j[d>>>16&255]<<16|j[d>>>8&255]<<8|j[d&255],d^=F[h/a|0]<<24);b[h]=b[h-a]^d}e=this._invKeySchedule=[];for(a=0;a<c;a++)h=c-a,d=a%4?b[h]:b[h-4],e[a]=4>a||4>=h?d:s[j[d>>>24]]^u[j[d>>>16&255]]^v[j[d>>> 8&255]]^w[j[d&255]]},encryptBlock:function(c,e){this._doCryptBlock(c,e,this._keySchedule,z,A,B,C,j)},decryptBlock:function(c,e){var a=c[e+1];c[e+1]=c[e+3];c[e+3]=a;this._doCryptBlock(c,e,this._invKeySchedule,s,u,v,w,y);a=c[e+1];c[e+1]=c[e+3];c[e+3]=a},_doCryptBlock:function(c,e,a,b,h,d,j,m){for(var n=this._nRounds,f=c[e]^a[0],g=c[e+1]^a[1],k=c[e+2]^a[2],p=c[e+3]^a[3],l=4,t=1;t<n;t++)var q=b[f>>>24]^h[g>>>16&255]^d[k>>>8&255]^j[p&255]^a[l++],r=b[g>>>24]^h[k>>>16&255]^d[p>>>8&255]^j[f&255]^a[l++],s= b[k>>>24]^h[p>>>16&255]^d[f>>>8&255]^j[g&255]^a[l++],p=b[p>>>24]^h[f>>>16&255]^d[g>>>8&255]^j[k&255]^a[l++],f=q,g=r,k=s;q=(m[f>>>24]<<24|m[g>>>16&255]<<16|m[k>>>8&255]<<8|m[p&255])^a[l++];r=(m[g>>>24]<<24|m[k>>>16&255]<<16|m[p>>>8&255]<<8|m[f&255])^a[l++];s=(m[k>>>24]<<24|m[p>>>16&255]<<16|m[f>>>8&255]<<8|m[g&255])^a[l++];p=(m[p>>>24]<<24|m[f>>>16&255]<<16|m[g>>>8&255]<<8|m[k&255])^a[l++];c[e]=q;c[e+1]=r;c[e+2]=s;c[e+3]=p},keySize:8});q.AES=x._createHelper(r)})(); /* CryptoJS v3.1.2 tripledes-min.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(){function j(b,c){var a=(this._lBlock>>>b^this._rBlock)&c;this._rBlock^=a;this._lBlock^=a<<b}function l(b,c){var a=(this._rBlock>>>b^this._lBlock)&c;this._lBlock^=a;this._rBlock^=a<<b}var h=CryptoJS,e=h.lib,n=e.WordArray,e=e.BlockCipher,g=h.algo,q=[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],p=[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],r=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],s=[{"0":8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2, 2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610, 1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{"0":1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224, 75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512, 276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{"0":260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536, 14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404, 17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{"0":2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808, 98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952, 1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{"0":128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256, 10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184, 83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{"0":268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192, 2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{"0":1048576, 16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433, 496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{"0":134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32, 2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760, 2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],t=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],m=g.DES=e.extend({_doReset:function(){for(var b=this._key.words,c=[],a=0;56>a;a++){var f=q[a]-1;c[a]=b[f>>>5]>>>31-f%32&1}b=this._subKeys=[];for(f=0;16>f;f++){for(var d=b[f]=[],e=r[f],a=0;24>a;a++)d[a/6|0]|=c[(p[a]-1+e)%28]<<31-a%6,d[4+(a/6|0)]|=c[28+(p[a+24]-1+e)%28]<<31-a%6;d[0]=d[0]<<1|d[0]>>>31;for(a=1;7>a;a++)d[a]>>>= 4*(a-1)+3;d[7]=d[7]<<5|d[7]>>>27}c=this._invSubKeys=[];for(a=0;16>a;a++)c[a]=b[15-a]},encryptBlock:function(b,c){this._doCryptBlock(b,c,this._subKeys)},decryptBlock:function(b,c){this._doCryptBlock(b,c,this._invSubKeys)},_doCryptBlock:function(b,c,a){this._lBlock=b[c];this._rBlock=b[c+1];j.call(this,4,252645135);j.call(this,16,65535);l.call(this,2,858993459);l.call(this,8,16711935);j.call(this,1,1431655765);for(var f=0;16>f;f++){for(var d=a[f],e=this._lBlock,h=this._rBlock,g=0,k=0;8>k;k++)g|=s[k][((h^ d[k])&t[k])>>>0];this._lBlock=h;this._rBlock=e^g}a=this._lBlock;this._lBlock=this._rBlock;this._rBlock=a;j.call(this,1,1431655765);l.call(this,8,16711935);l.call(this,2,858993459);j.call(this,16,65535);j.call(this,4,252645135);b[c]=this._lBlock;b[c+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});h.DES=e._createHelper(m);g=g.TripleDES=e.extend({_doReset:function(){var b=this._key.words;this._des1=m.createEncryptor(n.create(b.slice(0,2)));this._des2=m.createEncryptor(n.create(b.slice(2,4)));this._des3= m.createEncryptor(n.create(b.slice(4,6)))},encryptBlock:function(b,c){this._des1.encryptBlock(b,c);this._des2.decryptBlock(b,c);this._des3.encryptBlock(b,c)},decryptBlock:function(b,c){this._des3.decryptBlock(b,c);this._des2.encryptBlock(b,c);this._des1.decryptBlock(b,c)},keySize:6,ivSize:2,blockSize:2});h.TripleDES=e._createHelper(g)})(); /* CryptoJS v3.1.2 enc-base64.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(){var h=CryptoJS,j=h.lib.WordArray;h.enc.Base64={stringify:function(b){var e=b.words,f=b.sigBytes,c=this._map;b.clamp();b=[];for(var a=0;a<f;a+=3)for(var d=(e[a>>>2]>>>24-8*(a%4)&255)<<16|(e[a+1>>>2]>>>24-8*((a+1)%4)&255)<<8|e[a+2>>>2]>>>24-8*((a+2)%4)&255,g=0;4>g&&a+0.75*g<f;g++)b.push(c.charAt(d>>>6*(3-g)&63));if(e=c.charAt(64))for(;b.length%4;)b.push(e);return b.join("")},parse:function(b){var e=b.length,f=this._map,c=f.charAt(64);c&&(c=b.indexOf(c),-1!=c&&(e=c));for(var c=[],a=0,d=0;d< e;d++)if(d%4){var g=f.indexOf(b.charAt(d-1))<<2*(d%4),h=f.indexOf(b.charAt(d))>>>6-2*(d%4);c[a>>>2]|=(g|h)<<24-8*(a%4);a++}return j.create(c,a)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(); /* CryptoJS v3.1.2 md5.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(E){function h(a,f,g,j,p,h,k){a=a+(f&g|~f&j)+p+k;return(a<<h|a>>>32-h)+f}function k(a,f,g,j,p,h,k){a=a+(f&j|g&~j)+p+k;return(a<<h|a>>>32-h)+f}function l(a,f,g,j,h,k,l){a=a+(f^g^j)+h+l;return(a<<k|a>>>32-k)+f}function n(a,f,g,j,h,k,l){a=a+(g^(f|~j))+h+l;return(a<<k|a>>>32-k)+f}for(var r=CryptoJS,q=r.lib,F=q.WordArray,s=q.Hasher,q=r.algo,a=[],t=0;64>t;t++)a[t]=4294967296*E.abs(E.sin(t+1))|0;q=q.MD5=s.extend({_doReset:function(){this._hash=new F.init([1732584193,4023233417,2562383102,271733878])}, _doProcessBlock:function(m,f){for(var g=0;16>g;g++){var j=f+g,p=m[j];m[j]=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360}var g=this._hash.words,j=m[f+0],p=m[f+1],q=m[f+2],r=m[f+3],s=m[f+4],t=m[f+5],u=m[f+6],v=m[f+7],w=m[f+8],x=m[f+9],y=m[f+10],z=m[f+11],A=m[f+12],B=m[f+13],C=m[f+14],D=m[f+15],b=g[0],c=g[1],d=g[2],e=g[3],b=h(b,c,d,e,j,7,a[0]),e=h(e,b,c,d,p,12,a[1]),d=h(d,e,b,c,q,17,a[2]),c=h(c,d,e,b,r,22,a[3]),b=h(b,c,d,e,s,7,a[4]),e=h(e,b,c,d,t,12,a[5]),d=h(d,e,b,c,u,17,a[6]),c=h(c,d,e,b,v,22,a[7]), b=h(b,c,d,e,w,7,a[8]),e=h(e,b,c,d,x,12,a[9]),d=h(d,e,b,c,y,17,a[10]),c=h(c,d,e,b,z,22,a[11]),b=h(b,c,d,e,A,7,a[12]),e=h(e,b,c,d,B,12,a[13]),d=h(d,e,b,c,C,17,a[14]),c=h(c,d,e,b,D,22,a[15]),b=k(b,c,d,e,p,5,a[16]),e=k(e,b,c,d,u,9,a[17]),d=k(d,e,b,c,z,14,a[18]),c=k(c,d,e,b,j,20,a[19]),b=k(b,c,d,e,t,5,a[20]),e=k(e,b,c,d,y,9,a[21]),d=k(d,e,b,c,D,14,a[22]),c=k(c,d,e,b,s,20,a[23]),b=k(b,c,d,e,x,5,a[24]),e=k(e,b,c,d,C,9,a[25]),d=k(d,e,b,c,r,14,a[26]),c=k(c,d,e,b,w,20,a[27]),b=k(b,c,d,e,B,5,a[28]),e=k(e,b, c,d,q,9,a[29]),d=k(d,e,b,c,v,14,a[30]),c=k(c,d,e,b,A,20,a[31]),b=l(b,c,d,e,t,4,a[32]),e=l(e,b,c,d,w,11,a[33]),d=l(d,e,b,c,z,16,a[34]),c=l(c,d,e,b,C,23,a[35]),b=l(b,c,d,e,p,4,a[36]),e=l(e,b,c,d,s,11,a[37]),d=l(d,e,b,c,v,16,a[38]),c=l(c,d,e,b,y,23,a[39]),b=l(b,c,d,e,B,4,a[40]),e=l(e,b,c,d,j,11,a[41]),d=l(d,e,b,c,r,16,a[42]),c=l(c,d,e,b,u,23,a[43]),b=l(b,c,d,e,x,4,a[44]),e=l(e,b,c,d,A,11,a[45]),d=l(d,e,b,c,D,16,a[46]),c=l(c,d,e,b,q,23,a[47]),b=n(b,c,d,e,j,6,a[48]),e=n(e,b,c,d,v,10,a[49]),d=n(d,e,b,c, C,15,a[50]),c=n(c,d,e,b,t,21,a[51]),b=n(b,c,d,e,A,6,a[52]),e=n(e,b,c,d,r,10,a[53]),d=n(d,e,b,c,y,15,a[54]),c=n(c,d,e,b,p,21,a[55]),b=n(b,c,d,e,w,6,a[56]),e=n(e,b,c,d,D,10,a[57]),d=n(d,e,b,c,u,15,a[58]),c=n(c,d,e,b,B,21,a[59]),b=n(b,c,d,e,s,6,a[60]),e=n(e,b,c,d,z,10,a[61]),d=n(d,e,b,c,q,15,a[62]),c=n(c,d,e,b,x,21,a[63]);g[0]=g[0]+b|0;g[1]=g[1]+c|0;g[2]=g[2]+d|0;g[3]=g[3]+e|0},_doFinalize:function(){var a=this._data,f=a.words,g=8*this._nDataBytes,j=8*a.sigBytes;f[j>>>5]|=128<<24-j%32;var h=E.floor(g/ 4294967296);f[(j+64>>>9<<4)+15]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360;f[(j+64>>>9<<4)+14]=(g<<8|g>>>24)&16711935|(g<<24|g>>>8)&4278255360;a.sigBytes=4*(f.length+1);this._process();a=this._hash;f=a.words;for(g=0;4>g;g++)j=f[g],f[g]=(j<<8|j>>>24)&16711935|(j<<24|j>>>8)&4278255360;return a},clone:function(){var a=s.clone.call(this);a._hash=this._hash.clone();return a}});r.MD5=s._createHelper(q);r.HmacMD5=s._createHmacHelper(q)})(Math); /* CryptoJS v3.1.2 sha1-min.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(){var k=CryptoJS,b=k.lib,m=b.WordArray,l=b.Hasher,d=[],b=k.algo.SHA1=l.extend({_doReset:function(){this._hash=new m.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(n,p){for(var a=this._hash.words,e=a[0],f=a[1],h=a[2],j=a[3],b=a[4],c=0;80>c;c++){if(16>c)d[c]=n[p+c]|0;else{var g=d[c-3]^d[c-8]^d[c-14]^d[c-16];d[c]=g<<1|g>>>31}g=(e<<5|e>>>27)+b+d[c];g=20>c?g+((f&h|~f&j)+1518500249):40>c?g+((f^h^j)+1859775393):60>c?g+((f&h|f&j|h&j)-1894007588):g+((f^h^ j)-899497514);b=j;j=h;h=f<<30|f>>>2;f=e;e=g}a[0]=a[0]+e|0;a[1]=a[1]+f|0;a[2]=a[2]+h|0;a[3]=a[3]+j|0;a[4]=a[4]+b|0},_doFinalize:function(){var b=this._data,d=b.words,a=8*this._nDataBytes,e=8*b.sigBytes;d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=Math.floor(a/4294967296);d[(e+64>>>9<<4)+15]=a;b.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var b=l.clone.call(this);b._hash=this._hash.clone();return b}});k.SHA1=l._createHelper(b);k.HmacSHA1=l._createHmacHelper(b)})(); /* CryptoJS v3.1.2 sha256-min.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(k){for(var g=CryptoJS,h=g.lib,v=h.WordArray,j=h.Hasher,h=g.algo,s=[],t=[],u=function(q){return 4294967296*(q-(q|0))|0},l=2,b=0;64>b;){var d;a:{d=l;for(var w=k.sqrt(d),r=2;r<=w;r++)if(!(d%r)){d=!1;break a}d=!0}d&&(8>b&&(s[b]=u(k.pow(l,0.5))),t[b]=u(k.pow(l,1/3)),b++);l++}var n=[],h=h.SHA256=j.extend({_doReset:function(){this._hash=new v.init(s.slice(0))},_doProcessBlock:function(q,h){for(var a=this._hash.words,c=a[0],d=a[1],b=a[2],k=a[3],f=a[4],g=a[5],j=a[6],l=a[7],e=0;64>e;e++){if(16>e)n[e]= q[h+e]|0;else{var m=n[e-15],p=n[e-2];n[e]=((m<<25|m>>>7)^(m<<14|m>>>18)^m>>>3)+n[e-7]+((p<<15|p>>>17)^(p<<13|p>>>19)^p>>>10)+n[e-16]}m=l+((f<<26|f>>>6)^(f<<21|f>>>11)^(f<<7|f>>>25))+(f&g^~f&j)+t[e]+n[e];p=((c<<30|c>>>2)^(c<<19|c>>>13)^(c<<10|c>>>22))+(c&d^c&b^d&b);l=j;j=g;g=f;f=k+m|0;k=b;b=d;d=c;c=m+p|0}a[0]=a[0]+c|0;a[1]=a[1]+d|0;a[2]=a[2]+b|0;a[3]=a[3]+k|0;a[4]=a[4]+f|0;a[5]=a[5]+g|0;a[6]=a[6]+j|0;a[7]=a[7]+l|0},_doFinalize:function(){var d=this._data,b=d.words,a=8*this._nDataBytes,c=8*d.sigBytes; b[c>>>5]|=128<<24-c%32;b[(c+64>>>9<<4)+14]=k.floor(a/4294967296);b[(c+64>>>9<<4)+15]=a;d.sigBytes=4*b.length;this._process();return this._hash},clone:function(){var b=j.clone.call(this);b._hash=this._hash.clone();return b}});g.SHA256=j._createHelper(h);g.HmacSHA256=j._createHmacHelper(h)})(Math); /* CryptoJS v3.1.2 sha224-min.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(){var b=CryptoJS,d=b.lib.WordArray,a=b.algo,c=a.SHA256,a=a.SHA224=c.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=c._doFinalize.call(this);a.sigBytes-=4;return a}});b.SHA224=c._createHelper(a);b.HmacSHA224=c._createHmacHelper(a)})(); /* CryptoJS v3.1.2 sha512-min.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(){function a(){return d.create.apply(d,arguments)}for(var n=CryptoJS,r=n.lib.Hasher,e=n.x64,d=e.Word,T=e.WordArray,e=n.algo,ea=[a(1116352408,3609767458),a(1899447441,602891725),a(3049323471,3964484399),a(3921009573,2173295548),a(961987163,4081628472),a(1508970993,3053834265),a(2453635748,2937671579),a(2870763221,3664609560),a(3624381080,2734883394),a(310598401,1164996542),a(607225278,1323610764),a(1426881987,3590304994),a(1925078388,4068182383),a(2162078206,991336113),a(2614888103,633803317), a(3248222580,3479774868),a(3835390401,2666613458),a(4022224774,944711139),a(264347078,2341262773),a(604807628,2007800933),a(770255983,1495990901),a(1249150122,1856431235),a(1555081692,3175218132),a(1996064986,2198950837),a(2554220882,3999719339),a(2821834349,766784016),a(2952996808,2566594879),a(3210313671,3203337956),a(3336571891,1034457026),a(3584528711,2466948901),a(113926993,3758326383),a(338241895,168717936),a(666307205,1188179964),a(773529912,1546045734),a(1294757372,1522805485),a(1396182291, 2643833823),a(1695183700,2343527390),a(1986661051,1014477480),a(2177026350,1206759142),a(2456956037,344077627),a(2730485921,1290863460),a(2820302411,3158454273),a(3259730800,3505952657),a(3345764771,106217008),a(3516065817,3606008344),a(3600352804,1432725776),a(4094571909,1467031594),a(275423344,851169720),a(430227734,3100823752),a(506948616,1363258195),a(659060556,3750685593),a(883997877,3785050280),a(958139571,3318307427),a(1322822218,3812723403),a(1537002063,2003034995),a(1747873779,3602036899), a(1955562222,1575990012),a(2024104815,1125592928),a(2227730452,2716904306),a(2361852424,442776044),a(2428436474,593698344),a(2756734187,3733110249),a(3204031479,2999351573),a(3329325298,3815920427),a(3391569614,3928383900),a(3515267271,566280711),a(3940187606,3454069534),a(4118630271,4000239992),a(116418474,1914138554),a(174292421,2731055270),a(289380356,3203993006),a(460393269,320620315),a(685471733,587496836),a(852142971,1086792851),a(1017036298,365543100),a(1126000580,2618297676),a(1288033470, 3409855158),a(1501505948,4234509866),a(1607167915,987167468),a(1816402316,1246189591)],v=[],w=0;80>w;w++)v[w]=a();e=e.SHA512=r.extend({_doReset:function(){this._hash=new T.init([new d.init(1779033703,4089235720),new d.init(3144134277,2227873595),new d.init(1013904242,4271175723),new d.init(2773480762,1595750129),new d.init(1359893119,2917565137),new d.init(2600822924,725511199),new d.init(528734635,4215389547),new d.init(1541459225,327033209)])},_doProcessBlock:function(a,d){for(var f=this._hash.words, F=f[0],e=f[1],n=f[2],r=f[3],G=f[4],H=f[5],I=f[6],f=f[7],w=F.high,J=F.low,X=e.high,K=e.low,Y=n.high,L=n.low,Z=r.high,M=r.low,$=G.high,N=G.low,aa=H.high,O=H.low,ba=I.high,P=I.low,ca=f.high,Q=f.low,k=w,g=J,z=X,x=K,A=Y,y=L,U=Z,B=M,l=$,h=N,R=aa,C=O,S=ba,D=P,V=ca,E=Q,m=0;80>m;m++){var s=v[m];if(16>m)var j=s.high=a[d+2*m]|0,b=s.low=a[d+2*m+1]|0;else{var j=v[m-15],b=j.high,p=j.low,j=(b>>>1|p<<31)^(b>>>8|p<<24)^b>>>7,p=(p>>>1|b<<31)^(p>>>8|b<<24)^(p>>>7|b<<25),u=v[m-2],b=u.high,c=u.low,u=(b>>>19|c<<13)^(b<< 3|c>>>29)^b>>>6,c=(c>>>19|b<<13)^(c<<3|b>>>29)^(c>>>6|b<<26),b=v[m-7],W=b.high,t=v[m-16],q=t.high,t=t.low,b=p+b.low,j=j+W+(b>>>0<p>>>0?1:0),b=b+c,j=j+u+(b>>>0<c>>>0?1:0),b=b+t,j=j+q+(b>>>0<t>>>0?1:0);s.high=j;s.low=b}var W=l&R^~l&S,t=h&C^~h&D,s=k&z^k&A^z&A,T=g&x^g&y^x&y,p=(k>>>28|g<<4)^(k<<30|g>>>2)^(k<<25|g>>>7),u=(g>>>28|k<<4)^(g<<30|k>>>2)^(g<<25|k>>>7),c=ea[m],fa=c.high,da=c.low,c=E+((h>>>14|l<<18)^(h>>>18|l<<14)^(h<<23|l>>>9)),q=V+((l>>>14|h<<18)^(l>>>18|h<<14)^(l<<23|h>>>9))+(c>>>0<E>>>0?1: 0),c=c+t,q=q+W+(c>>>0<t>>>0?1:0),c=c+da,q=q+fa+(c>>>0<da>>>0?1:0),c=c+b,q=q+j+(c>>>0<b>>>0?1:0),b=u+T,s=p+s+(b>>>0<u>>>0?1:0),V=S,E=D,S=R,D=C,R=l,C=h,h=B+c|0,l=U+q+(h>>>0<B>>>0?1:0)|0,U=A,B=y,A=z,y=x,z=k,x=g,g=c+b|0,k=q+s+(g>>>0<c>>>0?1:0)|0}J=F.low=J+g;F.high=w+k+(J>>>0<g>>>0?1:0);K=e.low=K+x;e.high=X+z+(K>>>0<x>>>0?1:0);L=n.low=L+y;n.high=Y+A+(L>>>0<y>>>0?1:0);M=r.low=M+B;r.high=Z+U+(M>>>0<B>>>0?1:0);N=G.low=N+h;G.high=$+l+(N>>>0<h>>>0?1:0);O=H.low=O+C;H.high=aa+R+(O>>>0<C>>>0?1:0);P=I.low=P+D; I.high=ba+S+(P>>>0<D>>>0?1:0);Q=f.low=Q+E;f.high=ca+V+(Q>>>0<E>>>0?1:0)},_doFinalize:function(){var a=this._data,d=a.words,f=8*this._nDataBytes,e=8*a.sigBytes;d[e>>>5]|=128<<24-e%32;d[(e+128>>>10<<5)+30]=Math.floor(f/4294967296);d[(e+128>>>10<<5)+31]=f;a.sigBytes=4*d.length;this._process();return this._hash.toX32()},clone:function(){var a=r.clone.call(this);a._hash=this._hash.clone();return a},blockSize:32});n.SHA512=r._createHelper(e);n.HmacSHA512=r._createHmacHelper(e)})(); /* CryptoJS v3.1.2 sha384-min.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(){var c=CryptoJS,a=c.x64,b=a.Word,e=a.WordArray,a=c.algo,d=a.SHA512,a=a.SHA384=d.extend({_doReset:function(){this._hash=new e.init([new b.init(3418070365,3238371032),new b.init(1654270250,914150663),new b.init(2438529370,812702999),new b.init(355462360,4144912697),new b.init(1731405415,4290775857),new b.init(2394180231,1750603025),new b.init(3675008525,1694076839),new b.init(1203062813,3204075428)])},_doFinalize:function(){var a=d._doFinalize.call(this);a.sigBytes-=16;return a}});c.SHA384= d._createHelper(a);c.HmacSHA384=d._createHmacHelper(a)})(); /* CryptoJS v3.1.2 ripemd160-min.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ /* (c) 2012 by Cedric 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(){var q=CryptoJS,d=q.lib,n=d.WordArray,p=d.Hasher,d=q.algo,x=n.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]),y=n.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]),z=n.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]),A=n.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]),B=n.create([0,1518500249,1859775393,2400959708,2840853838]),C=n.create([1352829926,1548603684,1836072691, 2053994217,0]),d=d.RIPEMD160=p.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,v){for(var b=0;16>b;b++){var c=v+b,f=e[c];e[c]=(f<<8|f>>>24)&16711935|(f<<24|f>>>8)&4278255360}var c=this._hash.words,f=B.words,d=C.words,n=x.words,q=y.words,p=z.words,w=A.words,t,g,h,j,r,u,k,l,m,s;u=t=c[0];k=g=c[1];l=h=c[2];m=j=c[3];s=r=c[4];for(var a,b=0;80>b;b+=1)a=t+e[v+n[b]]|0,a=16>b?a+((g^h^j)+f[0]):32>b?a+((g&h|~g&j)+f[1]):48>b? a+(((g|~h)^j)+f[2]):64>b?a+((g&j|h&~j)+f[3]):a+((g^(h|~j))+f[4]),a|=0,a=a<<p[b]|a>>>32-p[b],a=a+r|0,t=r,r=j,j=h<<10|h>>>22,h=g,g=a,a=u+e[v+q[b]]|0,a=16>b?a+((k^(l|~m))+d[0]):32>b?a+((k&m|l&~m)+d[1]):48>b?a+(((k|~l)^m)+d[2]):64>b?a+((k&l|~k&m)+d[3]):a+((k^l^m)+d[4]),a|=0,a=a<<w[b]|a>>>32-w[b],a=a+s|0,u=s,s=m,m=l<<10|l>>>22,l=k,k=a;a=c[1]+h+m|0;c[1]=c[2]+j+s|0;c[2]=c[3]+r+u|0;c[3]=c[4]+t+k|0;c[4]=c[0]+g+l|0;c[0]=a},_doFinalize:function(){var e=this._data,d=e.words,b=8*this._nDataBytes,c=8*e.sigBytes; d[c>>>5]|=128<<24-c%32;d[(c+64>>>9<<4)+14]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;e.sigBytes=4*(d.length+1);this._process();e=this._hash;d=e.words;for(b=0;5>b;b++)c=d[b],d[b]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;return e},clone:function(){var d=p.clone.call(this);d._hash=this._hash.clone();return d}});q.RIPEMD160=p._createHelper(d);q.HmacRIPEMD160=p._createHmacHelper(d)})(Math); /* CryptoJS v3.1.2 hmac.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(){var c=CryptoJS,k=c.enc.Utf8;c.algo.HMAC=c.lib.Base.extend({init:function(a,b){a=this._hasher=new a.init;"string"==typeof b&&(b=k.parse(b));var c=a.blockSize,e=4*c;b.sigBytes>e&&(b=a.finalize(b));b.clamp();for(var f=this._oKey=b.clone(),g=this._iKey=b.clone(),h=f.words,j=g.words,d=0;d<c;d++)h[d]^=1549556828,j[d]^=909522486;f.sigBytes=g.sigBytes=e;this.reset()},reset:function(){var a=this._hasher;a.reset();a.update(this._iKey)},update:function(a){this._hasher.update(a);return this},finalize:function(a){var b= this._hasher;a=b.finalize(a);b.reset();return b.finalize(this._oKey.clone().concat(a))}})})(); /* CryptoJS v3.1.2 pbkdf2-min.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function(){var b=CryptoJS,a=b.lib,d=a.Base,m=a.WordArray,a=b.algo,q=a.HMAC,l=a.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:a.SHA1,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,f=q.create(c.hasher,a),g=m.create(),d=m.create([1]),l=g.words,r=d.words,n=c.keySize,c=c.iterations;l.length<n;){var h=f.update(b).finalize(d);f.reset();for(var j=h.words,s=j.length,k=h,p=1;p<c;p++){k=f.finalize(k);f.reset();for(var t=k.words,e=0;e<s;e++)j[e]^=t[e]}g.concat(h); r[0]++}g.sigBytes=4*n;return g}});b.PBKDF2=function(a,b,c){return l.create(c).compute(a,b)}})(); /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var b64pad="=";function hex2b64(d){var b;var e;var a="";for(b=0;b+3<=d.length;b+=3){e=parseInt(d.substring(b,b+3),16);a+=b64map.charAt(e>>6)+b64map.charAt(e&63)}if(b+1==d.length){e=parseInt(d.substring(b,b+1),16);a+=b64map.charAt(e<<2)}else{if(b+2==d.length){e=parseInt(d.substring(b,b+2),16);a+=b64map.charAt(e>>2)+b64map.charAt((e&3)<<4)}}if(b64pad){while((a.length&3)>0){a+=b64pad}}return a}function b64tohex(f){var d="";var e;var b=0;var c;var a;for(e=0;e<f.length;++e){if(f.charAt(e)==b64pad){break}a=b64map.indexOf(f.charAt(e));if(a<0){continue}if(b==0){d+=int2char(a>>2);c=a&3;b=1}else{if(b==1){d+=int2char((c<<2)|(a>>4));c=a&15;b=2}else{if(b==2){d+=int2char(c);d+=int2char(a>>2);c=a&3;b=3}else{d+=int2char((c<<2)|(a>>4));d+=int2char(a&15);b=0}}}}if(b==1){d+=int2char(c<<2)}return d}function b64toBA(e){var d=b64tohex(e);var c;var b=new Array();for(c=0;2*c<d.length;++c){b[c]=parseInt(d.substring(2*c,2*c+2),16)}return b}; /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ var dbits;var canary=244837814094590;var j_lm=((canary&16777215)==15715070);function BigInteger(e,d,f){if(e!=null){if("number"==typeof e){this.fromNumber(e,d,f)}else{if(d==null&&"string"!=typeof e){this.fromString(e,256)}else{this.fromString(e,d)}}}}function nbi(){return new BigInteger(null)}function am1(f,a,b,e,h,g){while(--g>=0){var d=a*this[f++]+b[e]+h;h=Math.floor(d/67108864);b[e++]=d&67108863}return h}function am2(f,q,r,e,o,a){var k=q&32767,p=q>>15;while(--a>=0){var d=this[f]&32767;var g=this[f++]>>15;var b=p*d+g*k;d=k*d+((b&32767)<<15)+r[e]+(o&1073741823);o=(d>>>30)+(b>>>15)+p*g+(o>>>30);r[e++]=d&1073741823}return o}function am3(f,q,r,e,o,a){var k=q&16383,p=q>>14;while(--a>=0){var d=this[f]&16383;var g=this[f++]>>14;var b=p*d+g*k;d=k*d+((b&16383)<<14)+r[e]+o;o=(d>>28)+(b>>14)+p*g;r[e++]=d&268435455}return o}if(j_lm&&(navigator.appName=="Microsoft Internet Explorer")){BigInteger.prototype.am=am2;dbits=30}else{if(j_lm&&(navigator.appName!="Netscape")){BigInteger.prototype.am=am1;dbits=26}else{BigInteger.prototype.am=am3;dbits=28}}BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=((1<<dbits)-1);BigInteger.prototype.DV=(1<<dbits);var BI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP);BigInteger.prototype.F1=BI_FP-dbits;BigInteger.prototype.F2=2*dbits-BI_FP;var BI_RM="0123456789abcdefghijklmnopqrstuvwxyz";var BI_RC=new Array();var rr,vv;rr="0".charCodeAt(0);for(vv=0;vv<=9;++vv){BI_RC[rr++]=vv}rr="a".charCodeAt(0);for(vv=10;vv<36;++vv){BI_RC[rr++]=vv}rr="A".charCodeAt(0);for(vv=10;vv<36;++vv){BI_RC[rr++]=vv}function int2char(a){return BI_RM.charAt(a)}function intAt(b,a){var d=BI_RC[b.charCodeAt(a)];return(d==null)?-1:d}function bnpCopyTo(b){for(var a=this.t-1;a>=0;--a){b[a]=this[a]}b.t=this.t;b.s=this.s}function bnpFromInt(a){this.t=1;this.s=(a<0)?-1:0;if(a>0){this[0]=a}else{if(a<-1){this[0]=a+this.DV}else{this.t=0}}}function nbv(a){var b=nbi();b.fromInt(a);return b}function bnpFromString(h,c){var e;if(c==16){e=4}else{if(c==8){e=3}else{if(c==256){e=8}else{if(c==2){e=1}else{if(c==32){e=5}else{if(c==4){e=2}else{this.fromRadix(h,c);return}}}}}}this.t=0;this.s=0;var g=h.length,d=false,f=0;while(--g>=0){var a=(e==8)?h[g]&255:intAt(h,g);if(a<0){if(h.charAt(g)=="-"){d=true}continue}d=false;if(f==0){this[this.t++]=a}else{if(f+e>this.DB){this[this.t-1]|=(a&((1<<(this.DB-f))-1))<<f;this[this.t++]=(a>>(this.DB-f))}else{this[this.t-1]|=a<<f}}f+=e;if(f>=this.DB){f-=this.DB}}if(e==8&&(h[0]&128)!=0){this.s=-1;if(f>0){this[this.t-1]|=((1<<(this.DB-f))-1)<<f}}this.clamp();if(d){BigInteger.ZERO.subTo(this,this)}}function bnpClamp(){var a=this.s&this.DM;while(this.t>0&&this[this.t-1]==a){--this.t}}function bnToString(c){if(this.s<0){return"-"+this.negate().toString(c)}var e;if(c==16){e=4}else{if(c==8){e=3}else{if(c==2){e=1}else{if(c==32){e=5}else{if(c==4){e=2}else{return this.toRadix(c)}}}}}var g=(1<<e)-1,l,a=false,h="",f=this.t;var j=this.DB-(f*this.DB)%e;if(f-->0){if(j<this.DB&&(l=this[f]>>j)>0){a=true;h=int2char(l)}while(f>=0){if(j<e){l=(this[f]&((1<<j)-1))<<(e-j);l|=this[--f]>>(j+=this.DB-e)}else{l=(this[f]>>(j-=e))&g;if(j<=0){j+=this.DB;--f}}if(l>0){a=true}if(a){h+=int2char(l)}}}return a?h:"0"}function bnNegate(){var a=nbi();BigInteger.ZERO.subTo(this,a);return a}function bnAbs(){return(this.s<0)?this.negate():this}function bnCompareTo(b){var d=this.s-b.s;if(d!=0){return d}var c=this.t;d=c-b.t;if(d!=0){return(this.s<0)?-d:d}while(--c>=0){if((d=this[c]-b[c])!=0){return d}}return 0}function nbits(a){var c=1,b;if((b=a>>>16)!=0){a=b;c+=16}if((b=a>>8)!=0){a=b;c+=8}if((b=a>>4)!=0){a=b;c+=4}if((b=a>>2)!=0){a=b;c+=2}if((b=a>>1)!=0){a=b;c+=1}return c}function bnBitLength(){if(this.t<=0){return 0}return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM))}function bnpDLShiftTo(c,b){var a;for(a=this.t-1;a>=0;--a){b[a+c]=this[a]}for(a=c-1;a>=0;--a){b[a]=0}b.t=this.t+c;b.s=this.s}function bnpDRShiftTo(c,b){for(var a=c;a<this.t;++a){b[a-c]=this[a]}b.t=Math.max(this.t-c,0);b.s=this.s}function bnpLShiftTo(j,e){var b=j%this.DB;var a=this.DB-b;var g=(1<<a)-1;var f=Math.floor(j/this.DB),h=(this.s<<b)&this.DM,d;for(d=this.t-1;d>=0;--d){e[d+f+1]=(this[d]>>a)|h;h=(this[d]&g)<<b}for(d=f-1;d>=0;--d){e[d]=0}e[f]=h;e.t=this.t+f+1;e.s=this.s;e.clamp()}function bnpRShiftTo(g,d){d.s=this.s;var e=Math.floor(g/this.DB);if(e>=this.t){d.t=0;return}var b=g%this.DB;var a=this.DB-b;var f=(1<<b)-1;d[0]=this[e]>>b;for(var c=e+1;c<this.t;++c){d[c-e-1]|=(this[c]&f)<<a;d[c-e]=this[c]>>b}if(b>0){d[this.t-e-1]|=(this.s&f)<<a}d.t=this.t-e;d.clamp()}function bnpSubTo(d,f){var e=0,g=0,b=Math.min(d.t,this.t);while(e<b){g+=this[e]-d[e];f[e++]=g&this.DM;g>>=this.DB}if(d.t<this.t){g-=d.s;while(e<this.t){g+=this[e];f[e++]=g&this.DM;g>>=this.DB}g+=this.s}else{g+=this.s;while(e<d.t){g-=d[e];f[e++]=g&this.DM;g>>=this.DB}g-=d.s}f.s=(g<0)?-1:0;if(g<-1){f[e++]=this.DV+g}else{if(g>0){f[e++]=g}}f.t=e;f.clamp()}function bnpMultiplyTo(c,e){var b=this.abs(),f=c.abs();var d=b.t;e.t=d+f.t;while(--d>=0){e[d]=0}for(d=0;d<f.t;++d){e[d+b.t]=b.am(0,f[d],e,d,0,b.t)}e.s=0;e.clamp();if(this.s!=c.s){BigInteger.ZERO.subTo(e,e)}}function bnpSquareTo(d){var a=this.abs();var b=d.t=2*a.t;while(--b>=0){d[b]=0}for(b=0;b<a.t-1;++b){var e=a.am(b,a[b],d,2*b,0,1);if((d[b+a.t]+=a.am(b+1,2*a[b],d,2*b+1,e,a.t-b-1))>=a.DV){d[b+a.t]-=a.DV;d[b+a.t+1]=1}}if(d.t>0){d[d.t-1]+=a.am(b,a[b],d,2*b,0,1)}d.s=0;d.clamp()}function bnpDivRemTo(n,h,g){var w=n.abs();if(w.t<=0){return}var k=this.abs();if(k.t<w.t){if(h!=null){h.fromInt(0)}if(g!=null){this.copyTo(g)}return}if(g==null){g=nbi()}var d=nbi(),a=this.s,l=n.s;var v=this.DB-nbits(w[w.t-1]);if(v>0){w.lShiftTo(v,d);k.lShiftTo(v,g)}else{w.copyTo(d);k.copyTo(g)}var p=d.t;var b=d[p-1];if(b==0){return}var o=b*(1<<this.F1)+((p>1)?d[p-2]>>this.F2:0);var A=this.FV/o,z=(1<<this.F1)/o,x=1<<this.F2;var u=g.t,s=u-p,f=(h==null)?nbi():h;d.dlShiftTo(s,f);if(g.compareTo(f)>=0){g[g.t++]=1;g.subTo(f,g)}BigInteger.ONE.dlShiftTo(p,f);f.subTo(d,d);while(d.t<p){d[d.t++]=0}while(--s>=0){var c=(g[--u]==b)?this.DM:Math.floor(g[u]*A+(g[u-1]+x)*z);if((g[u]+=d.am(0,c,g,s,0,p))<c){d.dlShiftTo(s,f);g.subTo(f,g);while(g[u]<--c){g.subTo(f,g)}}}if(h!=null){g.drShiftTo(p,h);if(a!=l){BigInteger.ZERO.subTo(h,h)}}g.t=p;g.clamp();if(v>0){g.rShiftTo(v,g)}if(a<0){BigInteger.ZERO.subTo(g,g)}}function bnMod(b){var c=nbi();this.abs().divRemTo(b,null,c);if(this.s<0&&c.compareTo(BigInteger.ZERO)>0){b.subTo(c,c)}return c}function Classic(a){this.m=a}function cConvert(a){if(a.s<0||a.compareTo(this.m)>=0){return a.mod(this.m)}else{return a}}function cRevert(a){return a}function cReduce(a){a.divRemTo(this.m,null,a)}function cMulTo(a,c,b){a.multiplyTo(c,b);this.reduce(b)}function cSqrTo(a,b){a.squareTo(b);this.reduce(b)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1){return 0}var a=this[0];if((a&1)==0){return 0}var b=a&3;b=(b*(2-(a&15)*b))&15;b=(b*(2-(a&255)*b))&255;b=(b*(2-(((a&65535)*b)&65535)))&65535;b=(b*(2-a*b%this.DV))%this.DV;return(b>0)?this.DV-b:-b}function Montgomery(a){this.m=a;this.mp=a.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<(a.DB-15))-1;this.mt2=2*a.t}function montConvert(a){var b=nbi();a.abs().dlShiftTo(this.m.t,b);b.divRemTo(this.m,null,b);if(a.s<0&&b.compareTo(BigInteger.ZERO)>0){this.m.subTo(b,b)}return b}function montRevert(a){var b=nbi();a.copyTo(b);this.reduce(b);return b}function montReduce(a){while(a.t<=this.mt2){a[a.t++]=0}for(var c=0;c<this.m.t;++c){var b=a[c]&32767;var d=(b*this.mpl+(((b*this.mph+(a[c]>>15)*this.mpl)&this.um)<<15))&a.DM;b=c+this.m.t;a[b]+=this.m.am(0,d,a,c,0,this.m.t);while(a[b]>=a.DV){a[b]-=a.DV;a[++b]++}}a.clamp();a.drShiftTo(this.m.t,a);if(a.compareTo(this.m)>=0){a.subTo(this.m,a)}}function montSqrTo(a,b){a.squareTo(b);this.reduce(b)}function montMulTo(a,c,b){a.multiplyTo(c,b);this.reduce(b)}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return((this.t>0)?(this[0]&1):this.s)==0}function bnpExp(h,j){if(h>4294967295||h<1){return BigInteger.ONE}var f=nbi(),a=nbi(),d=j.convert(this),c=nbits(h)-1;d.copyTo(f);while(--c>=0){j.sqrTo(f,a);if((h&(1<<c))>0){j.mulTo(a,d,f)}else{var b=f;f=a;a=b}}return j.revert(f)}function bnModPowInt(b,a){var c;if(b<256||a.isEven()){c=new Classic(a)}else{c=new Montgomery(a)}return this.exp(b,c)}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1); /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ function bnClone(){var a=nbi();this.copyTo(a);return a}function bnIntValue(){if(this.s<0){if(this.t==1){return this[0]-this.DV}else{if(this.t==0){return -1}}}else{if(this.t==1){return this[0]}else{if(this.t==0){return 0}}}return((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0]}function bnByteValue(){return(this.t==0)?this.s:(this[0]<<24)>>24}function bnShortValue(){return(this.t==0)?this.s:(this[0]<<16)>>16}function bnpChunkSize(a){return Math.floor(Math.LN2*this.DB/Math.log(a))}function bnSigNum(){if(this.s<0){return -1}else{if(this.t<=0||(this.t==1&&this[0]<=0)){return 0}else{return 1}}}function bnpToRadix(c){if(c==null){c=10}if(this.signum()==0||c<2||c>36){return"0"}var f=this.chunkSize(c);var e=Math.pow(c,f);var i=nbv(e),j=nbi(),h=nbi(),g="";this.divRemTo(i,j,h);while(j.signum()>0){g=(e+h.intValue()).toString(c).substr(1)+g;j.divRemTo(i,j,h)}return h.intValue().toString(c)+g}function bnpFromRadix(m,h){this.fromInt(0);if(h==null){h=10}var f=this.chunkSize(h);var g=Math.pow(h,f),e=false,a=0,l=0;for(var c=0;c<m.length;++c){var k=intAt(m,c);if(k<0){if(m.charAt(c)=="-"&&this.signum()==0){e=true}continue}l=h*l+k;if(++a>=f){this.dMultiply(g);this.dAddOffset(l,0);a=0;l=0}}if(a>0){this.dMultiply(Math.pow(h,a));this.dAddOffset(l,0)}if(e){BigInteger.ZERO.subTo(this,this)}}function bnpFromNumber(f,e,h){if("number"==typeof e){if(f<2){this.fromInt(1)}else{this.fromNumber(f,h);if(!this.testBit(f-1)){this.bitwiseTo(BigInteger.ONE.shiftLeft(f-1),op_or,this)}if(this.isEven()){this.dAddOffset(1,0)}while(!this.isProbablePrime(e)){this.dAddOffset(2,0);if(this.bitLength()>f){this.subTo(BigInteger.ONE.shiftLeft(f-1),this)}}}}else{var d=new Array(),g=f&7;d.length=(f>>3)+1;e.nextBytes(d);if(g>0){d[0]&=((1<<g)-1)}else{d[0]=0}this.fromString(d,256)}}function bnToByteArray(){var b=this.t,c=new Array();c[0]=this.s;var e=this.DB-(b*this.DB)%8,f,a=0;if(b-->0){if(e<this.DB&&(f=this[b]>>e)!=(this.s&this.DM)>>e){c[a++]=f|(this.s<<(this.DB-e))}while(b>=0){if(e<8){f=(this[b]&((1<<e)-1))<<(8-e);f|=this[--b]>>(e+=this.DB-8)}else{f=(this[b]>>(e-=8))&255;if(e<=0){e+=this.DB;--b}}if((f&128)!=0){f|=-256}if(a==0&&(this.s&128)!=(f&128)){++a}if(a>0||f!=this.s){c[a++]=f}}}return c}function bnEquals(b){return(this.compareTo(b)==0)}function bnMin(b){return(this.compareTo(b)<0)?this:b}function bnMax(b){return(this.compareTo(b)>0)?this:b}function bnpBitwiseTo(c,h,e){var d,g,b=Math.min(c.t,this.t);for(d=0;d<b;++d){e[d]=h(this[d],c[d])}if(c.t<this.t){g=c.s&this.DM;for(d=b;d<this.t;++d){e[d]=h(this[d],g)}e.t=this.t}else{g=this.s&this.DM;for(d=b;d<c.t;++d){e[d]=h(g,c[d])}e.t=c.t}e.s=h(this.s,c.s);e.clamp()}function op_and(a,b){return a&b}function bnAnd(b){var c=nbi();this.bitwiseTo(b,op_and,c);return c}function op_or(a,b){return a|b}function bnOr(b){var c=nbi();this.bitwiseTo(b,op_or,c);return c}function op_xor(a,b){return a^b}function bnXor(b){var c=nbi();this.bitwiseTo(b,op_xor,c);return c}function op_andnot(a,b){return a&~b}function bnAndNot(b){var c=nbi();this.bitwiseTo(b,op_andnot,c);return c}function bnNot(){var b=nbi();for(var a=0;a<this.t;++a){b[a]=this.DM&~this[a]}b.t=this.t;b.s=~this.s;return b}function bnShiftLeft(b){var a=nbi();if(b<0){this.rShiftTo(-b,a)}else{this.lShiftTo(b,a)}return a}function bnShiftRight(b){var a=nbi();if(b<0){this.lShiftTo(-b,a)}else{this.rShiftTo(b,a)}return a}function lbit(a){if(a==0){return -1}var b=0;if((a&65535)==0){a>>=16;b+=16}if((a&255)==0){a>>=8;b+=8}if((a&15)==0){a>>=4;b+=4}if((a&3)==0){a>>=2;b+=2}if((a&1)==0){++b}return b}function bnGetLowestSetBit(){for(var a=0;a<this.t;++a){if(this[a]!=0){return a*this.DB+lbit(this[a])}}if(this.s<0){return this.t*this.DB}return -1}function cbit(a){var b=0;while(a!=0){a&=a-1;++b}return b}function bnBitCount(){var c=0,a=this.s&this.DM;for(var b=0;b<this.t;++b){c+=cbit(this[b]^a)}return c}function bnTestBit(b){var a=Math.floor(b/this.DB);if(a>=this.t){return(this.s!=0)}return((this[a]&(1<<(b%this.DB)))!=0)}function bnpChangeBit(c,b){var a=BigInteger.ONE.shiftLeft(c);this.bitwiseTo(a,b,a);return a}function bnSetBit(a){return this.changeBit(a,op_or)}function bnClearBit(a){return this.changeBit(a,op_andnot)}function bnFlipBit(a){return this.changeBit(a,op_xor)}function bnpAddTo(d,f){var e=0,g=0,b=Math.min(d.t,this.t);while(e<b){g+=this[e]+d[e];f[e++]=g&this.DM;g>>=this.DB}if(d.t<this.t){g+=d.s;while(e<this.t){g+=this[e];f[e++]=g&this.DM;g>>=this.DB}g+=this.s}else{g+=this.s;while(e<d.t){g+=d[e];f[e++]=g&this.DM;g>>=this.DB}g+=d.s}f.s=(g<0)?-1:0;if(g>0){f[e++]=g}else{if(g<-1){f[e++]=this.DV+g}}f.t=e;f.clamp()}function bnAdd(b){var c=nbi();this.addTo(b,c);return c}function bnSubtract(b){var c=nbi();this.subTo(b,c);return c}function bnMultiply(b){var c=nbi();this.multiplyTo(b,c);return c}function bnSquare(){var a=nbi();this.squareTo(a);return a}function bnDivide(b){var c=nbi();this.divRemTo(b,c,null);return c}function bnRemainder(b){var c=nbi();this.divRemTo(b,null,c);return c}function bnDivideAndRemainder(b){var d=nbi(),c=nbi();this.divRemTo(b,d,c);return new Array(d,c)}function bnpDMultiply(a){this[this.t]=this.am(0,a-1,this,0,0,this.t);++this.t;this.clamp()}function bnpDAddOffset(b,a){if(b==0){return}while(this.t<=a){this[this.t++]=0}this[a]+=b;while(this[a]>=this.DV){this[a]-=this.DV;if(++a>=this.t){this[this.t++]=0}++this[a]}}function NullExp(){}function nNop(a){return a}function nMulTo(a,c,b){a.multiplyTo(c,b)}function nSqrTo(a,b){a.squareTo(b)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(a){return this.exp(a,new NullExp())}function bnpMultiplyLowerTo(b,f,e){var d=Math.min(this.t+b.t,f);e.s=0;e.t=d;while(d>0){e[--d]=0}var c;for(c=e.t-this.t;d<c;++d){e[d+this.t]=this.am(0,b[d],e,d,0,this.t)}for(c=Math.min(b.t,f);d<c;++d){this.am(0,b[d],e,d,0,f-d)}e.clamp()}function bnpMultiplyUpperTo(b,e,d){--e;var c=d.t=this.t+b.t-e;d.s=0;while(--c>=0){d[c]=0}for(c=Math.max(e-this.t,0);c<b.t;++c){d[this.t+c-e]=this.am(e-c,b[c],d,0,0,this.t+c-e)}d.clamp();d.drShiftTo(1,d)}function Barrett(a){this.r2=nbi();this.q3=nbi();BigInteger.ONE.dlShiftTo(2*a.t,this.r2);this.mu=this.r2.divide(a);this.m=a}function barrettConvert(a){if(a.s<0||a.t>2*this.m.t){return a.mod(this.m)}else{if(a.compareTo(this.m)<0){return a}else{var b=nbi();a.copyTo(b);this.reduce(b);return b}}}function barrettRevert(a){return a}function barrettReduce(a){a.drShiftTo(this.m.t-1,this.r2);if(a.t>this.m.t+1){a.t=this.m.t+1;a.clamp()}this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(a.compareTo(this.r2)<0){a.dAddOffset(1,this.m.t+1)}a.subTo(this.r2,a);while(a.compareTo(this.m)>=0){a.subTo(this.m,a)}}function barrettSqrTo(a,b){a.squareTo(b);this.reduce(b)}function barrettMulTo(a,c,b){a.multiplyTo(c,b);this.reduce(b)}Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(q,f){var o=q.bitLength(),h,b=nbv(1),v;if(o<=0){return b}else{if(o<18){h=1}else{if(o<48){h=3}else{if(o<144){h=4}else{if(o<768){h=5}else{h=6}}}}}if(o<8){v=new Classic(f)}else{if(f.isEven()){v=new Barrett(f)}else{v=new Montgomery(f)}}var p=new Array(),d=3,s=h-1,a=(1<<h)-1;p[1]=v.convert(this);if(h>1){var A=nbi();v.sqrTo(p[1],A);while(d<=a){p[d]=nbi();v.mulTo(A,p[d-2],p[d]);d+=2}}var l=q.t-1,x,u=true,c=nbi(),y;o=nbits(q[l])-1;while(l>=0){if(o>=s){x=(q[l]>>(o-s))&a}else{x=(q[l]&((1<<(o+1))-1))<<(s-o);if(l>0){x|=q[l-1]>>(this.DB+o-s)}}d=h;while((x&1)==0){x>>=1;--d}if((o-=d)<0){o+=this.DB;--l}if(u){p[x].copyTo(b);u=false}else{while(d>1){v.sqrTo(b,c);v.sqrTo(c,b);d-=2}if(d>0){v.sqrTo(b,c)}else{y=b;b=c;c=y}v.mulTo(c,p[x],b)}while(l>=0&&(q[l]&(1<<o))==0){v.sqrTo(b,c);y=b;b=c;c=y;if(--o<0){o=this.DB-1;--l}}}return v.revert(b)}function bnGCD(c){var b=(this.s<0)?this.negate():this.clone();var h=(c.s<0)?c.negate():c.clone();if(b.compareTo(h)<0){var e=b;b=h;h=e}var d=b.getLowestSetBit(),f=h.getLowestSetBit();if(f<0){return b}if(d<f){f=d}if(f>0){b.rShiftTo(f,b);h.rShiftTo(f,h)}while(b.signum()>0){if((d=b.getLowestSetBit())>0){b.rShiftTo(d,b)}if((d=h.getLowestSetBit())>0){h.rShiftTo(d,h)}if(b.compareTo(h)>=0){b.subTo(h,b);b.rShiftTo(1,b)}else{h.subTo(b,h);h.rShiftTo(1,h)}}if(f>0){h.lShiftTo(f,h)}return h}function bnpModInt(e){if(e<=0){return 0}var c=this.DV%e,b=(this.s<0)?e-1:0;if(this.t>0){if(c==0){b=this[0]%e}else{for(var a=this.t-1;a>=0;--a){b=(c*b+this[a])%e}}}return b}function bnModInverse(f){var j=f.isEven();if((this.isEven()&&j)||f.signum()==0){return BigInteger.ZERO}var i=f.clone(),h=this.clone();var g=nbv(1),e=nbv(0),l=nbv(0),k=nbv(1);while(i.signum()!=0){while(i.isEven()){i.rShiftTo(1,i);if(j){if(!g.isEven()||!e.isEven()){g.addTo(this,g);e.subTo(f,e)}g.rShiftTo(1,g)}else{if(!e.isEven()){e.subTo(f,e)}}e.rShiftTo(1,e)}while(h.isEven()){h.rShiftTo(1,h);if(j){if(!l.isEven()||!k.isEven()){l.addTo(this,l);k.subTo(f,k)}l.rShiftTo(1,l)}else{if(!k.isEven()){k.subTo(f,k)}}k.rShiftTo(1,k)}if(i.compareTo(h)>=0){i.subTo(h,i);if(j){g.subTo(l,g)}e.subTo(k,e)}else{h.subTo(i,h);if(j){l.subTo(g,l)}k.subTo(e,k)}}if(h.compareTo(BigInteger.ONE)!=0){return BigInteger.ZERO}if(k.compareTo(f)>=0){return k.subtract(f)}if(k.signum()<0){k.addTo(f,k)}else{return k}if(k.signum()<0){return k.add(f)}else{return k}}var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];var lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(e){var d,b=this.abs();if(b.t==1&&b[0]<=lowprimes[lowprimes.length-1]){for(d=0;d<lowprimes.length;++d){if(b[0]==lowprimes[d]){return true}}return false}if(b.isEven()){return false}d=1;while(d<lowprimes.length){var a=lowprimes[d],c=d+1;while(c<lowprimes.length&&a<lplim){a*=lowprimes[c++]}a=b.modInt(a);while(d<c){if(a%lowprimes[d++]==0){return false}}}return b.millerRabin(e)}function bnpMillerRabin(f){var g=this.subtract(BigInteger.ONE);var c=g.getLowestSetBit();if(c<=0){return false}var h=g.shiftRight(c);f=(f+1)>>1;if(f>lowprimes.length){f=lowprimes.length}var b=nbi();for(var e=0;e<f;++e){b.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);var l=b.modPow(h,this);if(l.compareTo(BigInteger.ONE)!=0&&l.compareTo(g)!=0){var d=1;while(d++<c&&l.compareTo(g)!=0){l=l.modPowInt(2,this);if(l.compareTo(BigInteger.ONE)==0){return false}}if(l.compareTo(g)!=0){return false}}}return true}BigInteger.prototype.chunkSize=bnpChunkSize;BigInteger.prototype.toRadix=bnpToRadix;BigInteger.prototype.fromRadix=bnpFromRadix;BigInteger.prototype.fromNumber=bnpFromNumber;BigInteger.prototype.bitwiseTo=bnpBitwiseTo;BigInteger.prototype.changeBit=bnpChangeBit;BigInteger.prototype.addTo=bnpAddTo;BigInteger.prototype.dMultiply=bnpDMultiply;BigInteger.prototype.dAddOffset=bnpDAddOffset;BigInteger.prototype.multiplyLowerTo=bnpMultiplyLowerTo;BigInteger.prototype.multiplyUpperTo=bnpMultiplyUpperTo;BigInteger.prototype.modInt=bnpModInt;BigInteger.prototype.millerRabin=bnpMillerRabin;BigInteger.prototype.clone=bnClone;BigInteger.prototype.intValue=bnIntValue;BigInteger.prototype.byteValue=bnByteValue;BigInteger.prototype.shortValue=bnShortValue;BigInteger.prototype.signum=bnSigNum;BigInteger.prototype.toByteArray=bnToByteArray;BigInteger.prototype.equals=bnEquals;BigInteger.prototype.min=bnMin;BigInteger.prototype.max=bnMax;BigInteger.prototype.and=bnAnd;BigInteger.prototype.or=bnOr;BigInteger.prototype.xor=bnXor;BigInteger.prototype.andNot=bnAndNot;BigInteger.prototype.not=bnNot;BigInteger.prototype.shiftLeft=bnShiftLeft;BigInteger.prototype.shiftRight=bnShiftRight;BigInteger.prototype.getLowestSetBit=bnGetLowestSetBit;BigInteger.prototype.bitCount=bnBitCount;BigInteger.prototype.testBit=bnTestBit;BigInteger.prototype.setBit=bnSetBit;BigInteger.prototype.clearBit=bnClearBit;BigInteger.prototype.flipBit=bnFlipBit;BigInteger.prototype.add=bnAdd;BigInteger.prototype.subtract=bnSubtract;BigInteger.prototype.multiply=bnMultiply;BigInteger.prototype.divide=bnDivide;BigInteger.prototype.remainder=bnRemainder;BigInteger.prototype.divideAndRemainder=bnDivideAndRemainder;BigInteger.prototype.modPow=bnModPow;BigInteger.prototype.modInverse=bnModInverse;BigInteger.prototype.pow=bnPow;BigInteger.prototype.gcd=bnGCD;BigInteger.prototype.isProbablePrime=bnIsProbablePrime;BigInteger.prototype.square=bnSquare; /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ function Arcfour(){this.i=0;this.j=0;this.S=new Array()}function ARC4init(d){var c,a,b;for(c=0;c<256;++c){this.S[c]=c}a=0;for(c=0;c<256;++c){a=(a+this.S[c]+d[c%d.length])&255;b=this.S[c];this.S[c]=this.S[a];this.S[a]=b}this.i=0;this.j=0}function ARC4next(){var a;this.i=(this.i+1)&255;this.j=(this.j+this.S[this.i])&255;a=this.S[this.i];this.S[this.i]=this.S[this.j];this.S[this.j]=a;return this.S[(a+this.S[this.i])&255]}Arcfour.prototype.init=ARC4init;Arcfour.prototype.next=ARC4next;function prng_newstate(){return new Arcfour()}var rng_psize=256; /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ var rng_state;var rng_pool;var rng_pptr;function rng_seed_int(a){rng_pool[rng_pptr++]^=a&255;rng_pool[rng_pptr++]^=(a>>8)&255;rng_pool[rng_pptr++]^=(a>>16)&255;rng_pool[rng_pptr++]^=(a>>24)&255;if(rng_pptr>=rng_psize){rng_pptr-=rng_psize}}function rng_seed_time(){rng_seed_int(new Date().getTime())}if(rng_pool==null){rng_pool=new Array();rng_pptr=0;var t;if(window!==undefined&&(window.crypto!==undefined||window.msCrypto!==undefined)){var crypto=window.crypto||window.msCrypto;if(crypto.getRandomValues){var ua=new Uint8Array(32);crypto.getRandomValues(ua);for(t=0;t<32;++t){rng_pool[rng_pptr++]=ua[t]}}else{if(navigator.appName=="Netscape"&&navigator.appVersion<"5"){var z=window.crypto.random(32);for(t=0;t<z.length;++t){rng_pool[rng_pptr++]=z.charCodeAt(t)&255}}}}while(rng_pptr<rng_psize){t=Math.floor(65536*Math.random());rng_pool[rng_pptr++]=t>>>8;rng_pool[rng_pptr++]=t&255}rng_pptr=0;rng_seed_time()}function rng_get_byte(){if(rng_state==null){rng_seed_time();rng_state=prng_newstate();rng_state.init(rng_pool);for(rng_pptr=0;rng_pptr<rng_pool.length;++rng_pptr){rng_pool[rng_pptr]=0}rng_pptr=0}return rng_state.next()}function rng_get_bytes(b){var a;for(a=0;a<b.length;++a){b[a]=rng_get_byte()}}function SecureRandom(){}SecureRandom.prototype.nextBytes=rng_get_bytes; /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ function parseBigInt(b,a){return new BigInteger(b,a)}function linebrk(c,d){var a="";var b=0;while(b+d<c.length){a+=c.substring(b,b+d)+"\n";b+=d}return a+c.substring(b,c.length)}function byte2Hex(a){if(a<16){return"0"+a.toString(16)}else{return a.toString(16)}}function pkcs1pad2(e,h){if(h<e.length+11){throw"Message too long for RSA";return null}var g=new Array();var d=e.length-1;while(d>=0&&h>0){var f=e.charCodeAt(d--);if(f<128){g[--h]=f}else{if((f>127)&&(f<2048)){g[--h]=(f&63)|128;g[--h]=(f>>6)|192}else{g[--h]=(f&63)|128;g[--h]=((f>>6)&63)|128;g[--h]=(f>>12)|224}}}g[--h]=0;var b=new SecureRandom();var a=new Array();while(h>2){a[0]=0;while(a[0]==0){b.nextBytes(a)}g[--h]=a[0]}g[--h]=2;g[--h]=0;return new BigInteger(g)}function oaep_mgf1_arr(c,a,e){var b="",d=0;while(b.length<a){b+=e(String.fromCharCode.apply(String,c.concat([(d&4278190080)>>24,(d&16711680)>>16,(d&65280)>>8,d&255])));d+=1}return b}function oaep_pad(q,a,f,l){var c=KJUR.crypto.MessageDigest;var o=KJUR.crypto.Util;var b=null;if(!f){f="sha1"}if(typeof f==="string"){b=c.getCanonicalAlgName(f);l=c.getHashLength(b);f=function(i){return hextorstr(o.hashHex(rstrtohex(i),b))}}if(q.length+2*l+2>a){throw"Message too long for RSA"}var k="",e;for(e=0;e<a-q.length-2*l-2;e+=1){k+="\x00"}var h=f("")+k+"\x01"+q;var g=new Array(l);new SecureRandom().nextBytes(g);var j=oaep_mgf1_arr(g,h.length,f);var p=[];for(e=0;e<h.length;e+=1){p[e]=h.charCodeAt(e)^j.charCodeAt(e)}var m=oaep_mgf1_arr(p,g.length,f);var d=[0];for(e=0;e<g.length;e+=1){d[e+1]=g[e]^m.charCodeAt(e)}return new BigInteger(d.concat(p))}function RSAKey(){this.n=null;this.e=0;this.d=null;this.p=null;this.q=null;this.dmp1=null;this.dmq1=null;this.coeff=null}function RSASetPublic(b,a){this.isPublic=true;this.isPrivate=false;if(typeof b!=="string"){this.n=b;this.e=a}else{if(b!=null&&a!=null&&b.length>0&&a.length>0){this.n=parseBigInt(b,16);this.e=parseInt(a,16)}else{throw"Invalid RSA public key"}}}function RSADoPublic(a){return a.modPowInt(this.e,this.n)}function RSAEncrypt(d){var a=pkcs1pad2(d,(this.n.bitLength()+7)>>3);if(a==null){return null}var e=this.doPublic(a);if(e==null){return null}var b=e.toString(16);if((b.length&1)==0){return b}else{return"0"+b}}function RSAEncryptOAEP(f,e,b){var a=oaep_pad(f,(this.n.bitLength()+7)>>3,e,b);if(a==null){return null}var g=this.doPublic(a);if(g==null){return null}var d=g.toString(16);if((d.length&1)==0){return d}else{return"0"+d}}RSAKey.prototype.doPublic=RSADoPublic;RSAKey.prototype.setPublic=RSASetPublic;RSAKey.prototype.encrypt=RSAEncrypt;RSAKey.prototype.encryptOAEP=RSAEncryptOAEP;RSAKey.prototype.type="RSA"; /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ function pkcs1unpad2(g,j){var a=g.toByteArray();var f=0;while(f<a.length&&a[f]==0){++f}if(a.length-f!=j-1||a[f]!=2){return null}++f;while(a[f]!=0){if(++f>=a.length){return null}}var e="";while(++f<a.length){var h=a[f]&255;if(h<128){e+=String.fromCharCode(h)}else{if((h>191)&&(h<224)){e+=String.fromCharCode(((h&31)<<6)|(a[f+1]&63));++f}else{e+=String.fromCharCode(((h&15)<<12)|((a[f+1]&63)<<6)|(a[f+2]&63));f+=2}}}return e}function oaep_mgf1_str(c,a,e){var b="",d=0;while(b.length<a){b+=e(c+String.fromCharCode.apply(String,[(d&4278190080)>>24,(d&16711680)>>16,(d&65280)>>8,d&255]));d+=1}return b}function oaep_unpad(o,b,g,p){var e=KJUR.crypto.MessageDigest;var r=KJUR.crypto.Util;var c=null;if(!g){g="sha1"}if(typeof g==="string"){c=e.getCanonicalAlgName(g);p=e.getHashLength(c);g=function(d){return hextorstr(r.hashHex(rstrtohex(d),c))}}o=o.toByteArray();var h;for(h=0;h<o.length;h+=1){o[h]&=255}while(o.length<b){o.unshift(0)}o=String.fromCharCode.apply(String,o);if(o.length<2*p+2){throw"Cipher too short"}var f=o.substr(1,p);var s=o.substr(p+1);var q=oaep_mgf1_str(s,p,g);var k=[],h;for(h=0;h<f.length;h+=1){k[h]=f.charCodeAt(h)^q.charCodeAt(h)}var l=oaep_mgf1_str(String.fromCharCode.apply(String,k),o.length-p,g);var j=[];for(h=0;h<s.length;h+=1){j[h]=s.charCodeAt(h)^l.charCodeAt(h)}j=String.fromCharCode.apply(String,j);if(j.substr(0,p)!==g("")){throw"Hash mismatch"}j=j.substr(p);var a=j.indexOf("\x01");var m=(a!=-1)?j.substr(0,a).lastIndexOf("\x00"):-1;if(m+1!=a){throw"Malformed data"}return j.substr(a+1)}function RSASetPrivate(c,a,b){this.isPrivate=true;if(typeof c!=="string"){this.n=c;this.e=a;this.d=b}else{if(c!=null&&a!=null&&c.length>0&&a.length>0){this.n=parseBigInt(c,16);this.e=parseInt(a,16);this.d=parseBigInt(b,16)}else{throw"Invalid RSA private key"}}}function RSASetPrivateEx(g,d,e,c,b,a,h,f){this.isPrivate=true;this.isPublic=false;if(g==null){throw"RSASetPrivateEx N == null"}if(d==null){throw"RSASetPrivateEx E == null"}if(g.length==0){throw"RSASetPrivateEx N.length == 0"}if(d.length==0){throw"RSASetPrivateEx E.length == 0"}if(g!=null&&d!=null&&g.length>0&&d.length>0){this.n=parseBigInt(g,16);this.e=parseInt(d,16);this.d=parseBigInt(e,16);this.p=parseBigInt(c,16);this.q=parseBigInt(b,16);this.dmp1=parseBigInt(a,16);this.dmq1=parseBigInt(h,16);this.coeff=parseBigInt(f,16)}else{throw"Invalid RSA private key in RSASetPrivateEx"}}function RSAGenerate(b,i){var a=new SecureRandom();var f=b>>1;this.e=parseInt(i,16);var c=new BigInteger(i,16);for(;;){for(;;){this.p=new BigInteger(b-f,1,a);if(this.p.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE)==0&&this.p.isProbablePrime(10)){break}}for(;;){this.q=new BigInteger(f,1,a);if(this.q.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE)==0&&this.q.isProbablePrime(10)){break}}if(this.p.compareTo(this.q)<=0){var h=this.p;this.p=this.q;this.q=h}var g=this.p.subtract(BigInteger.ONE);var d=this.q.subtract(BigInteger.ONE);var e=g.multiply(d);if(e.gcd(c).compareTo(BigInteger.ONE)==0){this.n=this.p.multiply(this.q);if(this.n.bitLength()==b){this.d=c.modInverse(e);this.dmp1=this.d.mod(g);this.dmq1=this.d.mod(d);this.coeff=this.q.modInverse(this.p);break}}}this.isPrivate=true}function RSADoPrivate(a){if(this.p==null||this.q==null){return a.modPow(this.d,this.n)}var c=a.mod(this.p).modPow(this.dmp1,this.p);var b=a.mod(this.q).modPow(this.dmq1,this.q);while(c.compareTo(b)<0){c=c.add(this.p)}return c.subtract(b).multiply(this.coeff).mod(this.p).multiply(this.q).add(b)}function RSADecrypt(b){if(b.length!=Math.ceil(this.n.bitLength()/4)){throw new Error("wrong ctext length")}var d=parseBigInt(b,16);var a=this.doPrivate(d);if(a==null){return null}return pkcs1unpad2(a,(this.n.bitLength()+7)>>3)}function RSADecryptOAEP(e,d,b){if(e.length!=Math.ceil(this.n.bitLength()/4)){throw new Error("wrong ctext length")}var f=parseBigInt(e,16);var a=this.doPrivate(f);if(a==null){return null}return oaep_unpad(a,(this.n.bitLength()+7)>>3,d,b)}RSAKey.prototype.doPrivate=RSADoPrivate;RSAKey.prototype.setPrivate=RSASetPrivate;RSAKey.prototype.setPrivateEx=RSASetPrivateEx;RSAKey.prototype.generate=RSAGenerate;RSAKey.prototype.decrypt=RSADecrypt;RSAKey.prototype.decryptOAEP=RSADecryptOAEP; /*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ function ECFieldElementFp(b,a){this.x=a;this.q=b}function feFpEquals(a){if(a==this){return true}return(this.q.equals(a.q)&&this.x.equals(a.x))}function feFpToBigInteger(){return this.x}function feFpNegate(){return new ECFieldElementFp(this.q,this.x.negate().mod(this.q))}function feFpAdd(a){return new ECFieldElementFp(this.q,this.x.add(a.toBigInteger()).mod(this.q))}function feFpSubtract(a){return new ECFieldElementFp(this.q,this.x.subtract(a.toBigInteger()).mod(this.q))}function feFpMultiply(a){return new ECFieldElementFp(this.q,this.x.multiply(a.toBigInteger()).mod(this.q))}function feFpSquare(){return new ECFieldElementFp(this.q,this.x.square().mod(this.q))}function feFpDivide(a){return new ECFieldElementFp(this.q,this.x.multiply(a.toBigInteger().modInverse(this.q)).mod(this.q))}ECFieldElementFp.prototype.equals=feFpEquals;ECFieldElementFp.prototype.toBigInteger=feFpToBigInteger;ECFieldElementFp.prototype.negate=feFpNegate;ECFieldElementFp.prototype.add=feFpAdd;ECFieldElementFp.prototype.subtract=feFpSubtract;ECFieldElementFp.prototype.multiply=feFpMultiply;ECFieldElementFp.prototype.square=feFpSquare;ECFieldElementFp.prototype.divide=feFpDivide;function ECPointFp(c,a,d,b){this.curve=c;this.x=a;this.y=d;if(b==null){this.z=BigInteger.ONE}else{this.z=b}this.zinv=null}function pointFpGetX(){if(this.zinv==null){this.zinv=this.z.modInverse(this.curve.q)}return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpGetY(){if(this.zinv==null){this.zinv=this.z.modInverse(this.curve.q)}return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpEquals(a){if(a==this){return true}if(this.isInfinity()){return a.isInfinity()}if(a.isInfinity()){return this.isInfinity()}var c,b;c=a.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(a.z)).mod(this.curve.q);if(!c.equals(BigInteger.ZERO)){return false}b=a.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(a.z)).mod(this.curve.q);return b.equals(BigInteger.ZERO)}function pointFpIsInfinity(){if((this.x==null)&&(this.y==null)){return true}return this.z.equals(BigInteger.ZERO)&&!this.y.toBigInteger().equals(BigInteger.ZERO)}function pointFpNegate(){return new ECPointFp(this.curve,this.x,this.y.negate(),this.z)}function pointFpAdd(l){if(this.isInfinity()){return l}if(l.isInfinity()){return this}var p=l.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(l.z)).mod(this.curve.q);var o=l.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(l.z)).mod(this.curve.q);if(BigInteger.ZERO.equals(o)){if(BigInteger.ZERO.equals(p)){return this.twice()}return this.curve.getInfinity()}var j=new BigInteger("3");var e=this.x.toBigInteger();var n=this.y.toBigInteger();var c=l.x.toBigInteger();var k=l.y.toBigInteger();var m=o.square();var i=m.multiply(o);var d=e.multiply(m);var g=p.square().multiply(this.z);var a=g.subtract(d.shiftLeft(1)).multiply(l.z).subtract(i).multiply(o).mod(this.curve.q);var h=d.multiply(j).multiply(p).subtract(n.multiply(i)).subtract(g.multiply(p)).multiply(l.z).add(p.multiply(i)).mod(this.curve.q);var f=i.multiply(this.z).multiply(l.z).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(h),f)}function pointFpTwice(){if(this.isInfinity()){return this}if(this.y.toBigInteger().signum()==0){return this.curve.getInfinity()}var g=new BigInteger("3");var c=this.x.toBigInteger();var h=this.y.toBigInteger();var e=h.multiply(this.z);var j=e.multiply(h).mod(this.curve.q);var i=this.curve.a.toBigInteger();var k=c.square().multiply(g);if(!BigInteger.ZERO.equals(i)){k=k.add(this.z.square().multiply(i))}k=k.mod(this.curve.q);var b=k.square().subtract(c.shiftLeft(3).multiply(j)).shiftLeft(1).multiply(e).mod(this.curve.q);var f=k.multiply(g).multiply(c).subtract(j.shiftLeft(1)).shiftLeft(2).multiply(j).subtract(k.square().multiply(k)).mod(this.curve.q);var d=e.square().multiply(e).shiftLeft(3).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(b),this.curve.fromBigInteger(f),d)}function pointFpMultiply(d){if(this.isInfinity()){return this}if(d.signum()==0){return this.curve.getInfinity()}var m=d;var l=m.multiply(new BigInteger("3"));var b=this.negate();var j=this;var q=this.curve.q.subtract(d);var o=q.multiply(new BigInteger("3"));var c=new ECPointFp(this.curve,this.x,this.y);var a=c.negate();var g;for(g=l.bitLength()-2;g>0;--g){j=j.twice();var n=l.testBit(g);var f=m.testBit(g);if(n!=f){j=j.add(n?this:b)}}for(g=o.bitLength()-2;g>0;--g){c=c.twice();var p=o.testBit(g);var r=q.testBit(g);if(p!=r){c=c.add(p?c:a)}}return j}function pointFpMultiplyTwo(c,a,b){var d;if(c.bitLength()>b.bitLength()){d=c.bitLength()-1}else{d=b.bitLength()-1}var f=this.curve.getInfinity();var e=this.add(a);while(d>=0){f=f.twice();if(c.testBit(d)){if(b.testBit(d)){f=f.add(e)}else{f=f.add(this)}}else{if(b.testBit(d)){f=f.add(a)}}--d}return f}ECPointFp.prototype.getX=pointFpGetX;ECPointFp.prototype.getY=pointFpGetY;ECPointFp.prototype.equals=pointFpEquals;ECPointFp.prototype.isInfinity=pointFpIsInfinity;ECPointFp.prototype.negate=pointFpNegate;ECPointFp.prototype.add=pointFpAdd;ECPointFp.prototype.twice=pointFpTwice;ECPointFp.prototype.multiply=pointFpMultiply;ECPointFp.prototype.multiplyTwo=pointFpMultiplyTwo;function ECCurveFp(e,d,c){this.q=e;this.a=this.fromBigInteger(d);this.b=this.fromBigInteger(c);this.infinity=new ECPointFp(this,null,null)}function curveFpGetQ(){return this.q}function curveFpGetA(){return this.a}function curveFpGetB(){return this.b}function curveFpEquals(a){if(a==this){return true}return(this.q.equals(a.q)&&this.a.equals(a.a)&&this.b.equals(a.b))}function curveFpGetInfinity(){return this.infinity}function curveFpFromBigInteger(a){return new ECFieldElementFp(this.q,a)}function curveFpDecodePointHex(d){switch(parseInt(d.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:return null;case 4:case 6:case 7:var a=(d.length-2)/2;var c=d.substr(2,a);var b=d.substr(a+2,a);return new ECPointFp(this,this.fromBigInteger(new BigInteger(c,16)),this.fromBigInteger(new BigInteger(b,16)));default:return null}}ECCurveFp.prototype.getQ=curveFpGetQ;ECCurveFp.prototype.getA=curveFpGetA;ECCurveFp.prototype.getB=curveFpGetB;ECCurveFp.prototype.equals=curveFpEquals;ECCurveFp.prototype.getInfinity=curveFpGetInfinity;ECCurveFp.prototype.fromBigInteger=curveFpFromBigInteger;ECCurveFp.prototype.decodePointHex=curveFpDecodePointHex; /*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib */ ECFieldElementFp.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)};ECPointFp.prototype.getEncoded=function(c){var d=function(h,f){var g=h.toByteArrayUnsigned();if(f<g.length){g=g.slice(g.length-f)}else{while(f>g.length){g.unshift(0)}}return g};var a=this.getX().toBigInteger();var e=this.getY().toBigInteger();var b=d(a,32);if(c){if(e.isEven()){b.unshift(2)}else{b.unshift(3)}}else{b.unshift(4);b=b.concat(d(e,32))}return b};ECPointFp.decodeFrom=function(g,c){var f=c[0];var e=c.length-1;var d=c.slice(1,1+e/2);var b=c.slice(1+e/2,1+e);d.unshift(0);b.unshift(0);var a=new BigInteger(d);var h=new BigInteger(b);return new ECPointFp(g,g.fromBigInteger(a),g.fromBigInteger(h))};ECPointFp.decodeFromHex=function(g,c){var f=c.substr(0,2);var e=c.length-2;var d=c.substr(2,e/2);var b=c.substr(2+e/2,e/2);var a=new BigInteger(d,16);var h=new BigInteger(b,16);return new ECPointFp(g,g.fromBigInteger(a),g.fromBigInteger(h))};ECPointFp.prototype.add2D=function(c){if(this.isInfinity()){return c}if(c.isInfinity()){return this}if(this.x.equals(c.x)){if(this.y.equals(c.y)){return this.twice()}return this.curve.getInfinity()}var g=c.x.subtract(this.x);var e=c.y.subtract(this.y);var a=e.divide(g);var d=a.square().subtract(this.x).subtract(c.x);var f=a.multiply(this.x.subtract(d)).subtract(this.y);return new ECPointFp(this.curve,d,f)};ECPointFp.prototype.twice2D=function(){if(this.isInfinity()){return this}if(this.y.toBigInteger().signum()==0){return this.curve.getInfinity()}var b=this.curve.fromBigInteger(BigInteger.valueOf(2));var e=this.curve.fromBigInteger(BigInteger.valueOf(3));var a=this.x.square().multiply(e).add(this.curve.a).divide(this.y.multiply(b));var c=a.square().subtract(this.x.multiply(b));var d=a.multiply(this.x.subtract(c)).subtract(this.y);return new ECPointFp(this.curve,c,d)};ECPointFp.prototype.multiply2D=function(b){if(this.isInfinity()){return this}if(b.signum()==0){return this.curve.getInfinity()}var g=b;var f=g.multiply(new BigInteger("3"));var l=this.negate();var d=this;var c;for(c=f.bitLength()-2;c>0;--c){d=d.twice();var a=f.testBit(c);var j=g.testBit(c);if(a!=j){d=d.add2D(a?this:l)}}return d};ECPointFp.prototype.isOnCurve=function(){var d=this.getX().toBigInteger();var i=this.getY().toBigInteger();var f=this.curve.getA().toBigInteger();var c=this.curve.getB().toBigInteger();var h=this.curve.getQ();var e=i.multiply(i).mod(h);var g=d.multiply(d).multiply(d).add(f.multiply(d)).add(c).mod(h);return e.equals(g)};ECPointFp.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"};ECPointFp.prototype.validate=function(){var c=this.curve.getQ();if(this.isInfinity()){throw new Error("Point is at infinity.")}var a=this.getX().toBigInteger();var b=this.getY().toBigInteger();if(a.compareTo(BigInteger.ONE)<0||a.compareTo(c.subtract(BigInteger.ONE))>0){throw new Error("x coordinate out of bounds")}if(b.compareTo(BigInteger.ONE)<0||b.compareTo(c.subtract(BigInteger.ONE))>0){throw new Error("y coordinate out of bounds")}if(!this.isOnCurve()){throw new Error("Point is not on the curve.")}if(this.multiply(c).isInfinity()){throw new Error("Point is not a scalar multiple of G.")}return true}; /*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval */ var jsonParse=(function(){var e="(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)";var j='(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';var i='(?:"'+j+'*")';var d=new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|"+e+"|"+i+")","g");var k=new RegExp("\\\\(?:([^u])|u(.{4}))","g");var g={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function h(l,m,n){return m?g[m]:String.fromCharCode(parseInt(n,16))}var c=new String("");var a="\\";var f={"{":Object,"[":Array};var b=Object.hasOwnProperty;return function(u,q){var p=u.match(d);var x;var v=p[0];var l=false;if("{"===v){x={}}else{if("["===v){x=[]}else{x=[];l=true}}var t;var r=[x];for(var o=1-l,m=p.length;o<m;++o){v=p[o];var w;switch(v.charCodeAt(0)){default:w=r[0];w[t||w.length]=+(v);t=void 0;break;case 34:v=v.substring(1,v.length-1);if(v.indexOf(a)!==-1){v=v.replace(k,h)}w=r[0];if(!t){if(w instanceof Array){t=w.length}else{t=v||c;break}}w[t]=v;t=void 0;break;case 91:w=r[0];r.unshift(w[t||w.length]=[]);t=void 0;break;case 93:r.shift();break;case 102:w=r[0];w[t||w.length]=false;t=void 0;break;case 110:w=r[0];w[t||w.length]=null;t=void 0;break;case 116:w=r[0];w[t||w.length]=true;t=void 0;break;case 123:w=r[0];r.unshift(w[t||w.length]={});t=void 0;break;case 125:r.shift();break}}if(l){if(r.length!==1){throw new Error()}x=x[0]}else{if(r.length){throw new Error()}}if(q){var s=function(C,B){var D=C[B];if(D&&typeof D==="object"){var n=null;for(var z in D){if(b.call(D,z)&&D!==C){var y=s(D,z);if(y!==void 0){D[z]=y}else{if(!n){n=[]}n.push(z)}}}if(n){for(var A=n.length;--A>=0;){delete D[n[A]]}}}return q.call(C,B,D)};x=s({"":x},"")}return x}})(); if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(a){var b=a.toString(16);if((b.length%2)==1){b="0"+b}return b};this.bigIntToMinTwosComplementsHex=function(j){var f=j.toString(16);if(f.substr(0,1)!="-"){if(f.length%2==1){f="0"+f}else{if(!f.match(/^[0-7]/)){f="00"+f}}}else{var a=f.substr(1);var e=a.length;if(e%2==1){e+=1}else{if(!f.match(/^[0-7]/)){e+=2}}var g="";for(var d=0;d<e;d++){g+="f"}var c=new BigInteger(g,16);var b=c.xor(j).add(BigInteger.ONE);f=b.toString(16).replace(/^-/,"")}return f};this.getPEMStringFromHex=function(a,b){return hextopem(a,b)};this.newObject=function(k){var D=KJUR,n=D.asn1,z=n.DERBoolean,e=n.DERInteger,s=n.DERBitString,h=n.DEROctetString,v=n.DERNull,w=n.DERObjectIdentifier,l=n.DEREnumerated,g=n.DERUTF8String,f=n.DERNumericString,y=n.DERPrintableString,u=n.DERTeletexString,p=n.DERIA5String,C=n.DERUTCTime,j=n.DERGeneralizedTime,m=n.DERSequence,c=n.DERSet,r=n.DERTaggedObject,o=n.ASN1Util.newObject;var t=Object.keys(k);if(t.length!=1){throw"key of param shall be only one."}var F=t[0];if(":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":"+F+":")==-1){throw"undefined key: "+F}if(F=="bool"){return new z(k[F])}if(F=="int"){return new e(k[F])}if(F=="bitstr"){return new s(k[F])}if(F=="octstr"){return new h(k[F])}if(F=="null"){return new v(k[F])}if(F=="oid"){return new w(k[F])}if(F=="enum"){return new l(k[F])}if(F=="utf8str"){return new g(k[F])}if(F=="numstr"){return new f(k[F])}if(F=="prnstr"){return new y(k[F])}if(F=="telstr"){return new u(k[F])}if(F=="ia5str"){return new p(k[F])}if(F=="utctime"){return new C(k[F])}if(F=="gentime"){return new j(k[F])}if(F=="seq"){var d=k[F];var E=[];for(var x=0;x<d.length;x++){var B=o(d[x]);E.push(B)}return new m({array:E})}if(F=="set"){var d=k[F];var E=[];for(var x=0;x<d.length;x++){var B=o(d[x]);E.push(B)}return new c({array:E})}if(F=="tag"){var A=k[F];if(Object.prototype.toString.call(A)==="[object Array]"&&A.length==3){var q=o(A[2]);return new r({tag:A[0],explicit:A[1],obj:q})}else{var b={};if(A.explicit!==undefined){b.explicit=A.explicit}if(A.tag!==undefined){b.tag=A.tag}if(A.obj===undefined){throw"obj shall be specified for 'tag'."}b.obj=o(A.obj);return new r(b)}}};this.jsonToASN1HEX=function(b){var a=this.newObject(b);return a.getEncodedHex()}};KJUR.asn1.ASN1Util.oidHexToInt=function(a){var j="";var k=parseInt(a.substr(0,2),16);var d=Math.floor(k/40);var c=k%40;var j=d+"."+c;var e="";for(var f=2;f<a.length;f+=2){var g=parseInt(a.substr(f,2),16);var h=("00000000"+g.toString(2)).slice(-8);e=e+h.substr(1,7);if(h.substr(0,1)=="0"){var b=new BigInteger(e,2);j=j+"."+b.toString(10);e=""}}return j};KJUR.asn1.ASN1Util.oidIntToHex=function(f){var e=function(a){var k=a.toString(16);if(k.length==1){k="0"+k}return k};var d=function(o){var n="";var k=new BigInteger(o,10);var a=k.toString(2);var l=7-a.length%7;if(l==7){l=0}var q="";for(var m=0;m<l;m++){q+="0"}a=q+a;for(var m=0;m<a.length-1;m+=7){var p=a.substr(m,7);if(m!=a.length-7){p="1"+p}n+=e(parseInt(p,2))}return n};if(!f.match(/^[0-9.]+$/)){throw"malformed oid string: "+f}var g="";var b=f.split(".");var j=parseInt(b[0])*40+parseInt(b[1]);g+=e(j);b.splice(0,2);for(var c=0;c<b.length;c++){g+=d(b[c])}return g};KJUR.asn1.ASN1Object=function(){var c=true;var b=null;var d="00";var e="00";var a="";this.getLengthHexFromValue=function(){if(typeof this.hV=="undefined"||this.hV==null){throw"this.hV is null or undefined."}if(this.hV.length%2==1){throw"value hex must be even length: n="+a.length+",v="+this.hV}var i=this.hV.length/2;var h=i.toString(16);if(h.length%2==1){h="0"+h}if(i<128){return h}else{var g=h.length/2;if(g>15){throw"ASN.1 length too long to represent by 8x: n = "+i.toString(16)}var f=128+g;return f.toString(16)+h}};this.getEncodedHex=function(){if(this.hTLV==null||this.isModified){this.hV=this.getFreshValueHex();this.hL=this.getLengthHexFromValue();this.hTLV=this.hT+this.hL+this.hV;this.isModified=false}return this.hTLV};this.getValueHex=function(){this.getEncodedHex();return this.hV};this.getFreshValueHex=function(){return""}};KJUR.asn1.DERAbstractString=function(c){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);var b=null;var a=null;this.getString=function(){return this.s};this.setString=function(d){this.hTLV=null;this.isModified=true;this.s=d;this.hV=utf8tohex(this.s).toLowerCase()};this.setStringHex=function(d){this.hTLV=null;this.isModified=true;this.s=null;this.hV=d};this.getFreshValueHex=function(){return this.hV};if(typeof c!="undefined"){if(typeof c=="string"){this.setString(c)}else{if(typeof c.str!="undefined"){this.setString(c.str)}else{if(typeof c.hex!="undefined"){this.setStringHex(c.hex)}}}}};YAHOO.lang.extend(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractTime=function(c){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);var b=null;var a=null;this.localDateToUTC=function(g){var e=g.getTime()+(g.getTimezoneOffset()*60000);var f=new Date(e);return f};this.formatDate=function(m,o,e){var g=this.zeroPadding;var n=this.localDateToUTC(m);var p=String(n.getFullYear());if(o=="utc"){p=p.substr(2,2)}var l=g(String(n.getMonth()+1),2);var q=g(String(n.getDate()),2);var h=g(String(n.getHours()),2);var i=g(String(n.getMinutes()),2);var j=g(String(n.getSeconds()),2);var r=p+l+q+h+i+j;if(e===true){var f=n.getMilliseconds();if(f!=0){var k=g(String(f),3);k=k.replace(/[0]+$/,"");r=r+"."+k}}return r+"Z"};this.zeroPadding=function(e,d){if(e.length>=d){return e}return new Array(d-e.length+1).join("0")+e};this.getString=function(){return this.s};this.setString=function(d){this.hTLV=null;this.isModified=true;this.s=d;this.hV=stohex(d)};this.setByDateValue=function(h,j,e,d,f,g){var i=new Date(Date.UTC(h,j-1,e,d,f,g,0));this.setByDate(i)};this.getFreshValueHex=function(){return this.hV}};YAHOO.lang.extend(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractStructured=function(b){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);var a=null;this.setByASN1ObjectArray=function(c){this.hTLV=null;this.isModified=true;this.asn1Array=c};this.appendASN1Object=function(c){this.hTLV=null;this.isModified=true;this.asn1Array.push(c)};this.asn1Array=new Array();if(typeof b!="undefined"){if(typeof b.array!="undefined"){this.asn1Array=b.array}}};YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object);KJUR.asn1.DERBoolean=function(){KJUR.asn1.DERBoolean.superclass.constructor.call(this);this.hT="01";this.hTLV="0101ff"};YAHOO.lang.extend(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object);KJUR.asn1.DERInteger=function(a){KJUR.asn1.DERInteger.superclass.constructor.call(this);this.hT="02";this.setByBigInteger=function(b){this.hTLV=null;this.isModified=true;this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(b)};this.setByInteger=function(c){var b=new BigInteger(String(c),10);this.setByBigInteger(b)};this.setValueHex=function(b){this.hV=b};this.getFreshValueHex=function(){return this.hV};if(typeof a!="undefined"){if(typeof a.bigint!="undefined"){this.setByBigInteger(a.bigint)}else{if(typeof a["int"]!="undefined"){this.setByInteger(a["int"])}else{if(typeof a=="number"){this.setByInteger(a)}else{if(typeof a.hex!="undefined"){this.setValueHex(a.hex)}}}}}};YAHOO.lang.extend(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object);KJUR.asn1.DERBitString=function(b){if(b!==undefined&&typeof b.obj!=="undefined"){var a=KJUR.asn1.ASN1Util.newObject(b.obj);b.hex="00"+a.getEncodedHex()}KJUR.asn1.DERBitString.superclass.constructor.call(this);this.hT="03";this.setHexValueIncludingUnusedBits=function(c){this.hTLV=null;this.isModified=true;this.hV=c};this.setUnusedBitsAndHexValue=function(c,e){if(c<0||7<c){throw"unused bits shall be from 0 to 7: u = "+c}var d="0"+c;this.hTLV=null;this.isModified=true;this.hV=d+e};this.setByBinaryString=function(e){e=e.replace(/0+$/,"");var f=8-e.length%8;if(f==8){f=0}for(var g=0;g<=f;g++){e+="0"}var j="";for(var g=0;g<e.length-1;g+=8){var d=e.substr(g,8);var c=parseInt(d,2).toString(16);if(c.length==1){c="0"+c}j+=c}this.hTLV=null;this.isModified=true;this.hV="0"+f+j};this.setByBooleanArray=function(e){var d="";for(var c=0;c<e.length;c++){if(e[c]==true){d+="1"}else{d+="0"}}this.setByBinaryString(d)};this.newFalseArray=function(e){var c=new Array(e);for(var d=0;d<e;d++){c[d]=false}return c};this.getFreshValueHex=function(){return this.hV};if(typeof b!="undefined"){if(typeof b=="string"&&b.toLowerCase().match(/^[0-9a-f]+$/)){this.setHexValueIncludingUnusedBits(b)}else{if(typeof b.hex!="undefined"){this.setHexValueIncludingUnusedBits(b.hex)}else{if(typeof b.bin!="undefined"){this.setByBinaryString(b.bin)}else{if(typeof b.array!="undefined"){this.setByBooleanArray(b.array)}}}}}};YAHOO.lang.extend(KJUR.asn1.DERBitString,KJUR.asn1.ASN1Object);KJUR.asn1.DEROctetString=function(b){if(b!==undefined&&typeof b.obj!=="undefined"){var a=KJUR.asn1.ASN1Util.newObject(b.obj);b.hex=a.getEncodedHex()}KJUR.asn1.DEROctetString.superclass.constructor.call(this,b);this.hT="04"};YAHOO.lang.extend(KJUR.asn1.DEROctetString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERNull=function(){KJUR.asn1.DERNull.superclass.constructor.call(this);this.hT="05";this.hTLV="0500"};YAHOO.lang.extend(KJUR.asn1.DERNull,KJUR.asn1.ASN1Object);KJUR.asn1.DERObjectIdentifier=function(c){var b=function(d){var e=d.toString(16);if(e.length==1){e="0"+e}return e};var a=function(k){var j="";var e=new BigInteger(k,10);var d=e.toString(2);var f=7-d.length%7;if(f==7){f=0}var m="";for(var g=0;g<f;g++){m+="0"}d=m+d;for(var g=0;g<d.length-1;g+=7){var l=d.substr(g,7);if(g!=d.length-7){l="1"+l}j+=b(parseInt(l,2))}return j};KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);this.hT="06";this.setValueHex=function(d){this.hTLV=null;this.isModified=true;this.s=null;this.hV=d};this.setValueOidString=function(f){if(!f.match(/^[0-9.]+$/)){throw"malformed oid string: "+f}var g="";var d=f.split(".");var j=parseInt(d[0])*40+parseInt(d[1]);g+=b(j);d.splice(0,2);for(var e=0;e<d.length;e++){g+=a(d[e])}this.hTLV=null;this.isModified=true;this.s=null;this.hV=g};this.setValueName=function(e){var d=KJUR.asn1.x509.OID.name2oid(e);if(d!==""){this.setValueOidString(d)}else{throw"DERObjectIdentifier oidName undefined: "+e}};this.getFreshValueHex=function(){return this.hV};if(c!==undefined){if(typeof c==="string"){if(c.match(/^[0-2].[0-9.]+$/)){this.setValueOidString(c)}else{this.setValueName(c)}}else{if(c.oid!==undefined){this.setValueOidString(c.oid)}else{if(c.hex!==undefined){this.setValueHex(c.hex)}else{if(c.name!==undefined){this.setValueName(c.name)}}}}}};YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier,KJUR.asn1.ASN1Object);KJUR.asn1.DEREnumerated=function(a){KJUR.asn1.DEREnumerated.superclass.constructor.call(this);this.hT="0a";this.setByBigInteger=function(b){this.hTLV=null;this.isModified=true;this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(b)};this.setByInteger=function(c){var b=new BigInteger(String(c),10);this.setByBigInteger(b)};this.setValueHex=function(b){this.hV=b};this.getFreshValueHex=function(){return this.hV};if(typeof a!="undefined"){if(typeof a["int"]!="undefined"){this.setByInteger(a["int"])}else{if(typeof a=="number"){this.setByInteger(a)}else{if(typeof a.hex!="undefined"){this.setValueHex(a.hex)}}}}};YAHOO.lang.extend(KJUR.asn1.DEREnumerated,KJUR.asn1.ASN1Object);KJUR.asn1.DERUTF8String=function(a){KJUR.asn1.DERUTF8String.superclass.constructor.call(this,a);this.hT="0c"};YAHOO.lang.extend(KJUR.asn1.DERUTF8String,KJUR.asn1.DERAbstractString);KJUR.asn1.DERNumericString=function(a){KJUR.asn1.DERNumericString.superclass.constructor.call(this,a);this.hT="12"};YAHOO.lang.extend(KJUR.asn1.DERNumericString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERPrintableString=function(a){KJUR.asn1.DERPrintableString.superclass.constructor.call(this,a);this.hT="13"};YAHOO.lang.extend(KJUR.asn1.DERPrintableString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERTeletexString=function(a){KJUR.asn1.DERTeletexString.superclass.constructor.call(this,a);this.hT="14"};YAHOO.lang.extend(KJUR.asn1.DERTeletexString,KJUR.asn1.DERAbstractString);KJUR.asn1.DERIA5String=function(a){KJUR.asn1.DERIA5String.superclass.constructor.call(this,a);this.hT="16"};YAHOO.lang.extend(KJUR.asn1.DERIA5String,KJUR.asn1.DERAbstractString);KJUR.asn1.DERUTCTime=function(a){KJUR.asn1.DERUTCTime.superclass.constructor.call(this,a);this.hT="17";this.setByDate=function(b){this.hTLV=null;this.isModified=true;this.date=b;this.s=this.formatDate(this.date,"utc");this.hV=stohex(this.s)};this.getFreshValueHex=function(){if(typeof this.date=="undefined"&&typeof this.s=="undefined"){this.date=new Date();this.s=this.formatDate(this.date,"utc");this.hV=stohex(this.s)}return this.hV};if(a!==undefined){if(a.str!==undefined){this.setString(a.str)}else{if(typeof a=="string"&&a.match(/^[0-9]{12}Z$/)){this.setString(a)}else{if(a.hex!==undefined){this.setStringHex(a.hex)}else{if(a.date!==undefined){this.setByDate(a.date)}}}}}};YAHOO.lang.extend(KJUR.asn1.DERUTCTime,KJUR.asn1.DERAbstractTime);KJUR.asn1.DERGeneralizedTime=function(a){KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this,a);this.hT="18";this.withMillis=false;this.setByDate=function(b){this.hTLV=null;this.isModified=true;this.date=b;this.s=this.formatDate(this.date,"gen",this.withMillis);this.hV=stohex(this.s)};this.getFreshValueHex=function(){if(this.date===undefined&&this.s===undefined){this.date=new Date();this.s=this.formatDate(this.date,"gen",this.withMillis);this.hV=stohex(this.s)}return this.hV};if(a!==undefined){if(a.str!==undefined){this.setString(a.str)}else{if(typeof a=="string"&&a.match(/^[0-9]{14}Z$/)){this.setString(a)}else{if(a.hex!==undefined){this.setStringHex(a.hex)}else{if(a.date!==undefined){this.setByDate(a.date)}}}}if(a.millis===true){this.withMillis=true}}};YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime,KJUR.asn1.DERAbstractTime);KJUR.asn1.DERSequence=function(a){KJUR.asn1.DERSequence.superclass.constructor.call(this,a);this.hT="30";this.getFreshValueHex=function(){var c="";for(var b=0;b<this.asn1Array.length;b++){var d=this.asn1Array[b];c+=d.getEncodedHex()}this.hV=c;return this.hV}};YAHOO.lang.extend(KJUR.asn1.DERSequence,KJUR.asn1.DERAbstractStructured);KJUR.asn1.DERSet=function(a){KJUR.asn1.DERSet.superclass.constructor.call(this,a);this.hT="31";this.sortFlag=true;this.getFreshValueHex=function(){var b=new Array();for(var c=0;c<this.asn1Array.length;c++){var d=this.asn1Array[c];b.push(d.getEncodedHex())}if(this.sortFlag==true){b.sort()}this.hV=b.join("");return this.hV};if(typeof a!="undefined"){if(typeof a.sortflag!="undefined"&&a.sortflag==false){this.sortFlag=false}}};YAHOO.lang.extend(KJUR.asn1.DERSet,KJUR.asn1.DERAbstractStructured);KJUR.asn1.DERTaggedObject=function(a){KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);this.hT="a0";this.hV="";this.isExplicit=true;this.asn1Object=null;this.setASN1Object=function(b,c,d){this.hT=c;this.isExplicit=b;this.asn1Object=d;if(this.isExplicit){this.hV=this.asn1Object.getEncodedHex();this.hTLV=null;this.isModified=true}else{this.hV=null;this.hTLV=d.getEncodedHex();this.hTLV=this.hTLV.replace(/^../,c);this.isModified=false}};this.getFreshValueHex=function(){return this.hV};if(typeof a!="undefined"){if(typeof a.tag!="undefined"){this.hT=a.tag}if(typeof a.explicit!="undefined"){this.isExplicit=a.explicit}if(typeof a.obj!="undefined"){this.asn1Object=a.obj;this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)}}};YAHOO.lang.extend(KJUR.asn1.DERTaggedObject,KJUR.asn1.ASN1Object); var ASN1HEX=new function(){};ASN1HEX.getLblen=function(c,a){if(c.substr(a+2,1)!="8"){return 1}var b=parseInt(c.substr(a+3,1));if(b==0){return -1}if(0<b&&b<10){return b+1}return -2};ASN1HEX.getL=function(c,b){var a=ASN1HEX.getLblen(c,b);if(a<1){return""}return c.substr(b+2,a*2)};ASN1HEX.getVblen=function(d,a){var c,b;c=ASN1HEX.getL(d,a);if(c==""){return -1}if(c.substr(0,1)==="8"){b=new BigInteger(c.substr(2),16)}else{b=new BigInteger(c,16)}return b.intValue()};ASN1HEX.getVidx=function(c,b){var a=ASN1HEX.getLblen(c,b);if(a<0){return a}return b+(a+1)*2};ASN1HEX.getV=function(d,a){var c=ASN1HEX.getVidx(d,a);var b=ASN1HEX.getVblen(d,a);return d.substr(c,b*2)};ASN1HEX.getTLV=function(b,a){return b.substr(a,2)+ASN1HEX.getL(b,a)+ASN1HEX.getV(b,a)};ASN1HEX.getNextSiblingIdx=function(d,a){var c=ASN1HEX.getVidx(d,a);var b=ASN1HEX.getVblen(d,a);return c+b*2};ASN1HEX.getChildIdx=function(e,f){var j=ASN1HEX;var g=new Array();var i=j.getVidx(e,f);if(e.substr(f,2)=="03"){g.push(i+2)}else{g.push(i)}var l=j.getVblen(e,f);var c=i;var d=0;while(1){var b=j.getNextSiblingIdx(e,c);if(b==null||(b-i>=(l*2))){break}if(d>=200){break}g.push(b);c=b;d++}return g};ASN1HEX.getNthChildIdx=function(d,b,e){var c=ASN1HEX.getChildIdx(d,b);return c[e]};ASN1HEX.getIdxbyList=function(e,d,c,i){var g=ASN1HEX;var f,b;if(c.length==0){if(i!==undefined){if(e.substr(d,2)!==i){throw Error("checking tag doesn't match: "+e.substr(d,2)+"!="+i)}}return d}f=c.shift();b=g.getChildIdx(e,d);return g.getIdxbyList(e,b[f],c,i)};ASN1HEX.getTLVbyList=function(d,c,b,f){var e=ASN1HEX;var a=e.getIdxbyList(d,c,b);if(a===undefined){throw"can't find nthList object"}if(f!==undefined){if(d.substr(a,2)!=f){throw"checking tag doesn't match: "+d.substr(a,2)+"!="+f}}return e.getTLV(d,a)};ASN1HEX.getVbyList=function(e,c,b,g,i){var f=ASN1HEX;var a,d;a=f.getIdxbyList(e,c,b,g);if(a===undefined){throw"can't find nthList object"}d=f.getV(e,a);if(i===true){d=d.substr(2)}return d};ASN1HEX.hextooidstr=function(e){var h=function(b,a){if(b.length>=a){return b}return new Array(a-b.length+1).join("0")+b};var l=[];var o=e.substr(0,2);var f=parseInt(o,16);l[0]=new String(Math.floor(f/40));l[1]=new String(f%40);var m=e.substr(2);var k=[];for(var g=0;g<m.length/2;g++){k.push(parseInt(m.substr(g*2,2),16))}var j=[];var d="";for(var g=0;g<k.length;g++){if(k[g]&128){d=d+h((k[g]&127).toString(2),7)}else{d=d+h((k[g]&127).toString(2),7);j.push(new String(parseInt(d,2)));d=""}}var n=l.join(".");if(j.length>0){n=n+"."+j.join(".")}return n};ASN1HEX.dump=function(t,c,l,g){var p=ASN1HEX;var j=p.getV;var y=p.dump;var w=p.getChildIdx;var e=t;if(t instanceof KJUR.asn1.ASN1Object){e=t.getEncodedHex()}var q=function(A,i){if(A.length<=i*2){return A}else{var v=A.substr(0,i)+"..(total "+A.length/2+"bytes).."+A.substr(A.length-i,i);return v}};if(c===undefined){c={ommit_long_octet:32}}if(l===undefined){l=0}if(g===undefined){g=""}var x=c.ommit_long_octet;if(e.substr(l,2)=="01"){var h=j(e,l);if(h=="00"){return g+"BOOLEAN FALSE\n"}else{return g+"BOOLEAN TRUE\n"}}if(e.substr(l,2)=="02"){var h=j(e,l);return g+"INTEGER "+q(h,x)+"\n"}if(e.substr(l,2)=="03"){var h=j(e,l);return g+"BITSTRING "+q(h,x)+"\n"}if(e.substr(l,2)=="04"){var h=j(e,l);if(p.isASN1HEX(h)){var k=g+"OCTETSTRING, encapsulates\n";k=k+y(h,c,0,g+" ");return k}else{return g+"OCTETSTRING "+q(h,x)+"\n"}}if(e.substr(l,2)=="05"){return g+"NULL\n"}if(e.substr(l,2)=="06"){var m=j(e,l);var a=KJUR.asn1.ASN1Util.oidHexToInt(m);var o=KJUR.asn1.x509.OID.oid2name(a);var b=a.replace(/\./g," ");if(o!=""){return g+"ObjectIdentifier "+o+" ("+b+")\n"}else{return g+"ObjectIdentifier ("+b+")\n"}}if(e.substr(l,2)=="0c"){return g+"UTF8String '"+hextoutf8(j(e,l))+"'\n"}if(e.substr(l,2)=="13"){return g+"PrintableString '"+hextoutf8(j(e,l))+"'\n"}if(e.substr(l,2)=="14"){return g+"TeletexString '"+hextoutf8(j(e,l))+"'\n"}if(e.substr(l,2)=="16"){return g+"IA5String '"+hextoutf8(j(e,l))+"'\n"}if(e.substr(l,2)=="17"){return g+"UTCTime "+hextoutf8(j(e,l))+"\n"}if(e.substr(l,2)=="18"){return g+"GeneralizedTime "+hextoutf8(j(e,l))+"\n"}if(e.substr(l,2)=="30"){if(e.substr(l,4)=="3000"){return g+"SEQUENCE {}\n"}var k=g+"SEQUENCE\n";var d=w(e,l);var f=c;if((d.length==2||d.length==3)&&e.substr(d[0],2)=="06"&&e.substr(d[d.length-1],2)=="04"){var o=p.oidname(j(e,d[0]));var r=JSON.parse(JSON.stringify(c));r.x509ExtName=o;f=r}for(var u=0;u<d.length;u++){k=k+y(e,f,d[u],g+" ")}return k}if(e.substr(l,2)=="31"){var k=g+"SET\n";var d=w(e,l);for(var u=0;u<d.length;u++){k=k+y(e,c,d[u],g+" ")}return k}var z=parseInt(e.substr(l,2),16);if((z&128)!=0){var n=z&31;if((z&32)!=0){var k=g+"["+n+"]\n";var d=w(e,l);for(var u=0;u<d.length;u++){k=k+y(e,c,d[u],g+" ")}return k}else{var h=j(e,l);if(h.substr(0,8)=="68747470"){h=hextoutf8(h)}if(c.x509ExtName==="subjectAltName"&&n==2){h=hextoutf8(h)}var k=g+"["+n+"] "+h+"\n";return k}}return g+"UNKNOWN("+e.substr(l,2)+") "+j(e,l)+"\n"};ASN1HEX.isASN1HEX=function(e){var d=ASN1HEX;if(e.length%2==1){return false}var c=d.getVblen(e,0);var b=e.substr(0,2);var f=d.getL(e,0);var a=e.length-b.length-f.length;if(a==c*2){return true}return false};ASN1HEX.checkStrictDER=function(g,o,d,c,r){var s=ASN1HEX;if(d===undefined){if(typeof g!="string"){throw new Error("not hex string")}g=g.toLowerCase();if(!KJUR.lang.String.isHex(g)){throw new Error("not hex string")}d=g.length;c=g.length/2;if(c<128){r=1}else{r=Math.ceil(c.toString(16))+1}}var k=s.getL(g,o);if(k.length>r*2){throw new Error("L of TLV too long: idx="+o)}var n=s.getVblen(g,o);if(n>c){throw new Error("value of L too long than hex: idx="+o)}var q=s.getTLV(g,o);var f=q.length-2-s.getL(g,o).length;if(f!==(n*2)){throw new Error("V string length and L's value not the same:"+f+"/"+(n*2))}if(o===0){if(g.length!=q.length){throw new Error("total length and TLV length unmatch:"+g.length+"!="+q.length)}}var b=g.substr(o,2);if(b==="02"){var a=s.getVidx(g,o);if(g.substr(a,2)=="00"&&g.charCodeAt(a+2)<56){throw new Error("not least zeros for DER INTEGER")}}if(parseInt(b,16)&32){var p=s.getVblen(g,o);var m=0;var l=s.getChildIdx(g,o);for(var e=0;e<l.length;e++){var j=s.getTLV(g,l[e]);m+=j.length;s.checkStrictDER(g,l[e],d,c,r)}if((p*2)!=m){throw new Error("sum of children's TLV length and L unmatch: "+(p*2)+"!="+m)}}};ASN1HEX.oidname=function(a){var c=KJUR.asn1;if(KJUR.lang.String.isHex(a)){a=c.ASN1Util.oidHexToInt(a)}var b=c.x509.OID.oid2name(a);if(b===""){b=a}return b}; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}if(typeof KJUR.asn1.x509=="undefined"||!KJUR.asn1.x509){KJUR.asn1.x509={}}KJUR.asn1.x509.Certificate=function(e){KJUR.asn1.x509.Certificate.superclass.constructor.call(this);var a=null,j=null,h=null,k=null,i=null,b=KJUR,f=b.crypto,g=b.asn1,d=g.DERSequence,c=g.DERBitString;this.sign=function(){this.asn1SignatureAlg=this.asn1TBSCert.asn1SignatureAlg;var m=new KJUR.crypto.Signature({alg:this.asn1SignatureAlg.nameAlg});m.init(this.prvKey);m.updateHex(this.asn1TBSCert.getEncodedHex());this.hexSig=m.sign();this.asn1Sig=new c({hex:"00"+this.hexSig});var l=new d({array:[this.asn1TBSCert,this.asn1SignatureAlg,this.asn1Sig]});this.hTLV=l.getEncodedHex();this.isModified=false};this.setSignatureHex=function(l){this.asn1SignatureAlg=this.asn1TBSCert.asn1SignatureAlg;this.hexSig=l;this.asn1Sig=new c({hex:"00"+this.hexSig});var m=new d({array:[this.asn1TBSCert,this.asn1SignatureAlg,this.asn1Sig]});this.hTLV=m.getEncodedHex();this.isModified=false};this.getEncodedHex=function(){if(this.isModified==false&&this.hTLV!=null){return this.hTLV}throw"not signed yet"};this.getPEMString=function(){var l=hextob64nl(this.getEncodedHex());return"-----BEGIN CERTIFICATE-----\r\n"+l+"\r\n-----END CERTIFICATE-----\r\n"};if(e!==undefined){if(e.tbscertobj!==undefined){this.asn1TBSCert=e.tbscertobj}if(e.prvkeyobj!==undefined){this.prvKey=e.prvkeyobj}}};YAHOO.lang.extend(KJUR.asn1.x509.Certificate,KJUR.asn1.ASN1Object);KJUR.asn1.x509.TBSCertificate=function(e){KJUR.asn1.x509.TBSCertificate.superclass.constructor.call(this);var b=KJUR,i=b.asn1,f=i.DERSequence,h=i.DERInteger,c=i.DERTaggedObject,d=i.x509,g=d.Time,a=d.X500Name,j=d.SubjectPublicKeyInfo;this._initialize=function(){this.asn1Array=new Array();this.asn1Version=new c({obj:new h({"int":2})});this.asn1SerialNumber=null;this.asn1SignatureAlg=null;this.asn1Issuer=null;this.asn1NotBefore=null;this.asn1NotAfter=null;this.asn1Subject=null;this.asn1SubjPKey=null;this.extensionsArray=new Array()};this.setSerialNumberByParam=function(k){this.asn1SerialNumber=new h(k)};this.setSignatureAlgByParam=function(k){this.asn1SignatureAlg=new d.AlgorithmIdentifier(k)};this.setIssuerByParam=function(k){this.asn1Issuer=new a(k)};this.setNotBeforeByParam=function(k){this.asn1NotBefore=new g(k)};this.setNotAfterByParam=function(k){this.asn1NotAfter=new g(k)};this.setSubjectByParam=function(k){this.asn1Subject=new a(k)};this.setSubjectPublicKey=function(k){this.asn1SubjPKey=new j(k)};this.setSubjectPublicKeyByGetKey=function(l){var k=KEYUTIL.getKey(l);this.asn1SubjPKey=new j(k)};this.appendExtension=function(k){this.extensionsArray.push(k)};this.appendExtensionByName=function(l,k){KJUR.asn1.x509.Extension.appendByNameToArray(l,k,this.extensionsArray)};this.getEncodedHex=function(){if(this.asn1NotBefore==null||this.asn1NotAfter==null){throw"notBefore and/or notAfter not set"}var l=new f({array:[this.asn1NotBefore,this.asn1NotAfter]});this.asn1Array=new Array();this.asn1Array.push(this.asn1Version);this.asn1Array.push(this.asn1SerialNumber);this.asn1Array.push(this.asn1SignatureAlg);this.asn1Array.push(this.asn1Issuer);this.asn1Array.push(l);this.asn1Array.push(this.asn1Subject);this.asn1Array.push(this.asn1SubjPKey);if(this.extensionsArray.length>0){var m=new f({array:this.extensionsArray});var k=new c({explicit:true,tag:"a3",obj:m});this.asn1Array.push(k)}var n=new f({array:this.asn1Array});this.hTLV=n.getEncodedHex();this.isModified=false;return this.hTLV};this._initialize()};YAHOO.lang.extend(KJUR.asn1.x509.TBSCertificate,KJUR.asn1.ASN1Object);KJUR.asn1.x509.Extension=function(d){KJUR.asn1.x509.Extension.superclass.constructor.call(this);var f=null,a=KJUR,e=a.asn1,h=e.DERObjectIdentifier,i=e.DEROctetString,b=e.DERBitString,g=e.DERBoolean,c=e.DERSequence;this.getEncodedHex=function(){var m=new h({oid:this.oid});var l=new i({hex:this.getExtnValueHex()});var k=new Array();k.push(m);if(this.critical){k.push(new g())}k.push(l);var j=new c({array:k});return j.getEncodedHex()};this.critical=false;if(d!==undefined){if(d.critical!==undefined){this.critical=d.critical}}};YAHOO.lang.extend(KJUR.asn1.x509.Extension,KJUR.asn1.ASN1Object);KJUR.asn1.x509.Extension.appendByNameToArray=function(e,c,b){var g=e.toLowerCase(),f=KJUR.asn1.x509;if(g=="basicconstraints"){var d=new f.BasicConstraints(c);b.push(d)}else{if(g=="keyusage"){var d=new f.KeyUsage(c);b.push(d)}else{if(g=="crldistributionpoints"){var d=new f.CRLDistributionPoints(c);b.push(d)}else{if(g=="extkeyusage"){var d=new f.ExtKeyUsage(c);b.push(d)}else{if(g=="authoritykeyidentifier"){var d=new f.AuthorityKeyIdentifier(c);b.push(d)}else{if(g=="subjectkeyidentifier"){var d=new f.SubjectKeyIdentifier(c);b.push(d)}else{if(g=="authorityinfoaccess"){var d=new f.AuthorityInfoAccess(c);b.push(d)}else{if(g=="subjectaltname"){var d=new f.SubjectAltName(c);b.push(d)}else{if(g=="issueraltname"){var d=new f.IssuerAltName(c);b.push(d)}else{throw"unsupported extension name: "+e}}}}}}}}}};KJUR.asn1.x509.KeyUsage=function(f){KJUR.asn1.x509.KeyUsage.superclass.constructor.call(this,f);var a=X509.KEYUSAGE_NAME;this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.oid="2.5.29.15";if(f!==undefined){if(f.bin!==undefined){this.asn1ExtnValue=new KJUR.asn1.DERBitString(f)}if(f.names!==undefined&&f.names.length!==undefined){var e=f.names;var d="000000000";for(var c=0;c<e.length;c++){for(var b=0;b<a.length;b++){if(e[c]===a[b]){d=d.substring(0,b)+"1"+d.substring(b+1,d.length)}}}this.asn1ExtnValue=new KJUR.asn1.DERBitString({bin:d})}}};YAHOO.lang.extend(KJUR.asn1.x509.KeyUsage,KJUR.asn1.x509.Extension);KJUR.asn1.x509.BasicConstraints=function(c){KJUR.asn1.x509.BasicConstraints.superclass.constructor.call(this,c);var a=false;var b=-1;this.getExtnValueHex=function(){var e=new Array();if(this.cA){e.push(new KJUR.asn1.DERBoolean())}if(this.pathLen>-1){e.push(new KJUR.asn1.DERInteger({"int":this.pathLen}))}var d=new KJUR.asn1.DERSequence({array:e});this.asn1ExtnValue=d;return this.asn1ExtnValue.getEncodedHex()};this.oid="2.5.29.19";this.cA=false;this.pathLen=-1;if(c!==undefined){if(c.cA!==undefined){this.cA=c.cA}if(c.pathLen!==undefined){this.pathLen=c.pathLen}}};YAHOO.lang.extend(KJUR.asn1.x509.BasicConstraints,KJUR.asn1.x509.Extension);KJUR.asn1.x509.CRLDistributionPoints=function(d){KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,d);var b=KJUR,a=b.asn1,c=a.x509;this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.setByDPArray=function(e){this.asn1ExtnValue=new a.DERSequence({array:e})};this.setByOneURI=function(h){var e=new c.GeneralNames([{uri:h}]);var g=new c.DistributionPointName(e);var f=new c.DistributionPoint({dpobj:g});this.setByDPArray([f])};this.oid="2.5.29.31";if(d!==undefined){if(d.array!==undefined){this.setByDPArray(d.array)}else{if(d.uri!==undefined){this.setByOneURI(d.uri)}}}};YAHOO.lang.extend(KJUR.asn1.x509.CRLDistributionPoints,KJUR.asn1.x509.Extension);KJUR.asn1.x509.ExtKeyUsage=function(c){KJUR.asn1.x509.ExtKeyUsage.superclass.constructor.call(this,c);var b=KJUR,a=b.asn1;this.setPurposeArray=function(d){this.asn1ExtnValue=new a.DERSequence();for(var e=0;e<d.length;e++){var f=new a.DERObjectIdentifier(d[e]);this.asn1ExtnValue.appendASN1Object(f)}};this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.oid="2.5.29.37";if(c!==undefined){if(c.array!==undefined){this.setPurposeArray(c.array)}}};YAHOO.lang.extend(KJUR.asn1.x509.ExtKeyUsage,KJUR.asn1.x509.Extension);KJUR.asn1.x509.AuthorityKeyIdentifier=function(f){KJUR.asn1.x509.AuthorityKeyIdentifier.superclass.constructor.call(this,f);var b=KJUR,a=b.asn1,d=a.DERTaggedObject,e=a.x509.GeneralNames,c=b.crypto.Util.isKey;this.asn1KID=null;this.asn1CertIssuer=null;this.asn1CertSN=null;this.getExtnValueHex=function(){var h=new Array();if(this.asn1KID){h.push(new d({explicit:false,tag:"80",obj:this.asn1KID}))}if(this.asn1CertIssuer){h.push(new d({explicit:false,tag:"a1",obj:new e([{dn:this.asn1CertIssuer}])}))}if(this.asn1CertSN){h.push(new d({explicit:false,tag:"82",obj:this.asn1CertSN}))}var g=new a.DERSequence({array:h});this.asn1ExtnValue=g;return this.asn1ExtnValue.getEncodedHex()};this.setKIDByParam=function(i){if(i.str!==undefined||i.hex!==undefined){this.asn1KID=new KJUR.asn1.DEROctetString(i)}else{if((typeof i==="object"&&KJUR.crypto.Util.isKey(i))||(typeof i==="string"&&i.indexOf("BEGIN ")!=-1)){var h=i;if(typeof i==="string"){h=KEYUTIL.getKey(i)}var g=KEYUTIL.getKeyID(h);this.asn1KID=new KJUR.asn1.DEROctetString({hex:g})}}};this.setCertIssuerByParam=function(g){if(g.str!==undefined||g.ldapstr!==undefined||g.hex!==undefined||g.certsubject!==undefined||g.certissuer!==undefined){this.asn1CertIssuer=new KJUR.asn1.x509.X500Name(g)}else{if(typeof g==="string"&&g.indexOf("BEGIN ")!=-1&&g.indexOf("CERTIFICATE")!=-1){this.asn1CertIssuer=new KJUR.asn1.x509.X500Name({certissuer:g})}}};this.setCertSNByParam=function(i){if(i.str!==undefined||i.bigint!==undefined||i.hex!==undefined){this.asn1CertSN=new KJUR.asn1.DERInteger(i)}else{if(typeof i==="string"&&i.indexOf("BEGIN ")!=-1&&i.indexOf("CERTIFICATE")){var g=new X509();g.readCertPEM(i);var h=g.getSerialNumberHex();this.asn1CertSN=new KJUR.asn1.DERInteger({hex:h})}}};this.oid="2.5.29.35";if(f!==undefined){if(f.kid!==undefined){this.setKIDByParam(f.kid)}if(f.issuer!==undefined){this.setCertIssuerByParam(f.issuer)}if(f.sn!==undefined){this.setCertSNByParam(f.sn)}if(f.issuersn!==undefined&&typeof f.issuersn==="string"&&f.issuersn.indexOf("BEGIN ")!=-1&&f.issuersn.indexOf("CERTIFICATE")){this.setCertSNByParam(f.issuersn);this.setCertIssuerByParam(f.issuersn)}}};YAHOO.lang.extend(KJUR.asn1.x509.AuthorityKeyIdentifier,KJUR.asn1.x509.Extension);KJUR.asn1.x509.SubjectKeyIdentifier=function(d){KJUR.asn1.x509.SubjectKeyIdentifier.superclass.constructor.call(this,d);var b=KJUR,a=b.asn1,c=a.DEROctetString;this.asn1KID=null;this.getExtnValueHex=function(){this.asn1ExtnValue=this.asn1KID;return this.asn1ExtnValue.getEncodedHex()};this.setKIDByParam=function(g){if(g.str!==undefined||g.hex!==undefined){this.asn1KID=new c(g)}else{if((typeof g==="object"&&KJUR.crypto.Util.isKey(g))||(typeof g==="string"&&g.indexOf("BEGIN")!=-1)){var f=g;if(typeof g==="string"){f=KEYUTIL.getKey(g)}var e=KEYUTIL.getKeyID(f);this.asn1KID=new KJUR.asn1.DEROctetString({hex:e})}}};this.oid="2.5.29.14";if(d!==undefined){if(d.kid!==undefined){this.setKIDByParam(d.kid)}}};YAHOO.lang.extend(KJUR.asn1.x509.SubjectKeyIdentifier,KJUR.asn1.x509.Extension);KJUR.asn1.x509.AuthorityInfoAccess=function(a){KJUR.asn1.x509.AuthorityInfoAccess.superclass.constructor.call(this,a);this.setAccessDescriptionArray=function(k){var j=new Array(),b=KJUR,g=b.asn1,d=g.DERSequence;for(var f=0;f<k.length;f++){var c=new g.DERObjectIdentifier(k[f].accessMethod);var e=new g.x509.GeneralName(k[f].accessLocation);var h=new d({array:[c,e]});j.push(h)}this.asn1ExtnValue=new d({array:j})};this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.oid="1.3.6.1.5.5.7.1.1";if(a!==undefined){if(a.array!==undefined){this.setAccessDescriptionArray(a.array)}}};YAHOO.lang.extend(KJUR.asn1.x509.AuthorityInfoAccess,KJUR.asn1.x509.Extension);KJUR.asn1.x509.SubjectAltName=function(a){KJUR.asn1.x509.SubjectAltName.superclass.constructor.call(this,a);this.setNameArray=function(b){this.asn1ExtnValue=new KJUR.asn1.x509.GeneralNames(b)};this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.oid="2.5.29.17";if(a!==undefined){if(a.array!==undefined){this.setNameArray(a.array)}}};YAHOO.lang.extend(KJUR.asn1.x509.SubjectAltName,KJUR.asn1.x509.Extension);KJUR.asn1.x509.IssuerAltName=function(a){KJUR.asn1.x509.IssuerAltName.superclass.constructor.call(this,a);this.setNameArray=function(b){this.asn1ExtnValue=new KJUR.asn1.x509.GeneralNames(b)};this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.oid="2.5.29.18";if(a!==undefined){if(a.array!==undefined){this.setNameArray(a.array)}}};YAHOO.lang.extend(KJUR.asn1.x509.IssuerAltName,KJUR.asn1.x509.Extension);KJUR.asn1.x509.CRL=function(f){KJUR.asn1.x509.CRL.superclass.constructor.call(this);var b=null,d=null,e=null,c=null,a=null;this.sign=function(){this.asn1SignatureAlg=this.asn1TBSCertList.asn1SignatureAlg;sig=new KJUR.crypto.Signature({alg:this.asn1SignatureAlg.nameAlg,prov:"cryptojs/jsrsa"});sig.init(this.prvKey);sig.updateHex(this.asn1TBSCertList.getEncodedHex());this.hexSig=sig.sign();this.asn1Sig=new KJUR.asn1.DERBitString({hex:"00"+this.hexSig});var g=new KJUR.asn1.DERSequence({array:[this.asn1TBSCertList,this.asn1SignatureAlg,this.asn1Sig]});this.hTLV=g.getEncodedHex();this.isModified=false};this.getEncodedHex=function(){if(this.isModified==false&&this.hTLV!=null){return this.hTLV}throw"not signed yet"};this.getPEMString=function(){var g=hextob64nl(this.getEncodedHex());return"-----BEGIN X509 CRL-----\r\n"+g+"\r\n-----END X509 CRL-----\r\n"};if(f!==undefined){if(f.tbsobj!==undefined){this.asn1TBSCertList=f.tbsobj}if(f.prvkeyobj!==undefined){this.prvKey=f.prvkeyobj}}};YAHOO.lang.extend(KJUR.asn1.x509.CRL,KJUR.asn1.ASN1Object);KJUR.asn1.x509.TBSCertList=function(g){KJUR.asn1.x509.TBSCertList.superclass.constructor.call(this);var e=null,d=KJUR,c=d.asn1,b=c.DERSequence,f=c.x509,a=f.Time;this.setSignatureAlgByParam=function(h){this.asn1SignatureAlg=new f.AlgorithmIdentifier(h)};this.setIssuerByParam=function(h){this.asn1Issuer=new f.X500Name(h)};this.setThisUpdateByParam=function(h){this.asn1ThisUpdate=new a(h)};this.setNextUpdateByParam=function(h){this.asn1NextUpdate=new a(h)};this.addRevokedCert=function(h,i){var k={};if(h!=undefined&&h!=null){k.sn=h}if(i!=undefined&&i!=null){k.time=i}var j=new f.CRLEntry(k);this.aRevokedCert.push(j)};this.getEncodedHex=function(){this.asn1Array=new Array();if(this.asn1Version!=null){this.asn1Array.push(this.asn1Version)}this.asn1Array.push(this.asn1SignatureAlg);this.asn1Array.push(this.asn1Issuer);this.asn1Array.push(this.asn1ThisUpdate);if(this.asn1NextUpdate!=null){this.asn1Array.push(this.asn1NextUpdate)}if(this.aRevokedCert.length>0){var h=new b({array:this.aRevokedCert});this.asn1Array.push(h)}var i=new b({array:this.asn1Array});this.hTLV=i.getEncodedHex();this.isModified=false;return this.hTLV};this._initialize=function(){this.asn1Version=null;this.asn1SignatureAlg=null;this.asn1Issuer=null;this.asn1ThisUpdate=null;this.asn1NextUpdate=null;this.aRevokedCert=new Array()};this._initialize()};YAHOO.lang.extend(KJUR.asn1.x509.TBSCertList,KJUR.asn1.ASN1Object);KJUR.asn1.x509.CRLEntry=function(e){KJUR.asn1.x509.CRLEntry.superclass.constructor.call(this);var d=null,c=null,b=KJUR,a=b.asn1;this.setCertSerial=function(f){this.sn=new a.DERInteger(f)};this.setRevocationDate=function(f){this.time=new a.x509.Time(f)};this.getEncodedHex=function(){var f=new a.DERSequence({array:[this.sn,this.time]});this.TLV=f.getEncodedHex();return this.TLV};if(e!==undefined){if(e.time!==undefined){this.setRevocationDate(e.time)}if(e.sn!==undefined){this.setCertSerial(e.sn)}}};YAHOO.lang.extend(KJUR.asn1.x509.CRLEntry,KJUR.asn1.ASN1Object);KJUR.asn1.x509.X500Name=function(f){KJUR.asn1.x509.X500Name.superclass.constructor.call(this);this.asn1Array=new Array();var d=KJUR,c=d.asn1,e=c.x509,b=pemtohex;this.setByString=function(g){var k=g.split("/");k.shift();var j=[];for(var l=0;l<k.length;l++){if(k[l].match(/^[^=]+=.+$/)){j.push(k[l])}else{var h=j.length-1;j[h]=j[h]+"/"+k[l]}}for(var l=0;l<j.length;l++){this.asn1Array.push(new e.RDN({str:j[l]}))}};this.setByLdapString=function(g){var h=e.X500Name.ldapToCompat(g);this.setByString(h)};this.setByObject=function(i){for(var g in i){if(i.hasOwnProperty(g)){var h=new KJUR.asn1.x509.RDN({str:g+"="+i[g]});this.asn1Array?this.asn1Array.push(h):this.asn1Array=[h]}}};this.getEncodedHex=function(){if(typeof this.hTLV=="string"){return this.hTLV}var g=new c.DERSequence({array:this.asn1Array});this.hTLV=g.getEncodedHex();return this.hTLV};if(f!==undefined){if(f.str!==undefined){this.setByString(f.str)}else{if(f.ldapstr!==undefined){this.setByLdapString(f.ldapstr)}else{if(f.hex!==undefined){this.hTLV=f.hex}else{if(f.certissuer!==undefined){var a=new X509();a.readCertPEM(f.certissuer);this.hTLV=a.getIssuerHex()}else{if(f.certsubject!==undefined){var a=new X509();a.readCertPEM(f.certsubject);this.hTLV=a.getSubjectHex()}else{if(typeof f==="object"&&f.certsubject===undefined&&f.certissuer===undefined){this.setByObject(f)}}}}}}}};YAHOO.lang.extend(KJUR.asn1.x509.X500Name,KJUR.asn1.ASN1Object);KJUR.asn1.x509.X500Name.compatToLDAP=function(d){if(d.substr(0,1)!=="/"){throw"malformed input"}var b="";d=d.substr(1);var c=d.split("/");c.reverse();c=c.map(function(a){return a.replace(/,/,"\\,")});return c.join(",")};KJUR.asn1.x509.X500Name.onelineToLDAP=function(a){return KJUR.asn1.x509.X500Name.compatToLDAP(a)};KJUR.asn1.x509.X500Name.ldapToCompat=function(g){var c=g.split(",");var e=false;var b=[];for(var f=0;c.length>0;f++){var h=c.shift();if(e===true){var d=b.pop();var j=(d+","+h).replace(/\\,/g,",");b.push(j);e=false}else{b.push(h)}if(h.substr(-1,1)==="\\"){e=true}}b=b.map(function(a){return a.replace("/","\\/")});b.reverse();return"/"+b.join("/")};KJUR.asn1.x509.X500Name.ldapToOneline=function(a){return KJUR.asn1.x509.X500Name.ldapToCompat(a)};KJUR.asn1.x509.RDN=function(a){KJUR.asn1.x509.RDN.superclass.constructor.call(this);this.asn1Array=new Array();this.addByString=function(b){this.asn1Array.push(new KJUR.asn1.x509.AttributeTypeAndValue({str:b}))};this.addByMultiValuedString=function(d){var b=KJUR.asn1.x509.RDN.parseString(d);for(var c=0;c<b.length;c++){this.addByString(b[c])}};this.getEncodedHex=function(){var b=new KJUR.asn1.DERSet({array:this.asn1Array});this.TLV=b.getEncodedHex();return this.TLV};if(a!==undefined){if(a.str!==undefined){this.addByMultiValuedString(a.str)}}};YAHOO.lang.extend(KJUR.asn1.x509.RDN,KJUR.asn1.ASN1Object);KJUR.asn1.x509.RDN.parseString=function(m){var j=m.split(/\+/);var h=false;var c=[];for(var g=0;j.length>0;g++){var k=j.shift();if(h===true){var f=c.pop();var d=(f+"+"+k).replace(/\\\+/g,"+");c.push(d);h=false}else{c.push(k)}if(k.substr(-1,1)==="\\"){h=true}}var l=false;var b=[];for(var g=0;c.length>0;g++){var k=c.shift();if(l===true){var e=b.pop();if(k.match(/"$/)){var d=(e+"+"+k).replace(/^([^=]+)="(.*)"$/,"$1=$2");b.push(d);l=false}else{b.push(e+"+"+k)}}else{b.push(k)}if(k.match(/^[^=]+="/)){l=true}}return b};KJUR.asn1.x509.AttributeTypeAndValue=function(d){KJUR.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this);var f=null,e=null,a="utf8",c=KJUR,b=c.asn1;this.setByString=function(h){var g=h.match(/^([^=]+)=(.+)$/);if(g){this.setByAttrTypeAndValueStr(g[1],g[2])}else{throw"malformed attrTypeAndValueStr: "+h}};this.setByAttrTypeAndValueStr=function(i,h){this.typeObj=KJUR.asn1.x509.OID.atype2obj(i);var g=a;if(i=="C"){g="prn"}this.valueObj=this.getValueObj(g,h)};this.getValueObj=function(h,g){if(h=="utf8"){return new b.DERUTF8String({str:g})}if(h=="prn"){return new b.DERPrintableString({str:g})}if(h=="tel"){return new b.DERTeletexString({str:g})}if(h=="ia5"){return new b.DERIA5String({str:g})}throw"unsupported directory string type: type="+h+" value="+g};this.getEncodedHex=function(){var g=new b.DERSequence({array:[this.typeObj,this.valueObj]});this.TLV=g.getEncodedHex();return this.TLV};if(d!==undefined){if(d.str!==undefined){this.setByString(d.str)}}};YAHOO.lang.extend(KJUR.asn1.x509.AttributeTypeAndValue,KJUR.asn1.ASN1Object);KJUR.asn1.x509.SubjectPublicKeyInfo=function(f){KJUR.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);var l=null,k=null,a=KJUR,j=a.asn1,i=j.DERInteger,b=j.DERBitString,m=j.DERObjectIdentifier,e=j.DERSequence,h=j.ASN1Util.newObject,d=j.x509,o=d.AlgorithmIdentifier,g=a.crypto,n=g.ECDSA,c=g.DSA;this.getASN1Object=function(){if(this.asn1AlgId==null||this.asn1SubjPKey==null){throw"algId and/or subjPubKey not set"}var p=new e({array:[this.asn1AlgId,this.asn1SubjPKey]});return p};this.getEncodedHex=function(){var p=this.getASN1Object();this.hTLV=p.getEncodedHex();return this.hTLV};this.setPubKey=function(q){try{if(q instanceof RSAKey){var u=h({seq:[{"int":{bigint:q.n}},{"int":{"int":q.e}}]});var s=u.getEncodedHex();this.asn1AlgId=new o({name:"rsaEncryption"});this.asn1SubjPKey=new b({hex:"00"+s})}}catch(p){}try{if(q instanceof KJUR.crypto.ECDSA){var r=new m({name:q.curveName});this.asn1AlgId=new o({name:"ecPublicKey",asn1params:r});this.asn1SubjPKey=new b({hex:"00"+q.pubKeyHex})}}catch(p){}try{if(q instanceof KJUR.crypto.DSA){var r=new h({seq:[{"int":{bigint:q.p}},{"int":{bigint:q.q}},{"int":{bigint:q.g}}]});this.asn1AlgId=new o({name:"dsa",asn1params:r});var t=new i({bigint:q.y});this.asn1SubjPKey=new b({hex:"00"+t.getEncodedHex()})}}catch(p){}};if(f!==undefined){this.setPubKey(f)}};YAHOO.lang.extend(KJUR.asn1.x509.SubjectPublicKeyInfo,KJUR.asn1.ASN1Object);KJUR.asn1.x509.Time=function(f){KJUR.asn1.x509.Time.superclass.constructor.call(this);var e=null,a=null,d=KJUR,c=d.asn1,b=c.DERUTCTime,g=c.DERGeneralizedTime;this.setTimeParams=function(h){this.timeParams=h};this.getEncodedHex=function(){var h=null;if(this.timeParams!=null){if(this.type=="utc"){h=new b(this.timeParams)}else{h=new g(this.timeParams)}}else{if(this.type=="utc"){h=new b()}else{h=new g()}}this.TLV=h.getEncodedHex();return this.TLV};this.type="utc";if(f!==undefined){if(f.type!==undefined){this.type=f.type}else{if(f.str!==undefined){if(f.str.match(/^[0-9]{12}Z$/)){this.type="utc"}if(f.str.match(/^[0-9]{14}Z$/)){this.type="gen"}}}this.timeParams=f}};YAHOO.lang.extend(KJUR.asn1.x509.Time,KJUR.asn1.ASN1Object);KJUR.asn1.x509.AlgorithmIdentifier=function(d){KJUR.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this);this.nameAlg=null;this.asn1Alg=null;this.asn1Params=null;this.paramEmpty=false;var b=KJUR,a=b.asn1;this.getEncodedHex=function(){if(this.nameAlg===null&&this.asn1Alg===null){throw"algorithm not specified"}if(this.nameAlg!==null&&this.asn1Alg===null){this.asn1Alg=a.x509.OID.name2obj(this.nameAlg)}var e=[this.asn1Alg];if(this.asn1Params!==null){e.push(this.asn1Params)}var f=new a.DERSequence({array:e});this.hTLV=f.getEncodedHex();return this.hTLV};if(d!==undefined){if(d.name!==undefined){this.nameAlg=d.name}if(d.asn1params!==undefined){this.asn1Params=d.asn1params}if(d.paramempty!==undefined){this.paramEmpty=d.paramempty}}if(this.asn1Params===null&&this.paramEmpty===false&&this.nameAlg!==null){var c=this.nameAlg.toLowerCase();if(c.substr(-7,7)!=="withdsa"&&c.substr(-9,9)!=="withecdsa"){this.asn1Params=new a.DERNull()}}};YAHOO.lang.extend(KJUR.asn1.x509.AlgorithmIdentifier,KJUR.asn1.ASN1Object);KJUR.asn1.x509.GeneralName=function(e){KJUR.asn1.x509.GeneralName.superclass.constructor.call(this);var m=null,i=null,k={rfc822:"81",dns:"82",dn:"a4",uri:"86",ip:"87"},b=KJUR,g=b.asn1,f=g.DERSequence,j=g.DEROctetString,d=g.DERIA5String,c=g.DERTaggedObject,l=g.ASN1Object,a=g.x509.X500Name,h=pemtohex;this.explicit=false;this.setByParam=function(p){var r=null;var u=null;if(p===undefined){return}if(p.rfc822!==undefined){this.type="rfc822";u=new d({str:p[this.type]})}if(p.dns!==undefined){this.type="dns";u=new d({str:p[this.type]})}if(p.uri!==undefined){this.type="uri";u=new d({str:p[this.type]})}if(p.dn!==undefined){this.type="dn";this.explicit=true;if(typeof p.dn==="string"){u=new a({str:p.dn})}else{if(p.dn instanceof KJUR.asn1.x509.X500Name){u=p.dn}else{u=new a(p.dn)}}}if(p.ldapdn!==undefined){this.type="dn";this.explicit=true;u=new a({ldapstr:p.ldapdn})}if(p.certissuer!==undefined){this.type="dn";this.explicit=true;var o=p.certissuer;var w=null;if(o.match(/^[0-9A-Fa-f]+$/)){w==o}if(o.indexOf("-----BEGIN ")!=-1){w=h(o)}if(w==null){throw"certissuer param not cert"}var t=new X509();t.hex=w;var y=t.getIssuerHex();u=new l();u.hTLV=y}if(p.certsubj!==undefined){this.type="dn";this.explicit=true;var o=p.certsubj;var w=null;if(o.match(/^[0-9A-Fa-f]+$/)){w==o}if(o.indexOf("-----BEGIN ")!=-1){w=h(o)}if(w==null){throw"certsubj param not cert"}var t=new X509();t.hex=w;var y=t.getSubjectHex();u=new l();u.hTLV=y}if(p.ip!==undefined){this.type="ip";this.explicit=false;var q=p.ip;var s;var n="malformed IP address";if(q.match(/^[0-9.]+[.][0-9.]+$/)){s=intarystrtohex("["+q.split(".").join(",")+"]");if(s.length!==8){throw n}}else{if(q.match(/^[0-9A-Fa-f:]+:[0-9A-Fa-f:]+$/)){s=ipv6tohex(q)}else{if(q.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/)){s=q}else{throw n}}}u=new j({hex:s})}if(this.type==null){throw"unsupported type in params="+p}this.asn1Obj=new c({explicit:this.explicit,tag:k[this.type],obj:u})};this.getEncodedHex=function(){return this.asn1Obj.getEncodedHex()};if(e!==undefined){this.setByParam(e)}};YAHOO.lang.extend(KJUR.asn1.x509.GeneralName,KJUR.asn1.ASN1Object);KJUR.asn1.x509.GeneralNames=function(d){KJUR.asn1.x509.GeneralNames.superclass.constructor.call(this);var a=null,c=KJUR,b=c.asn1;this.setByParamArray=function(g){for(var e=0;e<g.length;e++){var f=new b.x509.GeneralName(g[e]);this.asn1Array.push(f)}};this.getEncodedHex=function(){var e=new b.DERSequence({array:this.asn1Array});return e.getEncodedHex()};this.asn1Array=new Array();if(typeof d!="undefined"){this.setByParamArray(d)}};YAHOO.lang.extend(KJUR.asn1.x509.GeneralNames,KJUR.asn1.ASN1Object);KJUR.asn1.x509.DistributionPointName=function(b){KJUR.asn1.x509.DistributionPointName.superclass.constructor.call(this);var h=null,e=null,a=null,g=null,d=KJUR,c=d.asn1,f=c.DERTaggedObject;this.getEncodedHex=function(){if(this.type!="full"){throw"currently type shall be 'full': "+this.type}this.asn1Obj=new f({explicit:false,tag:this.tag,obj:this.asn1V});this.hTLV=this.asn1Obj.getEncodedHex();return this.hTLV};if(b!==undefined){if(c.x509.GeneralNames.prototype.isPrototypeOf(b)){this.type="full";this.tag="a0";this.asn1V=b}else{throw"This class supports GeneralNames only as argument"}}};YAHOO.lang.extend(KJUR.asn1.x509.DistributionPointName,KJUR.asn1.ASN1Object);KJUR.asn1.x509.DistributionPoint=function(d){KJUR.asn1.x509.DistributionPoint.superclass.constructor.call(this);var a=null,c=KJUR,b=c.asn1;this.getEncodedHex=function(){var e=new b.DERSequence();if(this.asn1DP!=null){var f=new b.DERTaggedObject({explicit:true,tag:"a0",obj:this.asn1DP});e.appendASN1Object(f)}this.hTLV=e.getEncodedHex();return this.hTLV};if(d!==undefined){if(d.dpobj!==undefined){this.asn1DP=d.dpobj}}};YAHOO.lang.extend(KJUR.asn1.x509.DistributionPoint,KJUR.asn1.ASN1Object);KJUR.asn1.x509.OID=new function(a){this.atype2oidList={CN:"2.5.4.3",L:"2.5.4.7",ST:"2.5.4.8",O:"2.5.4.10",OU:"2.5.4.11",C:"2.5.4.6",STREET:"2.5.4.9",DC:"0.9.2342.19200300.100.1.25",UID:"0.9.2342.19200300.100.1.1",SN:"2.5.4.4",T:"2.5.4.12",DN:"2.5.4.49",E:"1.2.840.113549.1.9.1",description:"2.5.4.13",businessCategory:"2.5.4.15",postalCode:"2.5.4.17",serialNumber:"2.5.4.5",uniqueIdentifier:"2.5.4.45",organizationIdentifier:"2.5.4.97",jurisdictionOfIncorporationL:"1.3.6.1.4.1.311.60.2.1.1",jurisdictionOfIncorporationSP:"1.3.6.1.4.1.311.60.2.1.2",jurisdictionOfIncorporationC:"1.3.6.1.4.1.311.60.2.1.3"};this.name2oidList={sha1:"1.3.14.3.2.26",sha256:"2.16.840.1.101.3.4.2.1",sha384:"2.16.840.1.101.3.4.2.2",sha512:"2.16.840.1.101.3.4.2.3",sha224:"2.16.840.1.101.3.4.2.4",md5:"1.2.840.113549.2.5",md2:"1.3.14.7.2.2.1",ripemd160:"1.3.36.3.2.1",MD2withRSA:"1.2.840.113549.1.1.2",MD4withRSA:"1.2.840.113549.1.1.3",MD5withRSA:"1.2.840.113549.1.1.4",SHA1withRSA:"1.2.840.113549.1.1.5",SHA224withRSA:"1.2.840.113549.1.1.14",SHA256withRSA:"1.2.840.113549.1.1.11",SHA384withRSA:"1.2.840.113549.1.1.12",SHA512withRSA:"1.2.840.113549.1.1.13",SHA1withECDSA:"1.2.840.10045.4.1",SHA224withECDSA:"1.2.840.10045.4.3.1",SHA256withECDSA:"1.2.840.10045.4.3.2",SHA384withECDSA:"1.2.840.10045.4.3.3",SHA512withECDSA:"1.2.840.10045.4.3.4",dsa:"1.2.840.10040.4.1",SHA1withDSA:"1.2.840.10040.4.3",SHA224withDSA:"2.16.840.1.101.3.4.3.1",SHA256withDSA:"2.16.840.1.101.3.4.3.2",rsaEncryption:"1.2.840.113549.1.1.1",commonName:"2.5.4.3",countryName:"2.5.4.6",localityName:"2.5.4.7",stateOrProvinceName:"2.5.4.8",streetAddress:"2.5.4.9",organizationName:"2.5.4.10",organizationalUnitName:"2.5.4.11",domainComponent:"0.9.2342.19200300.100.1.25",userId:"0.9.2342.19200300.100.1.1",surname:"2.5.4.4",title:"2.5.4.12",distinguishedName:"2.5.4.49",emailAddress:"1.2.840.113549.1.9.1",description:"2.5.4.13",businessCategory:"2.5.4.15",postalCode:"2.5.4.17",uniqueIdentifier:"2.5.4.45",organizationIdentifier:"2.5.4.97",jurisdictionOfIncorporationL:"1.3.6.1.4.1.311.60.2.1.1",jurisdictionOfIncorporationSP:"1.3.6.1.4.1.311.60.2.1.2",jurisdictionOfIncorporationC:"1.3.6.1.4.1.311.60.2.1.3",subjectKeyIdentifier:"2.5.29.14",keyUsage:"2.5.29.15",subjectAltName:"2.5.29.17",issuerAltName:"2.5.29.18",basicConstraints:"2.5.29.19",nameConstraints:"2.5.29.30",cRLDistributionPoints:"2.5.29.31",certificatePolicies:"2.5.29.32",authorityKeyIdentifier:"2.5.29.35",policyConstraints:"2.5.29.36",extKeyUsage:"2.5.29.37",authorityInfoAccess:"1.3.6.1.5.5.7.1.1",ocsp:"1.3.6.1.5.5.7.48.1",caIssuers:"1.3.6.1.5.5.7.48.2",anyExtendedKeyUsage:"2.5.29.37.0",serverAuth:"1.3.6.1.5.5.7.3.1",clientAuth:"1.3.6.1.5.5.7.3.2",codeSigning:"1.3.6.1.5.5.7.3.3",emailProtection:"1.3.6.1.5.5.7.3.4",timeStamping:"1.3.6.1.5.5.7.3.8",ocspSigning:"1.3.6.1.5.5.7.3.9",ecPublicKey:"1.2.840.10045.2.1",secp256r1:"1.2.840.10045.3.1.7",secp256k1:"1.3.132.0.10",secp384r1:"1.3.132.0.34",pkcs5PBES2:"1.2.840.113549.1.5.13",pkcs5PBKDF2:"1.2.840.113549.1.5.12","des-EDE3-CBC":"1.2.840.113549.3.7",data:"1.2.840.113549.1.7.1","signed-data":"1.2.840.113549.1.7.2","enveloped-data":"1.2.840.113549.1.7.3","digested-data":"1.2.840.113549.1.7.5","encrypted-data":"1.2.840.113549.1.7.6","authenticated-data":"1.2.840.113549.1.9.16.1.2",tstinfo:"1.2.840.113549.1.9.16.1.4",extensionRequest:"1.2.840.113549.1.9.14",};this.objCache={};this.name2obj=function(b){if(typeof this.objCache[b]!="undefined"){return this.objCache[b]}if(typeof this.name2oidList[b]=="undefined"){throw"Name of ObjectIdentifier not defined: "+b}var c=this.name2oidList[b];var d=new KJUR.asn1.DERObjectIdentifier({oid:c});this.objCache[b]=d;return d};this.atype2obj=function(b){if(typeof this.objCache[b]!="undefined"){return this.objCache[b]}if(typeof this.atype2oidList[b]=="undefined"){throw"AttributeType name undefined: "+b}var c=this.atype2oidList[b];var d=new KJUR.asn1.DERObjectIdentifier({oid:c});this.objCache[b]=d;return d}};KJUR.asn1.x509.OID.oid2name=function(b){var c=KJUR.asn1.x509.OID.name2oidList;for(var a in c){if(c[a]==b){return a}}return""};KJUR.asn1.x509.OID.oid2atype=function(b){var c=KJUR.asn1.x509.OID.atype2oidList;for(var a in c){if(c[a]==b){return a}}return b};KJUR.asn1.x509.OID.name2oid=function(a){var b=KJUR.asn1.x509.OID.name2oidList;if(b[a]===undefined){return""}return b[a]};KJUR.asn1.x509.X509Util={};KJUR.asn1.x509.X509Util.newCertPEM=function(h){var g=KJUR.asn1.x509,b=g.TBSCertificate,a=g.Certificate;var f=new b();if(h.serial!==undefined){f.setSerialNumberByParam(h.serial)}else{throw"serial number undefined."}if(typeof h.sigalg.name==="string"){f.setSignatureAlgByParam(h.sigalg)}else{throw"unproper signature algorithm name"}if(h.issuer!==undefined){f.setIssuerByParam(h.issuer)}else{throw"issuer name undefined."}if(h.notbefore!==undefined){f.setNotBeforeByParam(h.notbefore)}else{throw"notbefore undefined."}if(h.notafter!==undefined){f.setNotAfterByParam(h.notafter)}else{throw"notafter undefined."}if(h.subject!==undefined){f.setSubjectByParam(h.subject)}else{throw"subject name undefined."}if(h.sbjpubkey!==undefined){f.setSubjectPublicKeyByGetKey(h.sbjpubkey)}else{throw"subject public key undefined."}if(h.ext!==undefined&&h.ext.length!==undefined){for(var d=0;d<h.ext.length;d++){for(key in h.ext[d]){f.appendExtensionByName(key,h.ext[d][key])}}}if(h.cakey===undefined&&h.sighex===undefined){throw"param cakey and sighex undefined."}var e=null;var c=null;if(h.cakey){if(h.cakey.isPrivate===true){e=h.cakey}else{e=KEYUTIL.getKey.apply(null,h.cakey)}c=new a({tbscertobj:f,prvkeyobj:e});c.sign()}if(h.sighex){c=new a({tbscertobj:f});c.setSignatureHex(h.sighex)}return c.getPEMString()}; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}if(typeof KJUR.asn1.cms=="undefined"||!KJUR.asn1.cms){KJUR.asn1.cms={}}KJUR.asn1.cms.Attribute=function(d){var a=[],c=KJUR,b=c.asn1;b.cms.Attribute.superclass.constructor.call(this);this.getEncodedHex=function(){var h,g,e;h=new b.DERObjectIdentifier({oid:this.attrTypeOid});g=new b.DERSet({array:this.valueList});try{g.getEncodedHex()}catch(f){throw"fail valueSet.getEncodedHex in Attribute(1)/"+f}e=new b.DERSequence({array:[h,g]});try{this.hTLV=e.getEncodedHex()}catch(f){throw"failed seq.getEncodedHex in Attribute(2)/"+f}return this.hTLV}};YAHOO.lang.extend(KJUR.asn1.cms.Attribute,KJUR.asn1.ASN1Object);KJUR.asn1.cms.ContentType=function(d){var c=KJUR,b=c.asn1;b.cms.ContentType.superclass.constructor.call(this);this.attrTypeOid="1.2.840.113549.1.9.3";var a=null;if(typeof d!="undefined"){var a=new b.DERObjectIdentifier(d);this.valueList=[a]}};YAHOO.lang.extend(KJUR.asn1.cms.ContentType,KJUR.asn1.cms.Attribute);KJUR.asn1.cms.MessageDigest=function(d){var b=KJUR,e=b.asn1,g=e.DEROctetString,i=e.cms;i.MessageDigest.superclass.constructor.call(this);this.attrTypeOid="1.2.840.113549.1.9.4";if(d!==undefined){if(d.eciObj instanceof i.EncapsulatedContentInfo&&typeof d.hashAlg==="string"){var h=d.eciObj.eContentValueHex;var c=d.hashAlg;var a=b.crypto.Util.hashHex(h,c);var f=new g({hex:a});f.getEncodedHex();this.valueList=[f]}else{var f=new g(d);f.getEncodedHex();this.valueList=[f]}}};YAHOO.lang.extend(KJUR.asn1.cms.MessageDigest,KJUR.asn1.cms.Attribute);KJUR.asn1.cms.SigningTime=function(e){var d=KJUR,c=d.asn1;c.cms.SigningTime.superclass.constructor.call(this);this.attrTypeOid="1.2.840.113549.1.9.5";if(e!==undefined){var a=new c.x509.Time(e);try{a.getEncodedHex()}catch(b){throw"SigningTime.getEncodedHex() failed/"+b}this.valueList=[a]}};YAHOO.lang.extend(KJUR.asn1.cms.SigningTime,KJUR.asn1.cms.Attribute);KJUR.asn1.cms.SigningCertificate=function(f){var c=KJUR,b=c.asn1,a=b.DERSequence,e=b.cms,d=c.crypto;e.SigningCertificate.superclass.constructor.call(this);this.attrTypeOid="1.2.840.113549.1.9.16.2.12";this.setCerts=function(n){var l=[];for(var k=0;k<n.length;k++){var h=pemtohex(n[k]);var g=c.crypto.Util.hashHex(h,"sha1");var o=new b.DEROctetString({hex:g});o.getEncodedHex();var m=new e.IssuerAndSerialNumber({cert:n[k]});m.getEncodedHex();var p=new a({array:[o,m]});p.getEncodedHex();l.push(p)}var j=new a({array:l});j.getEncodedHex();this.valueList=[j]};if(f!==undefined){if(typeof f.array=="object"){this.setCerts(f.array)}}};YAHOO.lang.extend(KJUR.asn1.cms.SigningCertificate,KJUR.asn1.cms.Attribute);KJUR.asn1.cms.SigningCertificateV2=function(h){var d=KJUR,c=d.asn1,b=c.DERSequence,g=c.x509,f=c.cms,e=d.crypto;f.SigningCertificateV2.superclass.constructor.call(this);this.attrTypeOid="1.2.840.113549.1.9.16.2.47";this.setCerts=function(r,k){var p=[];for(var n=0;n<r.length;n++){var l=pemtohex(r[n]);var t=[];if(k!=="sha256"){t.push(new g.AlgorithmIdentifier({name:k}))}var j=e.Util.hashHex(l,k);var s=new c.DEROctetString({hex:j});s.getEncodedHex();t.push(s);var o=new f.IssuerAndSerialNumber({cert:r[n]});o.getEncodedHex();t.push(o);var q=new b({array:t});q.getEncodedHex();p.push(q)}var m=new b({array:p});m.getEncodedHex();this.valueList=[m]};if(h!==undefined){if(typeof h.array=="object"){var a="sha256";if(typeof h.hashAlg=="string"){a=h.hashAlg}this.setCerts(h.array,a)}}};YAHOO.lang.extend(KJUR.asn1.cms.SigningCertificateV2,KJUR.asn1.cms.Attribute);KJUR.asn1.cms.IssuerAndSerialNumber=function(e){var b=KJUR,g=b.asn1,f=g.DERInteger,i=g.cms,d=g.x509,a=d.X500Name,c=X509;i.IssuerAndSerialNumber.superclass.constructor.call(this);var j=null;var h=null;this.setByCertPEM=function(n){var l=pemtohex(n);var k=new c();k.hex=l;var o=k.getIssuerHex();this.dIssuer=new a();this.dIssuer.hTLV=o;var m=k.getSerialNumberHex();this.dSerial=new f({hex:m})};this.getEncodedHex=function(){var k=new g.DERSequence({array:[this.dIssuer,this.dSerial]});this.hTLV=k.getEncodedHex();return this.hTLV};if(e!==undefined){if(typeof e=="string"&&e.indexOf("-----BEGIN ")!=-1){this.setByCertPEM(e)}if(e.issuer&&e.serial){if(e.issuer instanceof a){this.dIssuer=e.issuer}else{this.dIssuer=new a(e.issuer)}if(e.serial instanceof f){this.dSerial=e.serial}else{this.dSerial=new f(e.serial)}}if(typeof e.cert=="string"){this.setByCertPEM(e.cert)}}};YAHOO.lang.extend(KJUR.asn1.cms.IssuerAndSerialNumber,KJUR.asn1.ASN1Object);KJUR.asn1.cms.AttributeList=function(d){var b=KJUR,a=b.asn1,c=a.cms;c.AttributeList.superclass.constructor.call(this);this.list=new Array();this.sortFlag=true;this.add=function(e){if(e instanceof c.Attribute){this.list.push(e)}};this.length=function(){return this.list.length};this.clear=function(){this.list=new Array();this.hTLV=null;this.hV=null};this.getEncodedHex=function(){if(typeof this.hTLV=="string"){return this.hTLV}var e=new a.DERSet({array:this.list,sortflag:this.sortFlag});this.hTLV=e.getEncodedHex();return this.hTLV};if(d!==undefined){if(typeof d.sortflag!="undefined"&&d.sortflag==false){this.sortFlag=false}}};YAHOO.lang.extend(KJUR.asn1.cms.AttributeList,KJUR.asn1.ASN1Object);KJUR.asn1.cms.SignerInfo=function(e){var a=KJUR,h=a.asn1,b=h.DERTaggedObject,n=h.cms,j=n.AttributeList,g=n.ContentType,k=n.EncapsulatedContentInfo,c=n.MessageDigest,l=n.SignedData,d=h.x509,m=d.AlgorithmIdentifier,f=a.crypto,i=KEYUTIL;n.SignerInfo.superclass.constructor.call(this);this.dCMSVersion=new h.DERInteger({"int":1});this.dSignerIdentifier=null;this.dDigestAlgorithm=null;this.dSignedAttrs=new j();this.dSigAlg=null;this.dSig=null;this.dUnsignedAttrs=new j();this.setSignerIdentifier=function(p){if(typeof p=="string"&&p.indexOf("CERTIFICATE")!=-1&&p.indexOf("BEGIN")!=-1&&p.indexOf("END")!=-1){var o=p;this.dSignerIdentifier=new n.IssuerAndSerialNumber({cert:p})}};this.setForContentAndHash=function(o){if(o!==undefined){if(o.eciObj instanceof k){this.dSignedAttrs.add(new g({oid:"1.2.840.113549.1.7.1"}));this.dSignedAttrs.add(new c({eciObj:o.eciObj,hashAlg:o.hashAlg}))}if(o.sdObj!==undefined&&o.sdObj instanceof l){if(o.sdObj.digestAlgNameList.join(":").indexOf(o.hashAlg)==-1){o.sdObj.digestAlgNameList.push(o.hashAlg)}}if(typeof o.hashAlg=="string"){this.dDigestAlgorithm=new m({name:o.hashAlg})}}};this.sign=function(t,p){this.dSigAlg=new m({name:p});var q=this.dSignedAttrs.getEncodedHex();var o=i.getKey(t);var s=new f.Signature({alg:p});s.init(o);s.updateHex(q);var r=s.sign();this.dSig=new h.DEROctetString({hex:r})};this.addUnsigned=function(o){this.hTLV=null;this.dUnsignedAttrs.hTLV=null;this.dUnsignedAttrs.add(o)};this.getEncodedHex=function(){if(this.dSignedAttrs instanceof j&&this.dSignedAttrs.length()==0){throw"SignedAttrs length = 0 (empty)"}var o=new b({obj:this.dSignedAttrs,tag:"a0",explicit:false});var r=null;if(this.dUnsignedAttrs.length()>0){r=new b({obj:this.dUnsignedAttrs,tag:"a1",explicit:false})}var q=[this.dCMSVersion,this.dSignerIdentifier,this.dDigestAlgorithm,o,this.dSigAlg,this.dSig,];if(r!=null){q.push(r)}var p=new h.DERSequence({array:q});this.hTLV=p.getEncodedHex();return this.hTLV}};YAHOO.lang.extend(KJUR.asn1.cms.SignerInfo,KJUR.asn1.ASN1Object);KJUR.asn1.cms.EncapsulatedContentInfo=function(g){var c=KJUR,b=c.asn1,e=b.DERTaggedObject,a=b.DERSequence,h=b.DERObjectIdentifier,d=b.DEROctetString,f=b.cms;f.EncapsulatedContentInfo.superclass.constructor.call(this);this.dEContentType=new h({name:"data"});this.dEContent=null;this.isDetached=false;this.eContentValueHex=null;this.setContentType=function(i){if(i.match(/^[0-2][.][0-9.]+$/)){this.dEContentType=new h({oid:i})}else{this.dEContentType=new h({name:i})}};this.setContentValue=function(i){if(i!==undefined){if(typeof i.hex=="string"){this.eContentValueHex=i.hex}else{if(typeof i.str=="string"){this.eContentValueHex=utf8tohex(i.str)}}}};this.setContentValueHex=function(i){this.eContentValueHex=i};this.setContentValueStr=function(i){this.eContentValueHex=utf8tohex(i)};this.getEncodedHex=function(){if(typeof this.eContentValueHex!="string"){throw"eContentValue not yet set"}var k=new d({hex:this.eContentValueHex});this.dEContent=new e({obj:k,tag:"a0",explicit:true});var i=[this.dEContentType];if(!this.isDetached){i.push(this.dEContent)}var j=new a({array:i});this.hTLV=j.getEncodedHex();return this.hTLV}};YAHOO.lang.extend(KJUR.asn1.cms.EncapsulatedContentInfo,KJUR.asn1.ASN1Object);KJUR.asn1.cms.ContentInfo=function(f){var c=KJUR,b=c.asn1,d=b.DERTaggedObject,a=b.DERSequence,e=b.x509;KJUR.asn1.cms.ContentInfo.superclass.constructor.call(this);this.dContentType=null;this.dContent=null;this.setContentType=function(g){if(typeof g=="string"){this.dContentType=e.OID.name2obj(g)}};this.getEncodedHex=function(){var h=new d({obj:this.dContent,tag:"a0",explicit:true});var g=new a({array:[this.dContentType,h]});this.hTLV=g.getEncodedHex();return this.hTLV};if(f!==undefined){if(f.type){this.setContentType(f.type)}if(f.obj&&f.obj instanceof b.ASN1Object){this.dContent=f.obj}}};YAHOO.lang.extend(KJUR.asn1.cms.ContentInfo,KJUR.asn1.ASN1Object);KJUR.asn1.cms.SignedData=function(e){var a=KJUR,h=a.asn1,j=h.ASN1Object,g=h.DERInteger,m=h.DERSet,f=h.DERSequence,b=h.DERTaggedObject,l=h.cms,i=l.EncapsulatedContentInfo,d=l.SignerInfo,n=l.ContentInfo,c=h.x509,k=c.AlgorithmIdentifier;KJUR.asn1.cms.SignedData.superclass.constructor.call(this);this.dCMSVersion=new g({"int":1});this.dDigestAlgs=null;this.digestAlgNameList=[];this.dEncapContentInfo=new i();this.dCerts=null;this.certificateList=[];this.crlList=[];this.signerInfoList=[new d()];this.addCertificatesByPEM=function(p){var q=pemtohex(p);var r=new j();r.hTLV=q;this.certificateList.push(r)};this.getEncodedHex=function(){if(typeof this.hTLV=="string"){return this.hTLV}if(this.dDigestAlgs==null){var u=[];for(var t=0;t<this.digestAlgNameList.length;t++){var s=this.digestAlgNameList[t];var w=new k({name:s});u.push(w)}this.dDigestAlgs=new m({array:u})}var p=[this.dCMSVersion,this.dDigestAlgs,this.dEncapContentInfo];if(this.dCerts==null){if(this.certificateList.length>0){var v=new m({array:this.certificateList});this.dCerts=new b({obj:v,tag:"a0",explicit:false})}}if(this.dCerts!=null){p.push(this.dCerts)}var r=new m({array:this.signerInfoList});p.push(r);var q=new f({array:p});this.hTLV=q.getEncodedHex();return this.hTLV};this.getContentInfo=function(){this.getEncodedHex();var o=new n({type:"signed-data",obj:this});return o};this.getContentInfoEncodedHex=function(){var o=this.getContentInfo();var p=o.getEncodedHex();return p};this.getPEM=function(){return hextopem(this.getContentInfoEncodedHex(),"CMS")}};YAHOO.lang.extend(KJUR.asn1.cms.SignedData,KJUR.asn1.ASN1Object);KJUR.asn1.cms.CMSUtil=new function(){};KJUR.asn1.cms.CMSUtil.newSignedData=function(d){var b=KJUR,j=b.asn1,q=j.cms,f=q.SignerInfo,n=q.SignedData,o=q.SigningTime,a=q.SigningCertificate,p=q.SigningCertificateV2,c=j.cades,e=c.SignaturePolicyIdentifier;var m=new n();m.dEncapContentInfo.setContentValue(d.content);if(typeof d.detached=="boolean"){m.dEncapContentInfo.isDetached=d.detached}if(typeof d.certs=="object"){for(var h=0;h<d.certs.length;h++){m.addCertificatesByPEM(d.certs[h])}}m.signerInfoList=[];for(var h=0;h<d.signerInfos.length;h++){var k=d.signerInfos[h];var g=new f();g.setSignerIdentifier(k.signerCert);g.setForContentAndHash({sdObj:m,eciObj:m.dEncapContentInfo,hashAlg:k.hashAlg});for(attrName in k.sAttr){var r=k.sAttr[attrName];if(attrName=="SigningTime"){var l=new o(r);g.dSignedAttrs.add(l)}if(attrName=="SigningCertificate"){var l=new a(r);g.dSignedAttrs.add(l)}if(attrName=="SigningCertificateV2"){var l=new p(r);g.dSignedAttrs.add(l)}if(attrName=="SignaturePolicyIdentifier"){var l=new e(r);g.dSignedAttrs.add(l)}}g.sign(k.signerPrvKey,k.sigAlg);m.signerInfoList.push(g)}return m};KJUR.asn1.cms.CMSUtil.verifySignedData=function(n){var C=KJUR,p=C.asn1,s=p.cms,D=s.SignerInfo,q=s.SignedData,y=s.SigningTime,b=s.SigningCertificate,d=s.SigningCertificateV2,A=p.cades,u=A.SignaturePolicyIdentifier,i=C.lang.String.isHex,v=ASN1HEX,h=v.getVbyList,a=v.getTLVbyList,t=v.getIdxbyList,z=v.getChildIdx,c=v.getTLV,B=v.oidname,j=C.crypto.Util.hashHex;if(n.cms===undefined&&!i(n.cms)){}var E=n.cms;var g=function(J,H){var G;for(var I=3;I<6;I++){G=t(J,0,[1,0,I]);if(G!==undefined){var F=J.substr(G,2);if(F==="a0"){H.certsIdx=G}if(F==="a1"){H.revinfosIdx=G}if(F==="31"){H.signerinfosIdx=G}}}};var l=function(I,F){var H=F.signerinfosIdx;if(H===undefined){return}var L=z(I,H);F.signerInfoIdxList=L;for(var G=0;G<L.length;G++){var K=L[G];var J={idx:K};k(I,J);F.signerInfos.push(J)}};var k=function(I,J){var F=J.idx;J.signerid_issuer1=a(I,F,[1,0],"30");J.signerid_serial1=h(I,F,[1,1],"02");J.hashalg=B(h(I,F,[2,0],"06"));var H=t(I,F,[3],"a0");J.idxSignedAttrs=H;f(I,J,H);var G=z(I,F);var K=G.length;if(K<6){throw"malformed SignerInfo"}J.sigalg=B(h(I,F,[K-2,0],"06"));J.sigval=h(I,F,[K-1],"04")};var f=function(L,M,F){var J=z(L,F);M.signedAttrIdxList=J;for(var K=0;K<J.length;K++){var I=J[K];var G=h(L,I,[0],"06");var H;if(G==="2a864886f70d010905"){H=hextoutf8(h(L,I,[1,0]));M.saSigningTime=H}else{if(G==="2a864886f70d010904"){H=h(L,I,[1,0],"04");M.saMessageDigest=H}}}};var w=function(G,F){if(h(G,0,[0],"06")!=="2a864886f70d010702"){return F}F.cmsType="signedData";F.econtent=h(G,0,[1,0,2,1,0]);g(G,F);F.signerInfos=[];l(G,F)};var o=function(J,F){var G=F.parse.signerInfos;var L=G.length;var K=true;for(var I=0;I<L;I++){var H=G[I];e(J,F,H,I);if(!H.isValid){K=false}}F.isValid=K};var x=function(F,Q,J,P){var N=Q.parse.certsIdx;var H;if(Q.certs===undefined){H=[];Q.certkeys=[];var K=z(F,N);for(var I=0;I<K.length;I++){var M=c(F,K[I]);var O=new X509();O.readCertHex(M);H[I]=O;Q.certkeys[I]=O.getPublicKey()}Q.certs=H}else{H=Q.certs}Q.cccc=H.length;Q.cccci=K.length;for(var I=0;I<H.length;I++){var L=O.getIssuerHex();var G=O.getSerialNumberHex();if(J.signerid_issuer1===L&&J.signerid_serial1===G){J.certkey_idx=I}}};var e=function(F,R,I,N){I.verifyDetail={};var Q=I.verifyDetail;var K=R.parse.econtent;var G=I.hashalg;var L=I.saMessageDigest;Q.validMessageDigest=false;if(j(K,G)===L){Q.validMessageDigest=true}x(F,R,I,N);Q.validSignatureValue=false;var H=I.sigalg;var M="31"+c(F,I.idxSignedAttrs).substr(2);I.signedattrshex=M;var J=R.certs[I.certkey_idx].getPublicKey();var P=new KJUR.crypto.Signature({alg:H});P.init(J);P.updateHex(M);var O=P.verify(I.sigval);Q.validSignatureValue_isValid=O;if(O===true){Q.validSignatureValue=true}I.isValid=false;if(Q.validMessageDigest&&Q.validSignatureValue){I.isValid=true}};var m=function(){};var r={isValid:false,parse:{}};w(E,r.parse);o(E,r);return r}; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}if(typeof KJUR.asn1.tsp=="undefined"||!KJUR.asn1.tsp){KJUR.asn1.tsp={}}KJUR.asn1.tsp.Accuracy=function(f){var c=KJUR,b=c.asn1,e=b.DERInteger,a=b.DERSequence,d=b.DERTaggedObject;b.tsp.Accuracy.superclass.constructor.call(this);this.seconds=null;this.millis=null;this.micros=null;this.getEncodedHex=function(){var i=null;var k=null;var m=null;var g=[];if(this.seconds!=null){i=new e({"int":this.seconds});g.push(i)}if(this.millis!=null){var l=new e({"int":this.millis});k=new d({obj:l,tag:"80",explicit:false});g.push(k)}if(this.micros!=null){var j=new e({"int":this.micros});m=new d({obj:j,tag:"81",explicit:false});g.push(m)}var h=new a({array:g});this.hTLV=h.getEncodedHex();return this.hTLV};if(f!==undefined){if(typeof f.seconds=="number"){this.seconds=f.seconds}if(typeof f.millis=="number"){this.millis=f.millis}if(typeof f.micros=="number"){this.micros=f.micros}}};YAHOO.lang.extend(KJUR.asn1.tsp.Accuracy,KJUR.asn1.ASN1Object);KJUR.asn1.tsp.MessageImprint=function(g){var c=KJUR,b=c.asn1,a=b.DERSequence,d=b.DEROctetString,f=b.x509,e=f.AlgorithmIdentifier;b.tsp.MessageImprint.superclass.constructor.call(this);this.dHashAlg=null;this.dHashValue=null;this.getEncodedHex=function(){if(typeof this.hTLV=="string"){return this.hTLV}var h=new a({array:[this.dHashAlg,this.dHashValue]});return h.getEncodedHex()};if(g!==undefined){if(typeof g.hashAlg=="string"){this.dHashAlg=new e({name:g.hashAlg})}if(typeof g.hashValue=="string"){this.dHashValue=new d({hex:g.hashValue})}}};YAHOO.lang.extend(KJUR.asn1.tsp.MessageImprint,KJUR.asn1.ASN1Object);KJUR.asn1.tsp.TimeStampReq=function(c){var a=KJUR,f=a.asn1,d=f.DERSequence,e=f.DERInteger,g=f.DERBoolean,i=f.DERObjectIdentifier,h=f.tsp,b=h.MessageImprint;h.TimeStampReq.superclass.constructor.call(this);this.dVersion=new e({"int":1});this.dMessageImprint=null;this.dPolicy=null;this.dNonce=null;this.certReq=true;this.setMessageImprint=function(j){if(j instanceof b){this.dMessageImprint=j;return}if(typeof j=="object"){this.dMessageImprint=new b(j)}};this.getEncodedHex=function(){if(this.dMessageImprint==null){throw"messageImprint shall be specified"}var j=[this.dVersion,this.dMessageImprint];if(this.dPolicy!=null){j.push(this.dPolicy)}if(this.dNonce!=null){j.push(this.dNonce)}if(this.certReq){j.push(new g())}var k=new d({array:j});this.hTLV=k.getEncodedHex();return this.hTLV};if(c!==undefined){if(typeof c.mi=="object"){this.setMessageImprint(c.mi)}if(typeof c.policy=="object"){this.dPolicy=new i(c.policy)}if(typeof c.nonce=="object"){this.dNonce=new e(c.nonce)}if(typeof c.certreq=="boolean"){this.certReq=c.certreq}}};YAHOO.lang.extend(KJUR.asn1.tsp.TimeStampReq,KJUR.asn1.ASN1Object);KJUR.asn1.tsp.TSTInfo=function(e){var c=KJUR,i=c.asn1,f=i.DERSequence,h=i.DERInteger,k=i.DERBoolean,g=i.DERGeneralizedTime,l=i.DERObjectIdentifier,j=i.tsp,d=j.MessageImprint,b=j.Accuracy,a=i.x509.X500Name;j.TSTInfo.superclass.constructor.call(this);this.dVersion=new h({"int":1});this.dPolicy=null;this.dMessageImprint=null;this.dSerialNumber=null;this.dGenTime=null;this.dAccuracy=null;this.dOrdering=null;this.dNonce=null;this.dTsa=null;this.getEncodedHex=function(){var m=[this.dVersion];if(this.dPolicy==null){throw"policy shall be specified."}m.push(this.dPolicy);if(this.dMessageImprint==null){throw"messageImprint shall be specified."}m.push(this.dMessageImprint);if(this.dSerialNumber==null){throw"serialNumber shall be specified."}m.push(this.dSerialNumber);if(this.dGenTime==null){throw"genTime shall be specified."}m.push(this.dGenTime);if(this.dAccuracy!=null){m.push(this.dAccuracy)}if(this.dOrdering!=null){m.push(this.dOrdering)}if(this.dNonce!=null){m.push(this.dNonce)}if(this.dTsa!=null){m.push(this.dTsa)}var n=new f({array:m});this.hTLV=n.getEncodedHex();return this.hTLV};if(e!==undefined){if(typeof e.policy=="string"){if(!e.policy.match(/^[0-9.]+$/)){throw"policy shall be oid like 0.1.4.134"}this.dPolicy=new l({oid:e.policy})}if(e.messageImprint!==undefined){this.dMessageImprint=new d(e.messageImprint)}if(e.serialNumber!==undefined){this.dSerialNumber=new h(e.serialNumber)}if(e.genTime!==undefined){this.dGenTime=new g(e.genTime)}if(e.accuracy!==undefined){this.dAccuracy=new b(e.accuracy)}if(e.ordering!==undefined&&e.ordering==true){this.dOrdering=new k()}if(e.nonce!==undefined){this.dNonce=new h(e.nonce)}if(e.tsa!==undefined){this.dTsa=new a(e.tsa)}}};YAHOO.lang.extend(KJUR.asn1.tsp.TSTInfo,KJUR.asn1.ASN1Object);KJUR.asn1.tsp.TimeStampResp=function(g){var e=KJUR,d=e.asn1,c=d.DERSequence,f=d.ASN1Object,a=d.tsp,b=a.PKIStatusInfo;a.TimeStampResp.superclass.constructor.call(this);this.dStatus=null;this.dTST=null;this.getEncodedHex=function(){if(this.dStatus==null){throw"status shall be specified"}var h=[this.dStatus];if(this.dTST!=null){h.push(this.dTST)}var i=new c({array:h});this.hTLV=i.getEncodedHex();return this.hTLV};if(g!==undefined){if(typeof g.status=="object"){this.dStatus=new b(g.status)}if(g.tst!==undefined&&g.tst instanceof f){this.dTST=g.tst.getContentInfo()}}};YAHOO.lang.extend(KJUR.asn1.tsp.TimeStampResp,KJUR.asn1.ASN1Object);KJUR.asn1.tsp.PKIStatusInfo=function(h){var g=KJUR,f=g.asn1,e=f.DERSequence,a=f.tsp,d=a.PKIStatus,c=a.PKIFreeText,b=a.PKIFailureInfo;a.PKIStatusInfo.superclass.constructor.call(this);this.dStatus=null;this.dStatusString=null;this.dFailureInfo=null;this.getEncodedHex=function(){if(this.dStatus==null){throw"status shall be specified"}var i=[this.dStatus];if(this.dStatusString!=null){i.push(this.dStatusString)}if(this.dFailureInfo!=null){i.push(this.dFailureInfo)}var j=new e({array:i});this.hTLV=j.getEncodedHex();return this.hTLV};if(h!==undefined){if(typeof h.status=="object"){this.dStatus=new d(h.status)}if(typeof h.statstr=="object"){this.dStatusString=new c({array:h.statstr})}if(typeof h.failinfo=="object"){this.dFailureInfo=new b(h.failinfo)}}};YAHOO.lang.extend(KJUR.asn1.tsp.PKIStatusInfo,KJUR.asn1.ASN1Object);KJUR.asn1.tsp.PKIStatus=function(h){var d=KJUR,c=d.asn1,g=c.DERInteger,a=c.tsp,b=a.PKIStatus;a.PKIStatus.superclass.constructor.call(this);var f=null;this.getEncodedHex=function(){this.hTLV=this.dStatus.getEncodedHex();return this.hTLV};if(h!==undefined){if(h.name!==undefined){var e=b.valueList;if(e[h.name]===undefined){throw"name undefined: "+h.name}this.dStatus=new g({"int":e[h.name]})}else{this.dStatus=new g(h)}}};YAHOO.lang.extend(KJUR.asn1.tsp.PKIStatus,KJUR.asn1.ASN1Object);KJUR.asn1.tsp.PKIStatus.valueList={granted:0,grantedWithMods:1,rejection:2,waiting:3,revocationWarning:4,revocationNotification:5};KJUR.asn1.tsp.PKIFreeText=function(f){var e=KJUR,d=e.asn1,b=d.DERSequence,c=d.DERUTF8String,a=d.tsp;a.PKIFreeText.superclass.constructor.call(this);this.textList=[];this.getEncodedHex=function(){var g=[];for(var j=0;j<this.textList.length;j++){g.push(new c({str:this.textList[j]}))}var h=new b({array:g});this.hTLV=h.getEncodedHex();return this.hTLV};if(f!==undefined){if(typeof f.array=="object"){this.textList=f.array}}};YAHOO.lang.extend(KJUR.asn1.tsp.PKIFreeText,KJUR.asn1.ASN1Object);KJUR.asn1.tsp.PKIFailureInfo=function(g){var d=KJUR,c=d.asn1,f=c.DERBitString,a=c.tsp,b=a.PKIFailureInfo;b.superclass.constructor.call(this);this.value=null;this.getEncodedHex=function(){if(this.value==null){throw"value shall be specified"}var h=new Number(this.value).toString(2);var i=new f();i.setByBinaryString(h);this.hTLV=i.getEncodedHex();return this.hTLV};if(g!==undefined){if(typeof g.name=="string"){var e=b.valueList;if(e[g.name]===undefined){throw"name undefined: "+g.name}this.value=e[g.name]}else{if(typeof g["int"]=="number"){this.value=g["int"]}}}};YAHOO.lang.extend(KJUR.asn1.tsp.PKIFailureInfo,KJUR.asn1.ASN1Object);KJUR.asn1.tsp.PKIFailureInfo.valueList={badAlg:0,badRequest:2,badDataFormat:5,timeNotAvailable:14,unacceptedPolicy:15,unacceptedExtension:16,addInfoNotAvailable:17,systemFailure:25};KJUR.asn1.tsp.AbstractTSAAdapter=function(a){this.getTSTHex=function(c,b){throw"not implemented yet"}};KJUR.asn1.tsp.SimpleTSAAdapter=function(e){var d=KJUR,c=d.asn1,a=c.tsp,b=d.crypto.Util.hashHex;a.SimpleTSAAdapter.superclass.constructor.call(this);this.params=null;this.serial=0;this.getTSTHex=function(g,f){var i=b(g,f);this.params.tstInfo.messageImprint={hashAlg:f,hashValue:i};this.params.tstInfo.serialNumber={"int":this.serial++};var h=Math.floor(Math.random()*1000000000);this.params.tstInfo.nonce={"int":h};var j=a.TSPUtil.newTimeStampToken(this.params);return j.getContentInfoEncodedHex()};if(e!==undefined){this.params=e}};YAHOO.lang.extend(KJUR.asn1.tsp.SimpleTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter);KJUR.asn1.tsp.FixedTSAAdapter=function(e){var d=KJUR,c=d.asn1,a=c.tsp,b=d.crypto.Util.hashHex;a.FixedTSAAdapter.superclass.constructor.call(this);this.params=null;this.getTSTHex=function(g,f){var h=b(g,f);this.params.tstInfo.messageImprint={hashAlg:f,hashValue:h};var i=a.TSPUtil.newTimeStampToken(this.params);return i.getContentInfoEncodedHex()};if(e!==undefined){this.params=e}};YAHOO.lang.extend(KJUR.asn1.tsp.FixedTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter);KJUR.asn1.tsp.TSPUtil=new function(){};KJUR.asn1.tsp.TSPUtil.newTimeStampToken=function(c){var b=KJUR,h=b.asn1,m=h.cms,k=h.tsp,a=h.tsp.TSTInfo;var j=new m.SignedData();var g=new a(c.tstInfo);var f=g.getEncodedHex();j.dEncapContentInfo.setContentValue({hex:f});j.dEncapContentInfo.setContentType("tstinfo");if(typeof c.certs=="object"){for(var e=0;e<c.certs.length;e++){j.addCertificatesByPEM(c.certs[e])}}var d=j.signerInfoList[0];d.setSignerIdentifier(c.signerCert);d.setForContentAndHash({sdObj:j,eciObj:j.dEncapContentInfo,hashAlg:c.hashAlg});var l=new m.SigningCertificate({array:[c.signerCert]});d.dSignedAttrs.add(l);d.sign(c.signerPrvKey,c.sigAlg);return j};KJUR.asn1.tsp.TSPUtil.parseTimeStampReq=function(m){var l=ASN1HEX;var h=l.getChildIdx;var f=l.getV;var b=l.getTLV;var j={};j.certreq=false;var a=h(m,0);if(a.length<2){throw"TimeStampReq must have at least 2 items"}var e=b(m,a[1]);j.mi=KJUR.asn1.tsp.TSPUtil.parseMessageImprint(e);for(var d=2;d<a.length;d++){var g=a[d];var k=m.substr(g,2);if(k=="06"){var c=f(m,g);j.policy=l.hextooidstr(c)}if(k=="02"){j.nonce=f(m,g)}if(k=="01"){j.certreq=true}}return j};KJUR.asn1.tsp.TSPUtil.parseMessageImprint=function(c){var m=ASN1HEX;var j=m.getChildIdx;var i=m.getV;var g=m.getIdxbyList;var k={};if(c.substr(0,2)!="30"){throw"head of messageImprint hex shall be '30'"}var a=j(c,0);var l=g(c,0,[0,0]);var e=i(c,l);var d=m.hextooidstr(e);var h=KJUR.asn1.x509.OID.oid2name(d);if(h==""){throw"hashAlg name undefined: "+d}var b=h;var f=g(c,0,[1]);k.hashAlg=b;k.hashValue=i(c,f);return k}; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}if(typeof KJUR.asn1.cades=="undefined"||!KJUR.asn1.cades){KJUR.asn1.cades={}}KJUR.asn1.cades.SignaturePolicyIdentifier=function(f){var b=KJUR,h=b.asn1,i=h.DERObjectIdentifier,g=h.DERSequence,e=h.cades,c=e.OtherHashAlgAndValue;e.SignaturePolicyIdentifier.superclass.constructor.call(this);this.attrTypeOid="1.2.840.113549.1.9.16.2.15";if(f!==undefined){if(typeof f.oid=="string"&&typeof f.hash=="object"){var d=new i({oid:f.oid});var a=new c(f.hash);var j=new g({array:[d,a]});this.valueList=[j]}}};YAHOO.lang.extend(KJUR.asn1.cades.SignaturePolicyIdentifier,KJUR.asn1.cms.Attribute);KJUR.asn1.cades.OtherHashAlgAndValue=function(e){var a=KJUR,g=a.asn1,f=g.DERSequence,h=g.DEROctetString,d=g.x509,i=d.AlgorithmIdentifier,c=g.cades,b=c.OtherHashAlgAndValue;b.superclass.constructor.call(this);this.dAlg=null;this.dHash=null;this.getEncodedHex=function(){var j=new f({array:[this.dAlg,this.dHash]});this.hTLV=j.getEncodedHex();return this.hTLV};if(e!==undefined){if(typeof e.alg=="string"&&typeof e.hash=="string"){this.dAlg=new i({name:e.alg});this.dHash=new h({hex:e.hash})}}};YAHOO.lang.extend(KJUR.asn1.cades.OtherHashAlgAndValue,KJUR.asn1.ASN1Object);KJUR.asn1.cades.SignatureTimeStamp=function(h){var c=KJUR,b=c.asn1,e=b.ASN1Object,g=b.x509,a=b.cades;a.SignatureTimeStamp.superclass.constructor.call(this);this.attrTypeOid="1.2.840.113549.1.9.16.2.14";this.tstHex=null;if(h!==undefined){if(h.res!==undefined){if(typeof h.res=="string"&&h.res.match(/^[0-9A-Fa-f]+$/)){}else{if(h.res instanceof e){}else{throw"res param shall be ASN1Object or hex string"}}}if(h.tst!==undefined){if(typeof h.tst=="string"&&h.tst.match(/^[0-9A-Fa-f]+$/)){var f=new e();this.tstHex=h.tst;f.hTLV=this.tstHex;f.getEncodedHex();this.valueList=[f]}else{if(h.tst instanceof e){}else{throw"tst param shall be ASN1Object or hex string"}}}}};YAHOO.lang.extend(KJUR.asn1.cades.SignatureTimeStamp,KJUR.asn1.cms.Attribute);KJUR.asn1.cades.CompleteCertificateRefs=function(d){var c=KJUR,b=c.asn1,a=b.cades;a.CompleteCertificateRefs.superclass.constructor.call(this);this.attrTypeOid="1.2.840.113549.1.9.16.2.21";this.setByArray=function(e){this.valueList=[];for(var f=0;f<e.length;f++){var g=new a.OtherCertID(e[f]);this.valueList.push(g)}};if(d!==undefined){if(typeof d=="object"&&typeof d.length=="number"){this.setByArray(d)}}};YAHOO.lang.extend(KJUR.asn1.cades.CompleteCertificateRefs,KJUR.asn1.cms.Attribute);KJUR.asn1.cades.OtherCertID=function(e){var c=KJUR,b=c.asn1,d=b.cms,a=b.cades;a.OtherCertID.superclass.constructor.call(this);this.hasIssuerSerial=true;this.dOtherCertHash=null;this.dIssuerSerial=null;this.setByCertPEM=function(f){this.dOtherCertHash=new a.OtherHash(f);if(this.hasIssuerSerial){this.dIssuerSerial=new d.IssuerAndSerialNumber(f)}};this.getEncodedHex=function(){if(this.hTLV!=null){return this.hTLV}if(this.dOtherCertHash==null){throw"otherCertHash not set"}var f=[this.dOtherCertHash];if(this.dIssuerSerial!=null){f.push(this.dIssuerSerial)}var g=new b.DERSequence({array:f});this.hTLV=g.getEncodedHex();return this.hTLV};if(e!==undefined){if(typeof e=="string"&&e.indexOf("-----BEGIN ")!=-1){this.setByCertPEM(e)}if(typeof e=="object"){if(e.hasis===false){this.hasIssuerSerial=false}if(typeof e.cert=="string"){this.setByCertPEM(e.cert)}}}};YAHOO.lang.extend(KJUR.asn1.cades.OtherCertID,KJUR.asn1.ASN1Object);KJUR.asn1.cades.OtherHash=function(f){var d=KJUR,c=d.asn1,e=c.cms,b=c.cades,g=b.OtherHashAlgAndValue,a=d.crypto.Util.hashHex;b.OtherHash.superclass.constructor.call(this);this.alg="sha256";this.dOtherHash=null;this.setByCertPEM=function(h){if(h.indexOf("-----BEGIN ")==-1){throw"certPEM not to seem PEM format"}var i=pemtohex(h);var j=a(i,this.alg);this.dOtherHash=new g({alg:this.alg,hash:j})};this.getEncodedHex=function(){if(this.dOtherHash==null){throw"OtherHash not set"}return this.dOtherHash.getEncodedHex()};if(f!==undefined){if(typeof f=="string"){if(f.indexOf("-----BEGIN ")!=-1){this.setByCertPEM(f)}else{if(f.match(/^[0-9A-Fa-f]+$/)){this.dOtherHash=new c.DEROctetString({hex:f})}else{throw"unsupported string value for params"}}}else{if(typeof f=="object"){if(typeof f.cert=="string"){if(typeof f.alg=="string"){this.alg=f.alg}this.setByCertPEM(f.cert)}else{this.dOtherHash=new g(f)}}}}};YAHOO.lang.extend(KJUR.asn1.cades.OtherHash,KJUR.asn1.ASN1Object);KJUR.asn1.cades.CAdESUtil=new function(){};KJUR.asn1.cades.CAdESUtil.addSigTS=function(c,b,a){};KJUR.asn1.cades.CAdESUtil.parseSignedDataForAddingUnsigned=function(e){var p=ASN1HEX,u=p.getChildIdx,b=p.getTLV,a=p.getTLVbyList,k=p.getIdxbyList,A=KJUR,g=A.asn1,l=g.ASN1Object,j=g.cms,h=j.SignedData,v=g.cades,z=v.CAdESUtil;var m={};if(a(e,0,[0])!="06092a864886f70d010702"){throw"hex is not CMS SignedData"}var y=k(e,0,[1,0]);var B=u(e,y);if(B.length<4){throw"num of SignedData elem shall be 4 at least"}var d=B.shift();m.version=b(e,d);var w=B.shift();m.algs=b(e,w);var c=B.shift();m.encapcontent=b(e,c);m.certs=null;m.revs=null;m.si=[];var o=B.shift();if(e.substr(o,2)=="a0"){m.certs=b(e,o);o=B.shift()}if(e.substr(o,2)=="a1"){m.revs=b(e,o);o=B.shift()}var t=o;if(e.substr(t,2)!="31"){throw"Can't find signerInfos"}var f=u(e,t);for(var q=0;q<f.length;q++){var s=f[q];var n=z.parseSignerInfoForAddingUnsigned(e,s,q);m.si[q]=n}var x=null;m.obj=new h();x=new l();x.hTLV=m.version;m.obj.dCMSVersion=x;x=new l();x.hTLV=m.algs;m.obj.dDigestAlgs=x;x=new l();x.hTLV=m.encapcontent;m.obj.dEncapContentInfo=x;x=new l();x.hTLV=m.certs;m.obj.dCerts=x;m.obj.signerInfoList=[];for(var q=0;q<m.si.length;q++){m.obj.signerInfoList.push(m.si[q].obj)}return m};KJUR.asn1.cades.CAdESUtil.parseSignerInfoForAddingUnsigned=function(g,q,c){var p=ASN1HEX,s=p.getChildIdx,a=p.getTLV,l=p.getV,v=KJUR,h=v.asn1,n=h.ASN1Object,j=h.cms,k=j.AttributeList,w=j.SignerInfo;var o={};var t=s(g,q);if(t.length!=6){throw"not supported items for SignerInfo (!=6)"}var d=t.shift();o.version=a(g,d);var e=t.shift();o.si=a(g,e);var m=t.shift();o.digalg=a(g,m);var f=t.shift();o.sattrs=a(g,f);var i=t.shift();o.sigalg=a(g,i);var b=t.shift();o.sig=a(g,b);o.sigval=l(g,b);var u=null;o.obj=new w();u=new n();u.hTLV=o.version;o.obj.dCMSVersion=u;u=new n();u.hTLV=o.si;o.obj.dSignerIdentifier=u;u=new n();u.hTLV=o.digalg;o.obj.dDigestAlgorithm=u;u=new n();u.hTLV=o.sattrs;o.obj.dSignedAttrs=u;u=new n();u.hTLV=o.sigalg;o.obj.dSigAlg=u;u=new n();u.hTLV=o.sig;o.obj.dSig=u;o.obj.dUnsignedAttrs=new k();return o}; if(typeof KJUR.asn1.csr=="undefined"||!KJUR.asn1.csr){KJUR.asn1.csr={}}KJUR.asn1.csr.CertificationRequest=function(d){var a=KJUR,f=a.asn1,b=f.DERBitString,e=f.DERSequence,k=f.csr,c=f.x509;k.CertificationRequest.superclass.constructor.call(this);var l=null;var j=null;var h=null;var i=null;var g=null;this.sign=function(p,n){if(this.prvKey==null){this.prvKey=n}this.asn1SignatureAlg=new c.AlgorithmIdentifier({name:p});var o=new a.crypto.Signature({alg:p});o.init(this.prvKey);o.updateHex(this.asn1CSRInfo.getEncodedHex());this.hexSig=o.sign();this.asn1Sig=new b({hex:"00"+this.hexSig});var m=new e({array:[this.asn1CSRInfo,this.asn1SignatureAlg,this.asn1Sig]});this.hTLV=m.getEncodedHex();this.isModified=false};this.getPEMString=function(){return hextopem(this.getEncodedHex(),"CERTIFICATE REQUEST")};this.getEncodedHex=function(){if(this.isModified==false&&this.hTLV!=null){return this.hTLV}throw"not signed yet"};if(d!==undefined&&d.csrinfo!==undefined){this.asn1CSRInfo=d.csrinfo}};YAHOO.lang.extend(KJUR.asn1.csr.CertificationRequest,KJUR.asn1.ASN1Object);KJUR.asn1.csr.CertificationRequestInfo=function(e){var b=KJUR,h=b.asn1,g=h.DERInteger,f=h.DERSequence,m=h.DERSet,j=h.DERNull,c=h.DERTaggedObject,k=h.DERObjectIdentifier,l=h.csr,d=h.x509,a=d.X500Name,n=d.Extension,i=KEYUTIL;l.CertificationRequestInfo.superclass.constructor.call(this);this._initialize=function(){this.asn1Array=new Array();this.asn1Version=new g({"int":0});this.asn1Subject=null;this.asn1SubjPKey=null;this.extensionsArray=new Array()};this.setSubjectByParam=function(o){this.asn1Subject=new a(o)};this.setSubjectPublicKeyByGetKey=function(p){var o=i.getKey(p);this.asn1SubjPKey=new d.SubjectPublicKeyInfo(o)};this.appendExtensionByName=function(p,o){n.appendByNameToArray(p,o,this.extensionsArray)};this.getEncodedHex=function(){this.asn1Array=new Array();this.asn1Array.push(this.asn1Version);this.asn1Array.push(this.asn1Subject);this.asn1Array.push(this.asn1SubjPKey);if(this.extensionsArray.length>0){var s=new f({array:this.extensionsArray});var r=new m({array:[s]});var q=new f({array:[new k({oid:"1.2.840.113549.1.9.14"}),r]});var p=new c({explicit:true,tag:"a0",obj:q});this.asn1Array.push(p)}else{var p=new c({explicit:false,tag:"a0",obj:new j()});this.asn1Array.push(p)}var t=new f({array:this.asn1Array});this.hTLV=t.getEncodedHex();this.isModified=false;return this.hTLV};this._initialize()};YAHOO.lang.extend(KJUR.asn1.csr.CertificationRequestInfo,KJUR.asn1.ASN1Object);KJUR.asn1.csr.CSRUtil=new function(){};KJUR.asn1.csr.CSRUtil.newCSRPEM=function(h){var c=KEYUTIL,b=KJUR.asn1.csr;if(h.subject===undefined){throw"parameter subject undefined"}if(h.sbjpubkey===undefined){throw"parameter sbjpubkey undefined"}if(h.sigalg===undefined){throw"parameter sigalg undefined"}if(h.sbjprvkey===undefined){throw"parameter sbjpubkey undefined"}var d=new b.CertificationRequestInfo();d.setSubjectByParam(h.subject);d.setSubjectPublicKeyByGetKey(h.sbjpubkey);if(h.ext!==undefined&&h.ext.length!==undefined){for(var e=0;e<h.ext.length;e++){for(key in h.ext[e]){d.appendExtensionByName(key,h.ext[e][key])}}}var f=new b.CertificationRequest({csrinfo:d});var a=c.getKey(h.sbjprvkey);f.sign(h.sigalg,a);var g=f.getPEMString();return g};KJUR.asn1.csr.CSRUtil.getInfo=function(c){var f=ASN1HEX;var g=f.getTLVbyList;var b={};b.subject={};b.pubkey={};if(c.indexOf("-----BEGIN CERTIFICATE REQUEST")==-1){throw"argument is not PEM file"}var e=pemtohex(c,"CERTIFICATE REQUEST");try{b.subject.hex=g(e,0,[0,1])}catch(d){}try{b.subject.name=X509.hex2dn(b.subject.hex)}catch(d){}b.pubkey.hex=g(e,0,[0,2]);b.pubkey.obj=KEYUTIL.getKey(b.pubkey.hex,null,"pkcs8pub");try{b.ext=[];var a=new X509();a.parseExt(c);b.ext.push({subjectAltName:{array:a.getExtSubjectAltName2()}})}catch(d){}return b}; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}if(typeof KJUR.asn1.ocsp=="undefined"||!KJUR.asn1.ocsp){KJUR.asn1.ocsp={}}KJUR.asn1.ocsp.DEFAULT_HASH="sha1";KJUR.asn1.ocsp.CertID=function(g){var d=KJUR,k=d.asn1,m=k.DEROctetString,j=k.DERInteger,h=k.DERSequence,f=k.x509,n=f.AlgorithmIdentifier,o=k.ocsp,l=o.DEFAULT_HASH,i=d.crypto,e=i.Util.hashHex,c=X509,q=ASN1HEX;o.CertID.superclass.constructor.call(this);this.dHashAlg=null;this.dIssuerNameHash=null;this.dIssuerKeyHash=null;this.dSerialNumber=null;this.setByValue=function(t,s,p,r){if(r===undefined){r=l}this.dHashAlg=new n({name:r});this.dIssuerNameHash=new m({hex:t});this.dIssuerKeyHash=new m({hex:s});this.dSerialNumber=new j({hex:p})};this.setByCert=function(x,t,v){if(v===undefined){v=l}var p=new c();p.readCertPEM(t);var y=new c();y.readCertPEM(x);var z=y.getPublicKeyHex();var w=q.getTLVbyList(z,0,[1,0],"30");var r=p.getSerialNumberHex();var s=e(y.getSubjectHex(),v);var u=e(w,v);this.setByValue(s,u,r,v);this.hoge=p.getSerialNumberHex()};this.getEncodedHex=function(){if(this.dHashAlg===null&&this.dIssuerNameHash===null&&this.dIssuerKeyHash===null&&this.dSerialNumber===null){throw"not yet set values"}var p=[this.dHashAlg,this.dIssuerNameHash,this.dIssuerKeyHash,this.dSerialNumber];var r=new h({array:p});this.hTLV=r.getEncodedHex();return this.hTLV};if(g!==undefined){var b=g;if(b.issuerCert!==undefined&&b.subjectCert!==undefined){var a=l;if(b.alg===undefined){a=undefined}this.setByCert(b.issuerCert,b.subjectCert,a)}else{if(b.namehash!==undefined&&b.keyhash!==undefined&&b.serial!==undefined){var a=l;if(b.alg===undefined){a=undefined}this.setByValue(b.namehash,b.keyhash,b.serial,a)}else{throw"invalid constructor arguments"}}}};YAHOO.lang.extend(KJUR.asn1.ocsp.CertID,KJUR.asn1.ASN1Object);KJUR.asn1.ocsp.Request=function(f){var c=KJUR,b=c.asn1,a=b.DERSequence,d=b.ocsp;d.Request.superclass.constructor.call(this);this.dReqCert=null;this.dExt=null;this.getEncodedHex=function(){var g=[];if(this.dReqCert===null){throw"reqCert not set"}g.push(this.dReqCert);var h=new a({array:g});this.hTLV=h.getEncodedHex();return this.hTLV};if(typeof f!=="undefined"){var e=new d.CertID(f);this.dReqCert=e}};YAHOO.lang.extend(KJUR.asn1.ocsp.Request,KJUR.asn1.ASN1Object);KJUR.asn1.ocsp.TBSRequest=function(e){var c=KJUR,b=c.asn1,a=b.DERSequence,d=b.ocsp;d.TBSRequest.superclass.constructor.call(this);this.version=0;this.dRequestorName=null;this.dRequestList=[];this.dRequestExt=null;this.setRequestListByParam=function(h){var f=[];for(var g=0;g<h.length;g++){var j=new d.Request(h[0]);f.push(j)}this.dRequestList=f};this.getEncodedHex=function(){var f=[];if(this.version!==0){throw"not supported version: "+this.version}if(this.dRequestorName!==null){throw"requestorName not supported"}var h=new a({array:this.dRequestList});f.push(h);if(this.dRequestExt!==null){throw"requestExtensions not supported"}var g=new a({array:f});this.hTLV=g.getEncodedHex();return this.hTLV};if(e!==undefined){if(e.reqList!==undefined){this.setRequestListByParam(e.reqList)}}};YAHOO.lang.extend(KJUR.asn1.ocsp.TBSRequest,KJUR.asn1.ASN1Object);KJUR.asn1.ocsp.OCSPRequest=function(f){var c=KJUR,b=c.asn1,a=b.DERSequence,d=b.ocsp;d.OCSPRequest.superclass.constructor.call(this);this.dTbsRequest=null;this.dOptionalSignature=null;this.getEncodedHex=function(){var g=[];if(this.dTbsRequest!==null){g.push(this.dTbsRequest)}else{throw"tbsRequest not set"}if(this.dOptionalSignature!==null){throw"optionalSignature not supported"}var h=new a({array:g});this.hTLV=h.getEncodedHex();return this.hTLV};if(f!==undefined){if(f.reqList!==undefined){var e=new d.TBSRequest(f);this.dTbsRequest=e}}};YAHOO.lang.extend(KJUR.asn1.ocsp.OCSPRequest,KJUR.asn1.ASN1Object);KJUR.asn1.ocsp.OCSPUtil={};KJUR.asn1.ocsp.OCSPUtil.getRequestHex=function(a,b,h){var d=KJUR,c=d.asn1,e=c.ocsp;if(h===undefined){h=e.DEFAULT_HASH}var g={alg:h,issuerCert:a,subjectCert:b};var f=new e.OCSPRequest({reqList:[g]});return f.getEncodedHex()};KJUR.asn1.ocsp.OCSPUtil.getOCSPResponseInfo=function(b){var k=ASN1HEX;var c=k.getVbyList;var d=k.getIdxbyList;var c=k.getVbyList;var f=k.getV;var l={};try{var i=c(b,0,[0],"0a");l.responseStatus=parseInt(i,16)}catch(e){}if(l.responseStatus!==0){return l}try{var g=d(b,0,[1,0,1,0,0,2,0,1]);if(b.substr(g,2)==="80"){l.certStatus="good"}else{if(b.substr(g,2)==="a1"){l.certStatus="revoked";l.revocationTime=hextoutf8(c(b,g,[0]))}else{if(b.substr(g,2)==="82"){l.certStatus="unknown"}}}}catch(e){}try{var a=d(b,0,[1,0,1,0,0,2,0,2]);l.thisUpdate=hextoutf8(f(b,a))}catch(e){}try{var j=d(b,0,[1,0,1,0,0,2,0,3]);if(b.substr(j,2)==="a0"){l.nextUpdate=hextoutf8(c(b,j,[0]))}}catch(e){}return l}; var KJUR;if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.lang=="undefined"||!KJUR.lang){KJUR.lang={}}KJUR.lang.String=function(){};function Base64x(){}function stoBA(d){var b=new Array();for(var c=0;c<d.length;c++){b[c]=d.charCodeAt(c)}return b}function BAtos(b){var d="";for(var c=0;c<b.length;c++){d=d+String.fromCharCode(b[c])}return d}function BAtohex(b){var e="";for(var d=0;d<b.length;d++){var c=b[d].toString(16);if(c.length==1){c="0"+c}e=e+c}return e}function stohex(a){return BAtohex(stoBA(a))}function stob64(a){return hex2b64(stohex(a))}function stob64u(a){return b64tob64u(hex2b64(stohex(a)))}function b64utos(a){return BAtos(b64toBA(b64utob64(a)))}function b64tob64u(a){a=a.replace(/\=/g,"");a=a.replace(/\+/g,"-");a=a.replace(/\//g,"_");return a}function b64utob64(a){if(a.length%4==2){a=a+"=="}else{if(a.length%4==3){a=a+"="}}a=a.replace(/-/g,"+");a=a.replace(/_/g,"/");return a}function hextob64u(a){if(a.length%2==1){a="0"+a}return b64tob64u(hex2b64(a))}function b64utohex(a){return b64tohex(b64utob64(a))}var utf8tob64u,b64utoutf8;if(typeof Buffer==="function"){utf8tob64u=function(a){return b64tob64u(new Buffer(a,"utf8").toString("base64"))};b64utoutf8=function(a){return new Buffer(b64utob64(a),"base64").toString("utf8")}}else{utf8tob64u=function(a){return hextob64u(uricmptohex(encodeURIComponentAll(a)))};b64utoutf8=function(a){return decodeURIComponent(hextouricmp(b64utohex(a)))}}function utf8tob64(a){return hex2b64(uricmptohex(encodeURIComponentAll(a)))}function b64toutf8(a){return decodeURIComponent(hextouricmp(b64tohex(a)))}function utf8tohex(a){return uricmptohex(encodeURIComponentAll(a))}function hextoutf8(a){return decodeURIComponent(hextouricmp(a))}function hextorstr(c){var b="";for(var a=0;a<c.length-1;a+=2){b+=String.fromCharCode(parseInt(c.substr(a,2),16))}return b}function rstrtohex(c){var a="";for(var b=0;b<c.length;b++){a+=("0"+c.charCodeAt(b).toString(16)).slice(-2)}return a}function hextob64(a){return hex2b64(a)}function hextob64nl(b){var a=hextob64(b);var c=a.replace(/(.{64})/g,"$1\r\n");c=c.replace(/\r\n$/,"");return c}function b64nltohex(b){var a=b.replace(/[^0-9A-Za-z\/+=]*/g,"");var c=b64tohex(a);return c}function hextopem(a,b){var c=hextob64nl(a);return"-----BEGIN "+b+"-----\r\n"+c+"\r\n-----END "+b+"-----\r\n"}function pemtohex(a,b){if(a.indexOf("-----BEGIN ")==-1){throw"can't find PEM header: "+b}if(b!==undefined){a=a.replace(new RegExp("^[^]*-----BEGIN "+b+"-----"),"");a=a.replace(new RegExp("-----END "+b+"-----[^]*$"),"")}else{a=a.replace(/^[^]*-----BEGIN [^-]+-----/,"");a=a.replace(/-----END [^-]+-----[^]*$/,"")}return b64nltohex(a)}function hextoArrayBuffer(d){if(d.length%2!=0){throw"input is not even length"}if(d.match(/^[0-9A-Fa-f]+$/)==null){throw"input is not hexadecimal"}var b=new ArrayBuffer(d.length/2);var a=new DataView(b);for(var c=0;c<d.length/2;c++){a.setUint8(c,parseInt(d.substr(c*2,2),16))}return b}function ArrayBuffertohex(b){var d="";var a=new DataView(b);for(var c=0;c<b.byteLength;c++){d+=("00"+a.getUint8(c).toString(16)).slice(-2)}return d}function zulutomsec(n){var l,j,m,e,f,i,b,k;var a,h,g,c;c=n.match(/^(\d{2}|\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/);if(c){a=c[1];l=parseInt(a);if(a.length===2){if(50<=l&&l<100){l=1900+l}else{if(0<=l&&l<50){l=2000+l}}}j=parseInt(c[2])-1;m=parseInt(c[3]);e=parseInt(c[4]);f=parseInt(c[5]);i=parseInt(c[6]);b=0;h=c[7];if(h!==""){g=(h.substr(1)+"00").substr(0,3);b=parseInt(g)}return Date.UTC(l,j,m,e,f,i,b)}throw"unsupported zulu format: "+n}function zulutosec(a){var b=zulutomsec(a);return ~~(b/1000)}function zulutodate(a){return new Date(zulutomsec(a))}function datetozulu(g,e,f){var b;var a=g.getUTCFullYear();if(e){if(a<1950||2049<a){throw"not proper year for UTCTime: "+a}b=(""+a).slice(-2)}else{b=("000"+a).slice(-4)}b+=("0"+(g.getUTCMonth()+1)).slice(-2);b+=("0"+g.getUTCDate()).slice(-2);b+=("0"+g.getUTCHours()).slice(-2);b+=("0"+g.getUTCMinutes()).slice(-2);b+=("0"+g.getUTCSeconds()).slice(-2);if(f){var c=g.getUTCMilliseconds();if(c!==0){c=("00"+c).slice(-3);c=c.replace(/0+$/g,"");b+="."+c}}b+="Z";return b}function uricmptohex(a){return a.replace(/%/g,"")}function hextouricmp(a){return a.replace(/(..)/g,"%$1")}function ipv6tohex(g){var b="malformed IPv6 address";if(!g.match(/^[0-9A-Fa-f:]+$/)){throw b}g=g.toLowerCase();var d=g.split(":").length-1;if(d<2){throw b}var e=":".repeat(7-d+2);g=g.replace("::",e);var c=g.split(":");if(c.length!=8){throw b}for(var f=0;f<8;f++){c[f]=("0000"+c[f]).slice(-4)}return c.join("")}function hextoipv6(e){if(!e.match(/^[0-9A-Fa-f]{32}$/)){throw"malformed IPv6 address octet"}e=e.toLowerCase();var b=e.match(/.{1,4}/g);for(var d=0;d<8;d++){b[d]=b[d].replace(/^0+/,"");if(b[d]==""){b[d]="0"}}e=":"+b.join(":")+":";var c=e.match(/:(0:){2,}/g);if(c===null){return e.slice(1,-1)}var f="";for(var d=0;d<c.length;d++){if(c[d].length>f.length){f=c[d]}}e=e.replace(f,"::");return e.slice(1,-1)}function hextoip(b){var d="malformed hex value";if(!b.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/)){throw d}if(b.length==8){var c;try{c=parseInt(b.substr(0,2),16)+"."+parseInt(b.substr(2,2),16)+"."+parseInt(b.substr(4,2),16)+"."+parseInt(b.substr(6,2),16);return c}catch(a){throw d}}else{if(b.length==32){return hextoipv6(b)}else{return b}}}function iptohex(f){var j="malformed IP address";f=f.toLowerCase(f);if(f.match(/^[0-9.]+$/)){var b=f.split(".");if(b.length!==4){throw j}var g="";try{for(var e=0;e<4;e++){var h=parseInt(b[e]);g+=("0"+h.toString(16)).slice(-2)}return g}catch(c){throw j}}else{if(f.match(/^[0-9a-f:]+$/)&&f.indexOf(":")!==-1){return ipv6tohex(f)}else{throw j}}}function encodeURIComponentAll(a){var d=encodeURIComponent(a);var b="";for(var c=0;c<d.length;c++){if(d[c]=="%"){b=b+d.substr(c,3);c=c+2}else{b=b+"%"+stohex(d[c])}}return b}function newline_toUnix(a){a=a.replace(/\r\n/mg,"\n");return a}function newline_toDos(a){a=a.replace(/\r\n/mg,"\n");a=a.replace(/\n/mg,"\r\n");return a}KJUR.lang.String.isInteger=function(a){if(a.match(/^[0-9]+$/)){return true}else{if(a.match(/^-[0-9]+$/)){return true}else{return false}}};KJUR.lang.String.isHex=function(a){if(a.length%2==0&&(a.match(/^[0-9a-f]+$/)||a.match(/^[0-9A-F]+$/))){return true}else{return false}};KJUR.lang.String.isBase64=function(a){a=a.replace(/\s+/g,"");if(a.match(/^[0-9A-Za-z+\/]+={0,3}$/)&&a.length%4==0){return true}else{return false}};KJUR.lang.String.isBase64URL=function(a){if(a.match(/[+/=]/)){return false}a=b64utob64(a);return KJUR.lang.String.isBase64(a)};KJUR.lang.String.isIntegerArray=function(a){a=a.replace(/\s+/g,"");if(a.match(/^\[[0-9,]+\]$/)){return true}else{return false}};function hextoposhex(a){if(a.length%2==1){return"0"+a}if(a.substr(0,1)>"7"){return"00"+a}return a}function intarystrtohex(b){b=b.replace(/^\s*\[\s*/,"");b=b.replace(/\s*\]\s*$/,"");b=b.replace(/\s*/g,"");try{var c=b.split(/,/).map(function(g,e,h){var f=parseInt(g);if(f<0||255<f){throw"integer not in range 0-255"}var d=("00"+f.toString(16)).slice(-2);return d}).join("");return c}catch(a){throw"malformed integer array string: "+a}}var strdiffidx=function(c,a){var d=c.length;if(c.length>a.length){d=a.length}for(var b=0;b<d;b++){if(c.charCodeAt(b)!=a.charCodeAt(b)){return b}}if(c.length!=a.length){return d}return -1}; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.crypto=="undefined"||!KJUR.crypto){KJUR.crypto={}}KJUR.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414",};this.DEFAULTPROVIDER={md5:"cryptojs",sha1:"cryptojs",sha224:"cryptojs",sha256:"cryptojs",sha384:"cryptojs",sha512:"cryptojs",ripemd160:"cryptojs",hmacmd5:"cryptojs",hmacsha1:"cryptojs",hmacsha224:"cryptojs",hmacsha256:"cryptojs",hmacsha384:"cryptojs",hmacsha512:"cryptojs",hmacripemd160:"cryptojs",MD5withRSA:"cryptojs/jsrsa",SHA1withRSA:"cryptojs/jsrsa",SHA224withRSA:"cryptojs/jsrsa",SHA256withRSA:"cryptojs/jsrsa",SHA384withRSA:"cryptojs/jsrsa",SHA512withRSA:"cryptojs/jsrsa",RIPEMD160withRSA:"cryptojs/jsrsa",MD5withECDSA:"cryptojs/jsrsa",SHA1withECDSA:"cryptojs/jsrsa",SHA224withECDSA:"cryptojs/jsrsa",SHA256withECDSA:"cryptojs/jsrsa",SHA384withECDSA:"cryptojs/jsrsa",SHA512withECDSA:"cryptojs/jsrsa",RIPEMD160withECDSA:"cryptojs/jsrsa",SHA1withDSA:"cryptojs/jsrsa",SHA224withDSA:"cryptojs/jsrsa",SHA256withDSA:"cryptojs/jsrsa",MD5withRSAandMGF1:"cryptojs/jsrsa",SHA1withRSAandMGF1:"cryptojs/jsrsa",SHA224withRSAandMGF1:"cryptojs/jsrsa",SHA256withRSAandMGF1:"cryptojs/jsrsa",SHA384withRSAandMGF1:"cryptojs/jsrsa",SHA512withRSAandMGF1:"cryptojs/jsrsa",RIPEMD160withRSAandMGF1:"cryptojs/jsrsa",};this.CRYPTOJSMESSAGEDIGESTNAME={md5:CryptoJS.algo.MD5,sha1:CryptoJS.algo.SHA1,sha224:CryptoJS.algo.SHA224,sha256:CryptoJS.algo.SHA256,sha384:CryptoJS.algo.SHA384,sha512:CryptoJS.algo.SHA512,ripemd160:CryptoJS.algo.RIPEMD160};this.getDigestInfoHex=function(a,b){if(typeof this.DIGESTINFOHEAD[b]=="undefined"){throw"alg not supported in Util.DIGESTINFOHEAD: "+b}return this.DIGESTINFOHEAD[b]+a};this.getPaddedDigestInfoHex=function(h,a,j){var c=this.getDigestInfoHex(h,a);var d=j/4;if(c.length+22>d){throw"key is too short for SigAlg: keylen="+j+","+a}var b="0001";var k="00"+c;var g="";var l=d-b.length-k.length;for(var f=0;f<l;f+=2){g+="ff"}var e=b+g+k;return e};this.hashString=function(a,c){var b=new KJUR.crypto.MessageDigest({alg:c});return b.digestString(a)};this.hashHex=function(b,c){var a=new KJUR.crypto.MessageDigest({alg:c});return a.digestHex(b)};this.sha1=function(a){return this.hashString(a,"sha1")};this.sha256=function(a){return this.hashString(a,"sha256")};this.sha256Hex=function(a){return this.hashHex(a,"sha256")};this.sha512=function(a){return this.hashString(a,"sha512")};this.sha512Hex=function(a){return this.hashHex(a,"sha512")};this.isKey=function(a){if(a instanceof RSAKey||a instanceof KJUR.crypto.DSA||a instanceof KJUR.crypto.ECDSA){return true}else{return false}}};KJUR.crypto.Util.md5=function(a){var b=new KJUR.crypto.MessageDigest({alg:"md5",prov:"cryptojs"});return b.digestString(a)};KJUR.crypto.Util.ripemd160=function(a){var b=new KJUR.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"});return b.digestString(a)};KJUR.crypto.Util.SECURERANDOMGEN=new SecureRandom();KJUR.crypto.Util.getRandomHexOfNbytes=function(b){var a=new Array(b);KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(a);return BAtohex(a)};KJUR.crypto.Util.getRandomBigIntegerOfNbytes=function(a){return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbytes(a),16)};KJUR.crypto.Util.getRandomHexOfNbits=function(d){var c=d%8;var a=(d-c)/8;var b=new Array(a+1);KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(b);b[0]=(((255<<c)&255)^255)&b[0];return BAtohex(b)};KJUR.crypto.Util.getRandomBigIntegerOfNbits=function(a){return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbits(a),16)};KJUR.crypto.Util.getRandomBigIntegerZeroToMax=function(b){var a=b.bitLength();while(1){var c=KJUR.crypto.Util.getRandomBigIntegerOfNbits(a);if(b.compareTo(c)!=-1){return c}}};KJUR.crypto.Util.getRandomBigIntegerMinToMax=function(e,b){var c=e.compareTo(b);if(c==1){throw"biMin is greater than biMax"}if(c==0){return e}var a=b.subtract(e);var d=KJUR.crypto.Util.getRandomBigIntegerZeroToMax(a);return d.add(e)};KJUR.crypto.MessageDigest=function(c){var b=null;var a=null;var d=null;this.setAlgAndProvider=function(g,f){g=KJUR.crypto.MessageDigest.getCanonicalAlgName(g);if(g!==null&&f===undefined){f=KJUR.crypto.Util.DEFAULTPROVIDER[g]}if(":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(g)!=-1&&f=="cryptojs"){try{this.md=KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[g].create()}catch(e){throw"setAlgAndProvider hash alg set fail alg="+g+"/"+e}this.updateString=function(h){this.md.update(h)};this.updateHex=function(h){var i=CryptoJS.enc.Hex.parse(h);this.md.update(i)};this.digest=function(){var h=this.md.finalize();return h.toString(CryptoJS.enc.Hex)};this.digestString=function(h){this.updateString(h);return this.digest()};this.digestHex=function(h){this.updateHex(h);return this.digest()}}if(":sha256:".indexOf(g)!=-1&&f=="sjcl"){try{this.md=new sjcl.hash.sha256()}catch(e){throw"setAlgAndProvider hash alg set fail alg="+g+"/"+e}this.updateString=function(h){this.md.update(h)};this.updateHex=function(i){var h=sjcl.codec.hex.toBits(i);this.md.update(h)};this.digest=function(){var h=this.md.finalize();return sjcl.codec.hex.fromBits(h)};this.digestString=function(h){this.updateString(h);return this.digest()};this.digestHex=function(h){this.updateHex(h);return this.digest()}}};this.updateString=function(e){throw"updateString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName};this.updateHex=function(e){throw"updateHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName};this.digest=function(){throw"digest() not supported for this alg/prov: "+this.algName+"/"+this.provName};this.digestString=function(e){throw"digestString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName};this.digestHex=function(e){throw"digestHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName};if(c!==undefined){if(c.alg!==undefined){this.algName=c.alg;if(c.prov===undefined){this.provName=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]}this.setAlgAndProvider(this.algName,this.provName)}}};KJUR.crypto.MessageDigest.getCanonicalAlgName=function(a){if(typeof a==="string"){a=a.toLowerCase();a=a.replace(/-/,"")}return a};KJUR.crypto.MessageDigest.getHashLength=function(c){var b=KJUR.crypto.MessageDigest;var a=b.getCanonicalAlgName(c);if(b.HASHLENGTH[a]===undefined){throw"not supported algorithm: "+c}return b.HASHLENGTH[a]};KJUR.crypto.MessageDigest.HASHLENGTH={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,ripemd160:20};KJUR.crypto.Mac=function(d){var f=null;var c=null;var a=null;var e=null;var b=null;this.setAlgAndProvider=function(k,i){k=k.toLowerCase();if(k==null){k="hmacsha1"}k=k.toLowerCase();if(k.substr(0,4)!="hmac"){throw"setAlgAndProvider unsupported HMAC alg: "+k}if(i===undefined){i=KJUR.crypto.Util.DEFAULTPROVIDER[k]}this.algProv=k+"/"+i;var g=k.substr(4);if(":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(g)!=-1&&i=="cryptojs"){try{var j=KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[g];this.mac=CryptoJS.algo.HMAC.create(j,this.pass)}catch(h){throw"setAlgAndProvider hash alg set fail hashAlg="+g+"/"+h}this.updateString=function(l){this.mac.update(l)};this.updateHex=function(l){var m=CryptoJS.enc.Hex.parse(l);this.mac.update(m)};this.doFinal=function(){var l=this.mac.finalize();return l.toString(CryptoJS.enc.Hex)};this.doFinalString=function(l){this.updateString(l);return this.doFinal()};this.doFinalHex=function(l){this.updateHex(l);return this.doFinal()}}};this.updateString=function(g){throw"updateString(str) not supported for this alg/prov: "+this.algProv};this.updateHex=function(g){throw"updateHex(hex) not supported for this alg/prov: "+this.algProv};this.doFinal=function(){throw"digest() not supported for this alg/prov: "+this.algProv};this.doFinalString=function(g){throw"digestString(str) not supported for this alg/prov: "+this.algProv};this.doFinalHex=function(g){throw"digestHex(hex) not supported for this alg/prov: "+this.algProv};this.setPassword=function(h){if(typeof h=="string"){var g=h;if(h.length%2==1||!h.match(/^[0-9A-Fa-f]+$/)){g=rstrtohex(h)}this.pass=CryptoJS.enc.Hex.parse(g);return}if(typeof h!="object"){throw"KJUR.crypto.Mac unsupported password type: "+h}var g=null;if(h.hex!==undefined){if(h.hex.length%2!=0||!h.hex.match(/^[0-9A-Fa-f]+$/)){throw"Mac: wrong hex password: "+h.hex}g=h.hex}if(h.utf8!==undefined){g=utf8tohex(h.utf8)}if(h.rstr!==undefined){g=rstrtohex(h.rstr)}if(h.b64!==undefined){g=b64tohex(h.b64)}if(h.b64u!==undefined){g=b64utohex(h.b64u)}if(g==null){throw"KJUR.crypto.Mac unsupported password type: "+h}this.pass=CryptoJS.enc.Hex.parse(g)};if(d!==undefined){if(d.pass!==undefined){this.setPassword(d.pass)}if(d.alg!==undefined){this.algName=d.alg;if(d.prov===undefined){this.provName=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]}this.setAlgAndProvider(this.algName,this.provName)}}};KJUR.crypto.Signature=function(o){var q=null;var n=null;var r=null;var c=null;var l=null;var d=null;var k=null;var h=null;var p=null;var e=null;var b=-1;var g=null;var j=null;var a=null;var i=null;var f=null;this._setAlgNames=function(){var s=this.algName.match(/^(.+)with(.+)$/);if(s){this.mdAlgName=s[1].toLowerCase();this.pubkeyAlgName=s[2].toLowerCase()}};this._zeroPaddingOfSignature=function(x,w){var v="";var t=w/4-x.length;for(var u=0;u<t;u++){v=v+"0"}return v+x};this.setAlgAndProvider=function(u,t){this._setAlgNames();if(t!="cryptojs/jsrsa"){throw"provider not supported: "+t}if(":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName)!=-1){try{this.md=new KJUR.crypto.MessageDigest({alg:this.mdAlgName})}catch(s){throw"setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+s}this.init=function(w,x){var y=null;try{if(x===undefined){y=KEYUTIL.getKey(w)}else{y=KEYUTIL.getKey(w,x)}}catch(v){throw"init failed:"+v}if(y.isPrivate===true){this.prvKey=y;this.state="SIGN"}else{if(y.isPublic===true){this.pubKey=y;this.state="VERIFY"}else{throw"init failed.:"+y}}};this.updateString=function(v){this.md.updateString(v)};this.updateHex=function(v){this.md.updateHex(v)};this.sign=function(){this.sHashHex=this.md.digest();if(this.prvKey===undefined&&this.ecprvhex!==undefined&&this.eccurvename!==undefined&&KJUR.crypto.ECDSA!==undefined){this.prvKey=new KJUR.crypto.ECDSA({curve:this.eccurvename,prv:this.ecprvhex})}if(this.prvKey instanceof RSAKey&&this.pubkeyAlgName==="rsaandmgf1"){this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen)}else{if(this.prvKey instanceof RSAKey&&this.pubkeyAlgName==="rsa"){this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName)}else{if(this.prvKey instanceof KJUR.crypto.ECDSA){this.hSign=this.prvKey.signWithMessageHash(this.sHashHex)}else{if(this.prvKey instanceof KJUR.crypto.DSA){this.hSign=this.prvKey.signWithMessageHash(this.sHashHex)}else{throw"Signature: unsupported private key alg: "+this.pubkeyAlgName}}}}return this.hSign};this.signString=function(v){this.updateString(v);return this.sign()};this.signHex=function(v){this.updateHex(v);return this.sign()};this.verify=function(v){this.sHashHex=this.md.digest();if(this.pubKey===undefined&&this.ecpubhex!==undefined&&this.eccurvename!==undefined&&KJUR.crypto.ECDSA!==undefined){this.pubKey=new KJUR.crypto.ECDSA({curve:this.eccurvename,pub:this.ecpubhex})}if(this.pubKey instanceof RSAKey&&this.pubkeyAlgName==="rsaandmgf1"){return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,v,this.mdAlgName,this.pssSaltLen)}else{if(this.pubKey instanceof RSAKey&&this.pubkeyAlgName==="rsa"){return this.pubKey.verifyWithMessageHash(this.sHashHex,v)}else{if(KJUR.crypto.ECDSA!==undefined&&this.pubKey instanceof KJUR.crypto.ECDSA){return this.pubKey.verifyWithMessageHash(this.sHashHex,v)}else{if(KJUR.crypto.DSA!==undefined&&this.pubKey instanceof KJUR.crypto.DSA){return this.pubKey.verifyWithMessageHash(this.sHashHex,v)}else{throw"Signature: unsupported public key alg: "+this.pubkeyAlgName}}}}}}};this.init=function(s,t){throw"init(key, pass) not supported for this alg:prov="+this.algProvName};this.updateString=function(s){throw"updateString(str) not supported for this alg:prov="+this.algProvName};this.updateHex=function(s){throw"updateHex(hex) not supported for this alg:prov="+this.algProvName};this.sign=function(){throw"sign() not supported for this alg:prov="+this.algProvName};this.signString=function(s){throw"digestString(str) not supported for this alg:prov="+this.algProvName};this.signHex=function(s){throw"digestHex(hex) not supported for this alg:prov="+this.algProvName};this.verify=function(s){throw"verify(hSigVal) not supported for this alg:prov="+this.algProvName};this.initParams=o;if(o!==undefined){if(o.alg!==undefined){this.algName=o.alg;if(o.prov===undefined){this.provName=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]}else{this.provName=o.prov}this.algProvName=this.algName+":"+this.provName;this.setAlgAndProvider(this.algName,this.provName);this._setAlgNames()}if(o.psssaltlen!==undefined){this.pssSaltLen=o.psssaltlen}if(o.prvkeypem!==undefined){if(o.prvkeypas!==undefined){throw"both prvkeypem and prvkeypas parameters not supported"}else{try{var q=KEYUTIL.getKey(o.prvkeypem);this.init(q)}catch(m){throw"fatal error to load pem private key: "+m}}}}};KJUR.crypto.Cipher=function(a){};KJUR.crypto.Cipher.encrypt=function(e,f,d){if(f instanceof RSAKey&&f.isPublic){var c=KJUR.crypto.Cipher.getAlgByKeyAndName(f,d);if(c==="RSA"){return f.encrypt(e)}if(c==="RSAOAEP"){return f.encryptOAEP(e,"sha1")}var b=c.match(/^RSAOAEP(\d+)$/);if(b!==null){return f.encryptOAEP(e,"sha"+b[1])}throw"Cipher.encrypt: unsupported algorithm for RSAKey: "+d}else{throw"Cipher.encrypt: unsupported key or algorithm"}};KJUR.crypto.Cipher.decrypt=function(e,f,d){if(f instanceof RSAKey&&f.isPrivate){var c=KJUR.crypto.Cipher.getAlgByKeyAndName(f,d);if(c==="RSA"){return f.decrypt(e)}if(c==="RSAOAEP"){return f.decryptOAEP(e,"sha1")}var b=c.match(/^RSAOAEP(\d+)$/);if(b!==null){return f.decryptOAEP(e,"sha"+b[1])}throw"Cipher.decrypt: unsupported algorithm for RSAKey: "+d}else{throw"Cipher.decrypt: unsupported key or algorithm"}};KJUR.crypto.Cipher.getAlgByKeyAndName=function(b,a){if(b instanceof RSAKey){if(":RSA:RSAOAEP:RSAOAEP224:RSAOAEP256:RSAOAEP384:RSAOAEP512:".indexOf(a)!=-1){return a}if(a===null||a===undefined){return"RSA"}throw"getAlgByKeyAndName: not supported algorithm name for RSAKey: "+a}throw"getAlgByKeyAndName: not supported algorithm name: "+a};KJUR.crypto.OID=new function(){this.oidhex2name={"2a864886f70d010101":"rsaEncryption","2a8648ce3d0201":"ecPublicKey","2a8648ce380401":"dsa","2a8648ce3d030107":"secp256r1","2b8104001f":"secp192k1","2b81040021":"secp224r1","2b8104000a":"secp256k1","2b81040023":"secp521r1","2b81040022":"secp384r1","2a8648ce380403":"SHA1withDSA","608648016503040301":"SHA224withDSA","608648016503040302":"SHA256withDSA",}}; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.crypto=="undefined"||!KJUR.crypto){KJUR.crypto={}}KJUR.crypto.ECDSA=function(d){var f="secp256r1";var l=null;var b=null;var h=null;var e=BigInteger,g=ECPointFp,j=KJUR.crypto.ECDSA,c=KJUR.crypto.ECParameterDB;var a=new SecureRandom();var k=null;this.type="EC";this.isPrivate=false;this.isPublic=false;function i(t,p,s,o){var n=Math.max(p.bitLength(),o.bitLength());var u=t.add2D(s);var r=t.curve.getInfinity();for(var q=n-1;q>=0;--q){r=r.twice2D();r.z=e.ONE;if(p.testBit(q)){if(o.testBit(q)){r=r.add2D(u)}else{r=r.add2D(t)}}else{if(o.testBit(q)){r=r.add2D(s)}}}return r}this.getBigRandom=function(m){return new e(m.bitLength(),a).mod(m.subtract(e.ONE)).add(e.ONE)};this.setNamedCurve=function(m){this.ecparams=c.getByName(m);this.prvKeyHex=null;this.pubKeyHex=null;this.curveName=m};this.setPrivateKeyHex=function(m){this.isPrivate=true;this.prvKeyHex=m};this.setPublicKeyHex=function(m){this.isPublic=true;this.pubKeyHex=m};this.getPublicKeyXYHex=function(){var o=this.pubKeyHex;if(o.substr(0,2)!=="04"){throw"this method supports uncompressed format(04) only"}var n=this.ecparams.keylen/4;if(o.length!==2+n*2){throw"malformed public key hex length"}var m={};m.x=o.substr(2,n);m.y=o.substr(2+n);return m};this.getShortNISTPCurveName=function(){var m=this.curveName;if(m==="secp256r1"||m==="NIST P-256"||m==="P-256"||m==="prime256v1"){return"P-256"}if(m==="secp384r1"||m==="NIST P-384"||m==="P-384"){return"P-384"}return null};this.generateKeyPairHex=function(){var o=this.ecparams.n;var r=this.getBigRandom(o);var p=this.ecparams.G.multiply(r);var u=p.getX().toBigInteger();var s=p.getY().toBigInteger();var m=this.ecparams.keylen/4;var q=("0000000000"+r.toString(16)).slice(-m);var v=("0000000000"+u.toString(16)).slice(-m);var t=("0000000000"+s.toString(16)).slice(-m);var n="04"+v+t;this.setPrivateKeyHex(q);this.setPublicKeyHex(n);return{ecprvhex:q,ecpubhex:n}};this.signWithMessageHash=function(m){return this.signHex(m,this.prvKeyHex)};this.signHex=function(t,o){var w=new e(o,16);var p=this.ecparams.n;var v=new e(t.substring(0,this.ecparams.keylen/4),16);do{var q=this.getBigRandom(p);var x=this.ecparams.G;var u=x.multiply(q);var m=u.getX().toBigInteger().mod(p)}while(m.compareTo(e.ZERO)<=0);var y=q.modInverse(p).multiply(v.add(w.multiply(m))).mod(p);return j.biRSSigToASN1Sig(m,y)};this.sign=function(q,x){var v=x;var o=this.ecparams.n;var u=e.fromByteArrayUnsigned(q);do{var p=this.getBigRandom(o);var w=this.ecparams.G;var t=w.multiply(p);var m=t.getX().toBigInteger().mod(o)}while(m.compareTo(BigInteger.ZERO)<=0);var y=p.modInverse(o).multiply(u.add(v.multiply(m))).mod(o);return this.serializeSig(m,y)};this.verifyWithMessageHash=function(n,m){return this.verifyHex(n,m,this.pubKeyHex)};this.verifyHex=function(o,t,n){try{var m,w;var p=j.parseSigHex(t);m=p.r;w=p.s;var q=g.decodeFromHex(this.ecparams.curve,n);var u=new e(o.substring(0,this.ecparams.keylen/4),16);return this.verifyRaw(u,m,w,q)}catch(v){return false}};this.verify=function(u,v,n){var p,m;if(Bitcoin.Util.isArray(v)){var t=this.parseSig(v);p=t.r;m=t.s}else{if("object"===typeof v&&v.r&&v.s){p=v.r;m=v.s}else{throw"Invalid value for signature"}}var o;if(n instanceof ECPointFp){o=n}else{if(Bitcoin.Util.isArray(n)){o=g.decodeFrom(this.ecparams.curve,n)}else{throw"Invalid format for pubkey value, must be byte array or ECPointFp"}}var q=e.fromByteArrayUnsigned(u);return this.verifyRaw(q,p,m,o)};this.verifyRaw=function(u,m,A,t){var q=this.ecparams.n;var z=this.ecparams.G;if(m.compareTo(e.ONE)<0||m.compareTo(q)>=0){return false}if(A.compareTo(e.ONE)<0||A.compareTo(q)>=0){return false}var w=A.modInverse(q);var p=u.multiply(w).mod(q);var o=m.multiply(w).mod(q);var x=z.multiply(p).add(t.multiply(o));var y=x.getX().toBigInteger().mod(q);return y.equals(m)};this.serializeSig=function(o,n){var p=o.toByteArraySigned();var m=n.toByteArraySigned();var q=[];q.push(2);q.push(p.length);q=q.concat(p);q.push(2);q.push(m.length);q=q.concat(m);q.unshift(q.length);q.unshift(48);return q};this.parseSig=function(t){var q;if(t[0]!=48){throw new Error("Signature not a valid DERSequence")}q=2;if(t[q]!=2){throw new Error("First element in signature must be a DERInteger")}var p=t.slice(q+2,q+2+t[q+1]);q+=2+t[q+1];if(t[q]!=2){throw new Error("Second element in signature must be a DERInteger")}var m=t.slice(q+2,q+2+t[q+1]);q+=2+t[q+1];var o=e.fromByteArrayUnsigned(p);var n=e.fromByteArrayUnsigned(m);return{r:o,s:n}};this.parseSigCompact=function(q){if(q.length!==65){throw"Signature has the wrong length"}var m=q[0]-27;if(m<0||m>7){throw"Invalid signature type"}var t=this.ecparams.n;var p=e.fromByteArrayUnsigned(q.slice(1,33)).mod(t);var o=e.fromByteArrayUnsigned(q.slice(33,65)).mod(t);return{r:p,s:o,i:m}};this.readPKCS5PrvKeyHex=function(p){var r=ASN1HEX,q=j.getName,t=r.getVbyList;if(r.isASN1HEX(p)===false){throw"not ASN.1 hex string"}var m,o,s;try{m=t(p,0,[2,0],"06");o=t(p,0,[1],"04");try{s=t(p,0,[3,0],"03").substr(2)}catch(n){}}catch(n){throw"malformed PKCS#1/5 plain ECC private key"}this.curveName=q(m);if(this.curveName===undefined){throw"unsupported curve name"}this.setNamedCurve(this.curveName);this.setPublicKeyHex(s);this.setPrivateKeyHex(o);this.isPublic=false};this.readPKCS8PrvKeyHex=function(p){var u=ASN1HEX;var m=KJUR.crypto.ECDSA.getName;var r=u.getVbyList;if(u.isASN1HEX(p)===false){throw"not ASN.1 hex string"}var n,t,q,o;try{n=r(p,0,[1,0],"06");t=r(p,0,[1,1],"06");q=r(p,0,[2,0,1],"04");try{o=r(p,0,[2,0,2,0],"03").substr(2)}catch(s){}}catch(s){throw"malformed PKCS#8 plain ECC private key"}this.curveName=m(t);if(this.curveName===undefined){throw"unsupported curve name"}this.setNamedCurve(this.curveName);this.setPublicKeyHex(o);this.setPrivateKeyHex(q);this.isPublic=false};this.readPKCS8PubKeyHex=function(p){var r=ASN1HEX;var q=KJUR.crypto.ECDSA.getName;var t=r.getVbyList;if(r.isASN1HEX(p)===false){throw"not ASN.1 hex string"}var o,m,s;try{o=t(p,0,[0,0],"06");m=t(p,0,[0,1],"06");s=t(p,0,[1],"03").substr(2)}catch(n){throw"malformed PKCS#8 ECC public key"}this.curveName=q(m);if(this.curveName===null){throw"unsupported curve name"}this.setNamedCurve(this.curveName);this.setPublicKeyHex(s)};this.readCertPubKeyHex=function(o,t){if(t!==5){t=6}var q=ASN1HEX;var p=j.getName;var s=q.getVbyList;if(q.isASN1HEX(o)===false){throw"not ASN.1 hex string"}var m,r;try{m=s(o,0,[0,t,0,1],"06");r=s(o,0,[0,t,1],"03").substr(2)}catch(n){throw"malformed X.509 certificate ECC public key"}this.curveName=p(m);if(this.curveName===null){throw"unsupported curve name"}this.setNamedCurve(this.curveName);this.setPublicKeyHex(r)};if(d!==undefined){if(d.curve!==undefined){this.curveName=d.curve}}if(this.curveName===undefined){this.curveName=f}this.setNamedCurve(this.curveName);if(d!==undefined){if(d.prv!==undefined){this.setPrivateKeyHex(d.prv)}if(d.pub!==undefined){this.setPublicKeyHex(d.pub)}}};KJUR.crypto.ECDSA.parseSigHex=function(a){var b=KJUR.crypto.ECDSA.parseSigHexInHexRS(a);var d=new BigInteger(b.r,16);var c=new BigInteger(b.s,16);return{r:d,s:c}};KJUR.crypto.ECDSA.parseSigHexInHexRS=function(f){var j=ASN1HEX,i=j.getChildIdx,g=j.getV;j.checkStrictDER(f,0);if(f.substr(0,2)!="30"){throw new Error("signature is not a ASN.1 sequence")}var h=i(f,0);if(h.length!=2){throw new Error("signature shall have two elements")}var e=h[0];var d=h[1];if(f.substr(e,2)!="02"){throw new Error("1st item not ASN.1 integer")}if(f.substr(d,2)!="02"){throw new Error("2nd item not ASN.1 integer")}var c=g(f,e);var b=g(f,d);return{r:c,s:b}};KJUR.crypto.ECDSA.asn1SigToConcatSig=function(c){var d=KJUR.crypto.ECDSA.parseSigHexInHexRS(c);var b=d.r;var a=d.s;if(b.substr(0,2)=="00"&&(b.length%32)==2){b=b.substr(2)}if(a.substr(0,2)=="00"&&(a.length%32)==2){a=a.substr(2)}if((b.length%32)==30){b="00"+b}if((a.length%32)==30){a="00"+a}if(b.length%32!=0){throw"unknown ECDSA sig r length error"}if(a.length%32!=0){throw"unknown ECDSA sig s length error"}return b+a};KJUR.crypto.ECDSA.concatSigToASN1Sig=function(a){if((((a.length/2)*8)%(16*8))!=0){throw"unknown ECDSA concatinated r-s sig length error"}var c=a.substr(0,a.length/2);var b=a.substr(a.length/2);return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(c,b)};KJUR.crypto.ECDSA.hexRSSigToASN1Sig=function(b,a){var d=new BigInteger(b,16);var c=new BigInteger(a,16);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(d,c)};KJUR.crypto.ECDSA.biRSSigToASN1Sig=function(f,d){var c=KJUR.asn1;var b=new c.DERInteger({bigint:f});var a=new c.DERInteger({bigint:d});var e=new c.DERSequence({array:[b,a]});return e.getEncodedHex()};KJUR.crypto.ECDSA.getName=function(a){if(a==="2b8104001f"){return"secp192k1"}if(a==="2a8648ce3d030107"){return"secp256r1"}if(a==="2b8104000a"){return"secp256k1"}if(a==="2b81040021"){return"secp224r1"}if(a==="2b81040022"){return"secp384r1"}if("|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(a)!==-1){return"secp256r1"}if("|secp256k1|".indexOf(a)!==-1){return"secp256k1"}if("|secp224r1|NIST P-224|P-224|".indexOf(a)!==-1){return"secp224r1"}if("|secp384r1|NIST P-384|P-384|".indexOf(a)!==-1){return"secp384r1"}return null}; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.crypto=="undefined"||!KJUR.crypto){KJUR.crypto={}}KJUR.crypto.ECParameterDB=new function(){var b={};var c={};function a(d){return new BigInteger(d,16)}this.getByName=function(e){var d=e;if(typeof c[d]!="undefined"){d=c[e]}if(typeof b[d]!="undefined"){return b[d]}throw"unregistered EC curve name: "+d};this.regist=function(A,l,o,g,m,e,j,f,k,u,d,x){b[A]={};var s=a(o);var z=a(g);var y=a(m);var t=a(e);var w=a(j);var r=new ECCurveFp(s,z,y);var q=r.decodePointHex("04"+f+k);b[A]["name"]=A;b[A]["keylen"]=l;b[A]["curve"]=r;b[A]["G"]=q;b[A]["n"]=t;b[A]["h"]=w;b[A]["oid"]=d;b[A]["info"]=x;for(var v=0;v<u.length;v++){c[u[v]]=A}}};KJUR.crypto.ECParameterDB.regist("secp128r1",128,"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC","E87579C11079F43DD824993C2CEE5ED3","FFFFFFFE0000000075A30D1B9038A115","1","161FF7528B899B2D0C28607CA52C5B86","CF5AC8395BAFEB13C02DA292DDED7A83",[],"","secp128r1 : SECG curve over a 128 bit prime field");KJUR.crypto.ECParameterDB.regist("secp160k1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73","0","7","0100000000000000000001B8FA16DFAB9ACA16B6B3","1","3B4C382CE37AA192A4019E763036F4F5DD4D7EBB","938CF935318FDCED6BC28286531733C3F03C4FEE",[],"","secp160k1 : SECG curve over a 160 bit prime field");KJUR.crypto.ECParameterDB.regist("secp160r1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC","1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45","0100000000000000000001F4C8F927AED3CA752257","1","4A96B5688EF573284664698968C38BB913CBFC82","23A628553168947D59DCC912042351377AC5FB32",[],"","secp160r1 : SECG curve over a 160 bit prime field");KJUR.crypto.ECParameterDB.regist("secp192k1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37","0","3","FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D","1","DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D","9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D",[]);KJUR.crypto.ECParameterDB.regist("secp192r1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC","64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1","FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831","1","188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012","07192B95FFC8DA78631011ED6B24CDD573F977A11E794811",[]);KJUR.crypto.ECParameterDB.regist("secp224r1",224,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE","B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4","FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D","1","B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21","BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",[]);KJUR.crypto.ECParameterDB.regist("secp256k1",256,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F","0","7","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141","1","79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798","483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",[]);KJUR.crypto.ECParameterDB.regist("secp256r1",256,"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC","5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B","FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551","1","6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296","4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",["NIST P-256","P-256","prime256v1"]);KJUR.crypto.ECParameterDB.regist("secp384r1",384,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC","B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973","1","AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7","3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",["NIST P-384","P-384"]);KJUR.crypto.ECParameterDB.regist("secp521r1",521,"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC","051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409","1","C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66","011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",["NIST P-521","P-521"]); if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.crypto=="undefined"||!KJUR.crypto){KJUR.crypto={}}KJUR.crypto.DSA=function(){this.p=null;this.q=null;this.g=null;this.y=null;this.x=null;this.type="DSA";this.isPrivate=false;this.isPublic=false;this.setPrivate=function(d,c,b,e,a){this.isPrivate=true;this.p=d;this.q=c;this.g=b;this.y=e;this.x=a};this.setPrivateHex=function(d,b,f,i,j){var c,a,e,g,h;c=new BigInteger(d,16);a=new BigInteger(b,16);e=new BigInteger(f,16);if(typeof i==="string"&&i.length>1){g=new BigInteger(i,16)}else{g=null}h=new BigInteger(j,16);this.setPrivate(c,a,e,g,h)};this.setPublic=function(c,b,a,d){this.isPublic=true;this.p=c;this.q=b;this.g=a;this.y=d;this.x=null};this.setPublicHex=function(f,e,d,g){var b,a,h,c;b=new BigInteger(f,16);a=new BigInteger(e,16);h=new BigInteger(d,16);c=new BigInteger(g,16);this.setPublic(b,a,h,c)};this.signWithMessageHash=function(d){var c=this.p;var b=this.q;var f=this.g;var i=this.y;var j=this.x;var e=KJUR.crypto.Util.getRandomBigIntegerMinToMax(BigInteger.ONE.add(BigInteger.ONE),b.subtract(BigInteger.ONE));var l=d.substr(0,b.bitLength()/4);var h=new BigInteger(l,16);var a=(f.modPow(e,c)).mod(b);var n=(e.modInverse(b).multiply(h.add(j.multiply(a)))).mod(b);var m=KJUR.asn1.ASN1Util.jsonToASN1HEX({seq:[{"int":{bigint:a}},{"int":{bigint:n}}]});return m};this.verifyWithMessageHash=function(h,f){var d=this.p;var b=this.q;var j=this.g;var l=this.y;var i=this.parseASN1Signature(f);var a=i[0];var t=i[1];var o=h.substr(0,b.bitLength()/4);var k=new BigInteger(o,16);if(BigInteger.ZERO.compareTo(a)>0||a.compareTo(b)>0){throw"invalid DSA signature"}if(BigInteger.ZERO.compareTo(t)>=0||t.compareTo(b)>0){throw"invalid DSA signature"}var m=t.modInverse(b);var e=k.multiply(m).mod(b);var c=a.multiply(m).mod(b);var n=j.modPow(e,d).multiply(l.modPow(c,d)).mod(d).mod(b);return n.compareTo(a)==0};this.parseASN1Signature=function(a){try{var d=new BigInteger(ASN1HEX.getVbyList(a,0,[0],"02"),16);var c=new BigInteger(ASN1HEX.getVbyList(a,0,[1],"02"),16);return[d,c]}catch(b){throw"malformed ASN.1 DSA signature"}};this.readPKCS5PrvKeyHex=function(c){var b,a,f,g,i;var j=ASN1HEX;var d=j.getVbyList;if(j.isASN1HEX(c)===false){throw"not ASN.1 hex string"}try{b=d(c,0,[1],"02");a=d(c,0,[2],"02");f=d(c,0,[3],"02");g=d(c,0,[4],"02");i=d(c,0,[5],"02")}catch(e){console.log("EXCEPTION:"+e);throw"malformed PKCS#1/5 plain DSA private key"}this.setPrivateHex(b,a,f,g,i)};this.readPKCS8PrvKeyHex=function(d){var f,c,b,g;var e=ASN1HEX;var i=e.getVbyList;if(e.isASN1HEX(d)===false){throw"not ASN.1 hex string"}try{f=i(d,0,[1,1,0],"02");c=i(d,0,[1,1,1],"02");b=i(d,0,[1,1,2],"02");g=i(d,0,[2,0],"02")}catch(a){console.log("EXCEPTION:"+a);throw"malformed PKCS#8 plain DSA private key"}this.setPrivateHex(f,c,b,null,g)};this.readPKCS8PubKeyHex=function(d){var f,c,b,g;var e=ASN1HEX;var i=e.getVbyList;if(e.isASN1HEX(d)===false){throw"not ASN.1 hex string"}try{f=i(d,0,[0,1,0],"02");c=i(d,0,[0,1,1],"02");b=i(d,0,[0,1,2],"02");g=i(d,0,[1,0],"02")}catch(a){console.log("EXCEPTION:"+a);throw"malformed PKCS#8 DSA public key"}this.setPublicHex(f,c,b,g)};this.readCertPubKeyHex=function(c,f){if(f!==5){f=6}var b,a,g,i;var j=ASN1HEX;var d=j.getVbyList;if(j.isASN1HEX(c)===false){throw"not ASN.1 hex string"}try{b=d(c,0,[0,f,0,1,0],"02");a=d(c,0,[0,f,0,1,1],"02");g=d(c,0,[0,f,0,1,2],"02");i=d(c,0,[0,f,1,0],"02")}catch(e){console.log("EXCEPTION:"+e);throw"malformed X.509 certificate DSA public key"}this.setPublicHex(b,a,g,i)}}; var KEYUTIL=function(){var d=function(p,r,q){return k(CryptoJS.AES,p,r,q)};var e=function(p,r,q){return k(CryptoJS.TripleDES,p,r,q)};var a=function(p,r,q){return k(CryptoJS.DES,p,r,q)};var k=function(s,x,u,q){var r=CryptoJS.enc.Hex.parse(x);var w=CryptoJS.enc.Hex.parse(u);var p=CryptoJS.enc.Hex.parse(q);var t={};t.key=w;t.iv=p;t.ciphertext=r;var v=s.decrypt(t,w,{iv:p});return CryptoJS.enc.Hex.stringify(v)};var l=function(p,r,q){return g(CryptoJS.AES,p,r,q)};var o=function(p,r,q){return g(CryptoJS.TripleDES,p,r,q)};var f=function(p,r,q){return g(CryptoJS.DES,p,r,q)};var g=function(t,y,v,q){var s=CryptoJS.enc.Hex.parse(y);var x=CryptoJS.enc.Hex.parse(v);var p=CryptoJS.enc.Hex.parse(q);var w=t.encrypt(s,x,{iv:p});var r=CryptoJS.enc.Hex.parse(w.toString());var u=CryptoJS.enc.Base64.stringify(r);return u};var i={"AES-256-CBC":{proc:d,eproc:l,keylen:32,ivlen:16},"AES-192-CBC":{proc:d,eproc:l,keylen:24,ivlen:16},"AES-128-CBC":{proc:d,eproc:l,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:e,eproc:o,keylen:24,ivlen:8},"DES-CBC":{proc:a,eproc:f,keylen:8,ivlen:8}};var c=function(p){return i[p]["proc"]};var m=function(p){var r=CryptoJS.lib.WordArray.random(p);var q=CryptoJS.enc.Hex.stringify(r);return q};var n=function(v){var w={};var q=v.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));if(q){w.cipher=q[1];w.ivsalt=q[2]}var p=v.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));if(p){w.type=p[1]}var u=-1;var x=0;if(v.indexOf("\r\n\r\n")!=-1){u=v.indexOf("\r\n\r\n");x=2}if(v.indexOf("\n\n")!=-1){u=v.indexOf("\n\n");x=1}var t=v.indexOf("-----END");if(u!=-1&&t!=-1){var r=v.substring(u+x*2,t-x);r=r.replace(/\s+/g,"");w.data=r}return w};var j=function(q,y,p){var v=p.substring(0,16);var t=CryptoJS.enc.Hex.parse(v);var r=CryptoJS.enc.Utf8.parse(y);var u=i[q]["keylen"]+i[q]["ivlen"];var x="";var w=null;for(;;){var s=CryptoJS.algo.MD5.create();if(w!=null){s.update(w)}s.update(r);s.update(t);w=s.finalize();x=x+CryptoJS.enc.Hex.stringify(w);if(x.length>=u*2){break}}var z={};z.keyhex=x.substr(0,i[q]["keylen"]*2);z.ivhex=x.substr(i[q]["keylen"]*2,i[q]["ivlen"]*2);return z};var b=function(p,v,r,w){var s=CryptoJS.enc.Base64.parse(p);var q=CryptoJS.enc.Hex.stringify(s);var u=i[v]["proc"];var t=u(q,r,w);return t};var h=function(p,s,q,u){var r=i[s]["eproc"];var t=r(p,q,u);return t};return{version:"1.0.0",parsePKCS5PEM:function(p){return n(p)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(q,p,r){return j(q,p,r)},decryptKeyB64:function(p,r,q,s){return b(p,r,q,s)},getDecryptedKeyHex:function(y,x){var q=n(y);var t=q.type;var r=q.cipher;var p=q.ivsalt;var s=q.data;var w=j(r,x,p);var v=w.keyhex;var u=b(s,r,v,p);return u},getEncryptedPKCS5PEMFromPrvKeyHex:function(x,s,A,t,r){var p="";if(typeof t=="undefined"||t==null){t="AES-256-CBC"}if(typeof i[t]=="undefined"){throw"KEYUTIL unsupported algorithm: "+t}if(typeof r=="undefined"||r==null){var v=i[t]["ivlen"];var u=m(v);r=u.toUpperCase()}var z=j(t,A,r);var y=z.keyhex;var w=h(s,t,y,r);var q=w.replace(/(.{64})/g,"$1\r\n");var p="-----BEGIN "+x+" PRIVATE KEY-----\r\n";p+="Proc-Type: 4,ENCRYPTED\r\n";p+="DEK-Info: "+t+","+r+"\r\n";p+="\r\n";p+=q;p+="\r\n-----END "+x+" PRIVATE KEY-----\r\n";return p},parseHexOfEncryptedPKCS8:function(y){var B=ASN1HEX;var z=B.getChildIdx;var w=B.getV;var t={};var r=z(y,0);if(r.length!=2){throw"malformed format: SEQUENCE(0).items != 2: "+r.length}t.ciphertext=w(y,r[1]);var A=z(y,r[0]);if(A.length!=2){throw"malformed format: SEQUENCE(0.0).items != 2: "+A.length}if(w(y,A[0])!="2a864886f70d01050d"){throw"this only supports pkcs5PBES2"}var p=z(y,A[1]);if(A.length!=2){throw"malformed format: SEQUENCE(0.0.1).items != 2: "+p.length}var q=z(y,p[1]);if(q.length!=2){throw"malformed format: SEQUENCE(0.0.1.1).items != 2: "+q.length}if(w(y,q[0])!="2a864886f70d0307"){throw"this only supports TripleDES"}t.encryptionSchemeAlg="TripleDES";t.encryptionSchemeIV=w(y,q[1]);var s=z(y,p[0]);if(s.length!=2){throw"malformed format: SEQUENCE(0.0.1.0).items != 2: "+s.length}if(w(y,s[0])!="2a864886f70d01050c"){throw"this only supports pkcs5PBKDF2"}var x=z(y,s[1]);if(x.length<2){throw"malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+x.length}t.pbkdf2Salt=w(y,x[0]);var u=w(y,x[1]);try{t.pbkdf2Iter=parseInt(u,16)}catch(v){throw"malformed format pbkdf2Iter: "+u}return t},getPBKDF2KeyHexFromParam:function(u,p){var t=CryptoJS.enc.Hex.parse(u.pbkdf2Salt);var q=u.pbkdf2Iter;var s=CryptoJS.PBKDF2(p,t,{keySize:192/32,iterations:q});var r=CryptoJS.enc.Hex.stringify(s);return r},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(x,y){var r=pemtohex(x,"ENCRYPTED PRIVATE KEY");var p=this.parseHexOfEncryptedPKCS8(r);var u=KEYUTIL.getPBKDF2KeyHexFromParam(p,y);var v={};v.ciphertext=CryptoJS.enc.Hex.parse(p.ciphertext);var t=CryptoJS.enc.Hex.parse(u);var s=CryptoJS.enc.Hex.parse(p.encryptionSchemeIV);var w=CryptoJS.TripleDES.decrypt(v,t,{iv:s});var q=CryptoJS.enc.Hex.stringify(w);return q},getKeyFromEncryptedPKCS8PEM:function(s,q){var p=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(s,q);var r=this.getKeyFromPlainPrivatePKCS8Hex(p);return r},parsePlainPrivatePKCS8Hex:function(s){var v=ASN1HEX;var u=v.getChildIdx;var t=v.getV;var q={};q.algparam=null;if(s.substr(0,2)!="30"){throw"malformed plain PKCS8 private key(code:001)"}var r=u(s,0);if(r.length!=3){throw"malformed plain PKCS8 private key(code:002)"}if(s.substr(r[1],2)!="30"){throw"malformed PKCS8 private key(code:003)"}var p=u(s,r[1]);if(p.length!=2){throw"malformed PKCS8 private key(code:004)"}if(s.substr(p[0],2)!="06"){throw"malformed PKCS8 private key(code:005)"}q.algoid=t(s,p[0]);if(s.substr(p[1],2)=="06"){q.algparam=t(s,p[1])}if(s.substr(r[2],2)!="04"){throw"malformed PKCS8 private key(code:006)"}q.keyidx=v.getVidx(s,r[2]);return q},getKeyFromPlainPrivatePKCS8PEM:function(q){var p=pemtohex(q,"PRIVATE KEY");var r=this.getKeyFromPlainPrivatePKCS8Hex(p);return r},getKeyFromPlainPrivatePKCS8Hex:function(p){var q=this.parsePlainPrivatePKCS8Hex(p);var r;if(q.algoid=="2a864886f70d010101"){r=new RSAKey()}else{if(q.algoid=="2a8648ce380401"){r=new KJUR.crypto.DSA()}else{if(q.algoid=="2a8648ce3d0201"){r=new KJUR.crypto.ECDSA()}else{throw"unsupported private key algorithm"}}}r.readPKCS8PrvKeyHex(p);return r},_getKeyFromPublicPKCS8Hex:function(q){var p;var r=ASN1HEX.getVbyList(q,0,[0,0],"06");if(r==="2a864886f70d010101"){p=new RSAKey()}else{if(r==="2a8648ce380401"){p=new KJUR.crypto.DSA()}else{if(r==="2a8648ce3d0201"){p=new KJUR.crypto.ECDSA()}else{throw"unsupported PKCS#8 public key hex"}}}p.readPKCS8PubKeyHex(q);return p},parsePublicRawRSAKeyHex:function(r){var u=ASN1HEX;var t=u.getChildIdx;var s=u.getV;var p={};if(r.substr(0,2)!="30"){throw"malformed RSA key(code:001)"}var q=t(r,0);if(q.length!=2){throw"malformed RSA key(code:002)"}if(r.substr(q[0],2)!="02"){throw"malformed RSA key(code:003)"}p.n=s(r,q[0]);if(r.substr(q[1],2)!="02"){throw"malformed RSA key(code:004)"}p.e=s(r,q[1]);return p},parsePublicPKCS8Hex:function(t){var v=ASN1HEX;var u=v.getChildIdx;var s=v.getV;var q={};q.algparam=null;var r=u(t,0);if(r.length!=2){throw"outer DERSequence shall have 2 elements: "+r.length}var w=r[0];if(t.substr(w,2)!="30"){throw"malformed PKCS8 public key(code:001)"}var p=u(t,w);if(p.length!=2){throw"malformed PKCS8 public key(code:002)"}if(t.substr(p[0],2)!="06"){throw"malformed PKCS8 public key(code:003)"}q.algoid=s(t,p[0]);if(t.substr(p[1],2)=="06"){q.algparam=s(t,p[1])}else{if(t.substr(p[1],2)=="30"){q.algparam={};q.algparam.p=v.getVbyList(t,p[1],[0],"02");q.algparam.q=v.getVbyList(t,p[1],[1],"02");q.algparam.g=v.getVbyList(t,p[1],[2],"02")}}if(t.substr(r[1],2)!="03"){throw"malformed PKCS8 public key(code:004)"}q.key=s(t,r[1]).substr(2);return q},}}();KEYUTIL.getKey=function(l,k,n){var G=ASN1HEX,L=G.getChildIdx,v=G.getV,d=G.getVbyList,c=KJUR.crypto,i=c.ECDSA,C=c.DSA,w=RSAKey,M=pemtohex,F=KEYUTIL;if(typeof w!="undefined"&&l instanceof w){return l}if(typeof i!="undefined"&&l instanceof i){return l}if(typeof C!="undefined"&&l instanceof C){return l}if(l.curve!==undefined&&l.xy!==undefined&&l.d===undefined){return new i({pub:l.xy,curve:l.curve})}if(l.curve!==undefined&&l.d!==undefined){return new i({prv:l.d,curve:l.curve})}if(l.kty===undefined&&l.n!==undefined&&l.e!==undefined&&l.d===undefined){var P=new w();P.setPublic(l.n,l.e);return P}if(l.kty===undefined&&l.n!==undefined&&l.e!==undefined&&l.d!==undefined&&l.p!==undefined&&l.q!==undefined&&l.dp!==undefined&&l.dq!==undefined&&l.co!==undefined&&l.qi===undefined){var P=new w();P.setPrivateEx(l.n,l.e,l.d,l.p,l.q,l.dp,l.dq,l.co);return P}if(l.kty===undefined&&l.n!==undefined&&l.e!==undefined&&l.d!==undefined&&l.p===undefined){var P=new w();P.setPrivate(l.n,l.e,l.d);return P}if(l.p!==undefined&&l.q!==undefined&&l.g!==undefined&&l.y!==undefined&&l.x===undefined){var P=new C();P.setPublic(l.p,l.q,l.g,l.y);return P}if(l.p!==undefined&&l.q!==undefined&&l.g!==undefined&&l.y!==undefined&&l.x!==undefined){var P=new C();P.setPrivate(l.p,l.q,l.g,l.y,l.x);return P}if(l.kty==="RSA"&&l.n!==undefined&&l.e!==undefined&&l.d===undefined){var P=new w();P.setPublic(b64utohex(l.n),b64utohex(l.e));return P}if(l.kty==="RSA"&&l.n!==undefined&&l.e!==undefined&&l.d!==undefined&&l.p!==undefined&&l.q!==undefined&&l.dp!==undefined&&l.dq!==undefined&&l.qi!==undefined){var P=new w();P.setPrivateEx(b64utohex(l.n),b64utohex(l.e),b64utohex(l.d),b64utohex(l.p),b64utohex(l.q),b64utohex(l.dp),b64utohex(l.dq),b64utohex(l.qi));return P}if(l.kty==="RSA"&&l.n!==undefined&&l.e!==undefined&&l.d!==undefined){var P=new w();P.setPrivate(b64utohex(l.n),b64utohex(l.e),b64utohex(l.d));return P}if(l.kty==="EC"&&l.crv!==undefined&&l.x!==undefined&&l.y!==undefined&&l.d===undefined){var j=new i({curve:l.crv});var t=j.ecparams.keylen/4;var B=("0000000000"+b64utohex(l.x)).slice(-t);var z=("0000000000"+b64utohex(l.y)).slice(-t);var u="04"+B+z;j.setPublicKeyHex(u);return j}if(l.kty==="EC"&&l.crv!==undefined&&l.x!==undefined&&l.y!==undefined&&l.d!==undefined){var j=new i({curve:l.crv});var t=j.ecparams.keylen/4;var B=("0000000000"+b64utohex(l.x)).slice(-t);var z=("0000000000"+b64utohex(l.y)).slice(-t);var u="04"+B+z;var b=("0000000000"+b64utohex(l.d)).slice(-t);j.setPublicKeyHex(u);j.setPrivateKeyHex(b);return j}if(n==="pkcs5prv"){var J=l,G=ASN1HEX,N,P;N=L(J,0);if(N.length===9){P=new w();P.readPKCS5PrvKeyHex(J)}else{if(N.length===6){P=new C();P.readPKCS5PrvKeyHex(J)}else{if(N.length>2&&J.substr(N[1],2)==="04"){P=new i();P.readPKCS5PrvKeyHex(J)}else{throw"unsupported PKCS#1/5 hexadecimal key"}}}return P}if(n==="pkcs8prv"){var P=F.getKeyFromPlainPrivatePKCS8Hex(l);return P}if(n==="pkcs8pub"){return F._getKeyFromPublicPKCS8Hex(l)}if(n==="x509pub"){return X509.getPublicKeyFromCertHex(l)}if(l.indexOf("-END CERTIFICATE-",0)!=-1||l.indexOf("-END X509 CERTIFICATE-",0)!=-1||l.indexOf("-END TRUSTED CERTIFICATE-",0)!=-1){return X509.getPublicKeyFromCertPEM(l)}if(l.indexOf("-END PUBLIC KEY-")!=-1){var O=pemtohex(l,"PUBLIC KEY");return F._getKeyFromPublicPKCS8Hex(O)}if(l.indexOf("-END RSA PRIVATE KEY-")!=-1&&l.indexOf("4,ENCRYPTED")==-1){var m=M(l,"RSA PRIVATE KEY");return F.getKey(m,null,"pkcs5prv")}if(l.indexOf("-END DSA PRIVATE KEY-")!=-1&&l.indexOf("4,ENCRYPTED")==-1){var I=M(l,"DSA PRIVATE KEY");var E=d(I,0,[1],"02");var D=d(I,0,[2],"02");var K=d(I,0,[3],"02");var r=d(I,0,[4],"02");var s=d(I,0,[5],"02");var P=new C();P.setPrivate(new BigInteger(E,16),new BigInteger(D,16),new BigInteger(K,16),new BigInteger(r,16),new BigInteger(s,16));return P}if(l.indexOf("-END EC PRIVATE KEY-")!=-1&&l.indexOf("4,ENCRYPTED")==-1){var m=M(l,"EC PRIVATE KEY");return F.getKey(m,null,"pkcs5prv")}if(l.indexOf("-END PRIVATE KEY-")!=-1){return F.getKeyFromPlainPrivatePKCS8PEM(l)}if(l.indexOf("-END RSA PRIVATE KEY-")!=-1&&l.indexOf("4,ENCRYPTED")!=-1){var o=F.getDecryptedKeyHex(l,k);var H=new RSAKey();H.readPKCS5PrvKeyHex(o);return H}if(l.indexOf("-END EC PRIVATE KEY-")!=-1&&l.indexOf("4,ENCRYPTED")!=-1){var I=F.getDecryptedKeyHex(l,k);var P=d(I,0,[1],"04");var f=d(I,0,[2,0],"06");var A=d(I,0,[3,0],"03").substr(2);var e="";if(KJUR.crypto.OID.oidhex2name[f]!==undefined){e=KJUR.crypto.OID.oidhex2name[f]}else{throw"undefined OID(hex) in KJUR.crypto.OID: "+f}var j=new i({curve:e});j.setPublicKeyHex(A);j.setPrivateKeyHex(P);j.isPublic=false;return j}if(l.indexOf("-END DSA PRIVATE KEY-")!=-1&&l.indexOf("4,ENCRYPTED")!=-1){var I=F.getDecryptedKeyHex(l,k);var E=d(I,0,[1],"02");var D=d(I,0,[2],"02");var K=d(I,0,[3],"02");var r=d(I,0,[4],"02");var s=d(I,0,[5],"02");var P=new C();P.setPrivate(new BigInteger(E,16),new BigInteger(D,16),new BigInteger(K,16),new BigInteger(r,16),new BigInteger(s,16));return P}if(l.indexOf("-END ENCRYPTED PRIVATE KEY-")!=-1){return F.getKeyFromEncryptedPKCS8PEM(l,k)}throw"not supported argument"};KEYUTIL.generateKeypair=function(a,c){if(a=="RSA"){var b=c;var h=new RSAKey();h.generate(b,"10001");h.isPrivate=true;h.isPublic=true;var f=new RSAKey();var e=h.n.toString(16);var i=h.e.toString(16);f.setPublic(e,i);f.isPrivate=false;f.isPublic=true;var k={};k.prvKeyObj=h;k.pubKeyObj=f;return k}else{if(a=="EC"){var d=c;var g=new KJUR.crypto.ECDSA({curve:d});var j=g.generateKeyPairHex();var h=new KJUR.crypto.ECDSA({curve:d});h.setPublicKeyHex(j.ecpubhex);h.setPrivateKeyHex(j.ecprvhex);h.isPrivate=true;h.isPublic=false;var f=new KJUR.crypto.ECDSA({curve:d});f.setPublicKeyHex(j.ecpubhex);f.isPrivate=false;f.isPublic=true;var k={};k.prvKeyObj=h;k.pubKeyObj=f;return k}else{throw"unknown algorithm: "+a}}};KEYUTIL.getPEM=function(b,D,y,m,q,j){var F=KJUR,k=F.asn1,z=k.DERObjectIdentifier,f=k.DERInteger,l=k.ASN1Util.newObject,a=k.x509,C=a.SubjectPublicKeyInfo,e=F.crypto,u=e.DSA,r=e.ECDSA,n=RSAKey;function A(s){var G=l({seq:[{"int":0},{"int":{bigint:s.n}},{"int":s.e},{"int":{bigint:s.d}},{"int":{bigint:s.p}},{"int":{bigint:s.q}},{"int":{bigint:s.dmp1}},{"int":{bigint:s.dmq1}},{"int":{bigint:s.coeff}}]});return G}function B(G){var s=l({seq:[{"int":1},{octstr:{hex:G.prvKeyHex}},{tag:["a0",true,{oid:{name:G.curveName}}]},{tag:["a1",true,{bitstr:{hex:"00"+G.pubKeyHex}}]}]});return s}function x(s){var G=l({seq:[{"int":0},{"int":{bigint:s.p}},{"int":{bigint:s.q}},{"int":{bigint:s.g}},{"int":{bigint:s.y}},{"int":{bigint:s.x}}]});return G}if(((n!==undefined&&b instanceof n)||(u!==undefined&&b instanceof u)||(r!==undefined&&b instanceof r))&&b.isPublic==true&&(D===undefined||D=="PKCS8PUB")){var E=new C(b);var w=E.getEncodedHex();return hextopem(w,"PUBLIC KEY")}if(D=="PKCS1PRV"&&n!==undefined&&b instanceof n&&(y===undefined||y==null)&&b.isPrivate==true){var E=A(b);var w=E.getEncodedHex();return hextopem(w,"RSA PRIVATE KEY")}if(D=="PKCS1PRV"&&r!==undefined&&b instanceof r&&(y===undefined||y==null)&&b.isPrivate==true){var i=new z({name:b.curveName});var v=i.getEncodedHex();var h=B(b);var t=h.getEncodedHex();var p="";p+=hextopem(v,"EC PARAMETERS");p+=hextopem(t,"EC PRIVATE KEY");return p}if(D=="PKCS1PRV"&&u!==undefined&&b instanceof u&&(y===undefined||y==null)&&b.isPrivate==true){var E=x(b);var w=E.getEncodedHex();return hextopem(w,"DSA PRIVATE KEY")}if(D=="PKCS5PRV"&&n!==undefined&&b instanceof n&&(y!==undefined&&y!=null)&&b.isPrivate==true){var E=A(b);var w=E.getEncodedHex();if(m===undefined){m="DES-EDE3-CBC"}return this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",w,y,m,j)}if(D=="PKCS5PRV"&&r!==undefined&&b instanceof r&&(y!==undefined&&y!=null)&&b.isPrivate==true){var E=B(b);var w=E.getEncodedHex();if(m===undefined){m="DES-EDE3-CBC"}return this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",w,y,m,j)}if(D=="PKCS5PRV"&&u!==undefined&&b instanceof u&&(y!==undefined&&y!=null)&&b.isPrivate==true){var E=x(b);var w=E.getEncodedHex();if(m===undefined){m="DES-EDE3-CBC"}return this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",w,y,m,j)}var o=function(G,s){var I=c(G,s);var H=new l({seq:[{seq:[{oid:{name:"pkcs5PBES2"}},{seq:[{seq:[{oid:{name:"pkcs5PBKDF2"}},{seq:[{octstr:{hex:I.pbkdf2Salt}},{"int":I.pbkdf2Iter}]}]},{seq:[{oid:{name:"des-EDE3-CBC"}},{octstr:{hex:I.encryptionSchemeIV}}]}]}]},{octstr:{hex:I.ciphertext}}]});return H.getEncodedHex()};var c=function(N,O){var H=100;var M=CryptoJS.lib.WordArray.random(8);var L="DES-EDE3-CBC";var s=CryptoJS.lib.WordArray.random(8);var I=CryptoJS.PBKDF2(O,M,{keySize:192/32,iterations:H});var J=CryptoJS.enc.Hex.parse(N);var K=CryptoJS.TripleDES.encrypt(J,I,{iv:s})+"";var G={};G.ciphertext=K;G.pbkdf2Salt=CryptoJS.enc.Hex.stringify(M);G.pbkdf2Iter=H;G.encryptionSchemeAlg=L;G.encryptionSchemeIV=CryptoJS.enc.Hex.stringify(s);return G};if(D=="PKCS8PRV"&&n!=undefined&&b instanceof n&&b.isPrivate==true){var g=A(b);var d=g.getEncodedHex();var E=l({seq:[{"int":0},{seq:[{oid:{name:"rsaEncryption"}},{"null":true}]},{octstr:{hex:d}}]});var w=E.getEncodedHex();if(y===undefined||y==null){return hextopem(w,"PRIVATE KEY")}else{var t=o(w,y);return hextopem(t,"ENCRYPTED PRIVATE KEY")}}if(D=="PKCS8PRV"&&r!==undefined&&b instanceof r&&b.isPrivate==true){var g=new l({seq:[{"int":1},{octstr:{hex:b.prvKeyHex}},{tag:["a1",true,{bitstr:{hex:"00"+b.pubKeyHex}}]}]});var d=g.getEncodedHex();var E=l({seq:[{"int":0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:b.curveName}}]},{octstr:{hex:d}}]});var w=E.getEncodedHex();if(y===undefined||y==null){return hextopem(w,"PRIVATE KEY")}else{var t=o(w,y);return hextopem(t,"ENCRYPTED PRIVATE KEY")}}if(D=="PKCS8PRV"&&u!==undefined&&b instanceof u&&b.isPrivate==true){var g=new f({bigint:b.x});var d=g.getEncodedHex();var E=l({seq:[{"int":0},{seq:[{oid:{name:"dsa"}},{seq:[{"int":{bigint:b.p}},{"int":{bigint:b.q}},{"int":{bigint:b.g}}]}]},{octstr:{hex:d}}]});var w=E.getEncodedHex();if(y===undefined||y==null){return hextopem(w,"PRIVATE KEY")}else{var t=o(w,y);return hextopem(t,"ENCRYPTED PRIVATE KEY")}}throw"unsupported object nor format"};KEYUTIL.getKeyFromCSRPEM=function(b){var a=pemtohex(b,"CERTIFICATE REQUEST");var c=KEYUTIL.getKeyFromCSRHex(a);return c};KEYUTIL.getKeyFromCSRHex=function(a){var c=KEYUTIL.parseCSRHex(a);var b=KEYUTIL.getKey(c.p8pubkeyhex,null,"pkcs8pub");return b};KEYUTIL.parseCSRHex=function(d){var i=ASN1HEX;var f=i.getChildIdx;var c=i.getTLV;var b={};var g=d;if(g.substr(0,2)!="30"){throw"malformed CSR(code:001)"}var e=f(g,0);if(e.length<1){throw"malformed CSR(code:002)"}if(g.substr(e[0],2)!="30"){throw"malformed CSR(code:003)"}var a=f(g,e[0]);if(a.length<3){throw"malformed CSR(code:004)"}b.p8pubkeyhex=c(g,a[2]);return b};KEYUTIL.getKeyID=function(f){var c=KEYUTIL;var e=ASN1HEX;if(typeof f==="string"&&f.indexOf("BEGIN ")!=-1){f=c.getKey(f)}var d=pemtohex(c.getPEM(f));var b=e.getIdxbyList(d,0,[1]);var a=e.getV(d,b).substring(2);return KJUR.crypto.Util.hashHex(a,"sha1")};KEYUTIL.getJWKFromKey=function(d){var b={};if(d instanceof RSAKey&&d.isPrivate){b.kty="RSA";b.n=hextob64u(d.n.toString(16));b.e=hextob64u(d.e.toString(16));b.d=hextob64u(d.d.toString(16));b.p=hextob64u(d.p.toString(16));b.q=hextob64u(d.q.toString(16));b.dp=hextob64u(d.dmp1.toString(16));b.dq=hextob64u(d.dmq1.toString(16));b.qi=hextob64u(d.coeff.toString(16));return b}else{if(d instanceof RSAKey&&d.isPublic){b.kty="RSA";b.n=hextob64u(d.n.toString(16));b.e=hextob64u(d.e.toString(16));return b}else{if(d instanceof KJUR.crypto.ECDSA&&d.isPrivate){var a=d.getShortNISTPCurveName();if(a!=="P-256"&&a!=="P-384"){throw"unsupported curve name for JWT: "+a}var c=d.getPublicKeyXYHex();b.kty="EC";b.crv=a;b.x=hextob64u(c.x);b.y=hextob64u(c.y);b.d=hextob64u(d.prvKeyHex);return b}else{if(d instanceof KJUR.crypto.ECDSA&&d.isPublic){var a=d.getShortNISTPCurveName();if(a!=="P-256"&&a!=="P-384"){throw"unsupported curve name for JWT: "+a}var c=d.getPublicKeyXYHex();b.kty="EC";b.crv=a;b.x=hextob64u(c.x);b.y=hextob64u(c.y);return b}}}}throw"not supported key object"}; RSAKey.getPosArrayOfChildrenFromHex=function(a){return ASN1HEX.getChildIdx(a,0)};RSAKey.getHexValueArrayOfChildrenFromHex=function(f){var n=ASN1HEX;var i=n.getV;var k=RSAKey.getPosArrayOfChildrenFromHex(f);var e=i(f,k[0]);var j=i(f,k[1]);var b=i(f,k[2]);var c=i(f,k[3]);var h=i(f,k[4]);var g=i(f,k[5]);var m=i(f,k[6]);var l=i(f,k[7]);var d=i(f,k[8]);var k=new Array();k.push(e,j,b,c,h,g,m,l,d);return k};RSAKey.prototype.readPrivateKeyFromPEMString=function(d){var c=pemtohex(d);var b=RSAKey.getHexValueArrayOfChildrenFromHex(c);this.setPrivateEx(b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8])};RSAKey.prototype.readPKCS5PrvKeyHex=function(c){var b=RSAKey.getHexValueArrayOfChildrenFromHex(c);this.setPrivateEx(b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8])};RSAKey.prototype.readPKCS8PrvKeyHex=function(e){var c,j,l,b,a,f,d,k;var m=ASN1HEX;var g=m.getVbyList;if(m.isASN1HEX(e)===false){throw"not ASN.1 hex string"}try{c=g(e,0,[2,0,1],"02");j=g(e,0,[2,0,2],"02");l=g(e,0,[2,0,3],"02");b=g(e,0,[2,0,4],"02");a=g(e,0,[2,0,5],"02");f=g(e,0,[2,0,6],"02");d=g(e,0,[2,0,7],"02");k=g(e,0,[2,0,8],"02")}catch(i){throw"malformed PKCS#8 plain RSA private key"}this.setPrivateEx(c,j,l,b,a,f,d,k)};RSAKey.prototype.readPKCS5PubKeyHex=function(c){var e=ASN1HEX;var b=e.getV;if(e.isASN1HEX(c)===false){throw"keyHex is not ASN.1 hex string"}var a=e.getChildIdx(c,0);if(a.length!==2||c.substr(a[0],2)!=="02"||c.substr(a[1],2)!=="02"){throw"wrong hex for PKCS#5 public key"}var f=b(c,a[0]);var d=b(c,a[1]);this.setPublic(f,d)};RSAKey.prototype.readPKCS8PubKeyHex=function(b){var c=ASN1HEX;if(c.isASN1HEX(b)===false){throw"not ASN.1 hex string"}if(c.getTLVbyList(b,0,[0,0])!=="06092a864886f70d010101"){throw"not PKCS8 RSA public key"}var a=c.getTLVbyList(b,0,[1,0]);this.readPKCS5PubKeyHex(a)};RSAKey.prototype.readCertPubKeyHex=function(b,d){var a,c;a=new X509();a.readCertHex(b);c=a.getPublicKeyHex();this.readPKCS8PubKeyHex(c)}; var _RE_HEXDECONLY=new RegExp("[^0-9a-f]","gi");function _rsasign_getHexPaddedDigestInfoForString(d,e,a){var b=function(f){return KJUR.crypto.Util.hashString(f,a)};var c=b(d);return KJUR.crypto.Util.getPaddedDigestInfoHex(c,a,e)}function _zeroPaddingOfSignature(e,d){var c="";var a=d/4-e.length;for(var b=0;b<a;b++){c=c+"0"}return c+e}RSAKey.prototype.sign=function(d,a){var b=function(e){return KJUR.crypto.Util.hashString(e,a)};var c=b(d);return this.signWithMessageHash(c,a)};RSAKey.prototype.signWithMessageHash=function(e,c){var f=KJUR.crypto.Util.getPaddedDigestInfoHex(e,c,this.n.bitLength());var b=parseBigInt(f,16);var d=this.doPrivate(b);var a=d.toString(16);return _zeroPaddingOfSignature(a,this.n.bitLength())};function pss_mgf1_str(c,a,e){var b="",d=0;while(b.length<a){b+=hextorstr(e(rstrtohex(c+String.fromCharCode.apply(String,[(d&4278190080)>>24,(d&16711680)>>16,(d&65280)>>8,d&255]))));d+=1}return b}RSAKey.prototype.signPSS=function(e,a,d){var c=function(f){return KJUR.crypto.Util.hashHex(f,a)};var b=c(rstrtohex(e));if(d===undefined){d=-1}return this.signWithMessageHashPSS(b,a,d)};RSAKey.prototype.signWithMessageHashPSS=function(l,a,k){var b=hextorstr(l);var g=b.length;var m=this.n.bitLength()-1;var c=Math.ceil(m/8);var d;var o=function(i){return KJUR.crypto.Util.hashHex(i,a)};if(k===-1||k===undefined){k=g}else{if(k===-2){k=c-g-2}else{if(k<-2){throw"invalid salt length"}}}if(c<(g+k+2)){throw"data too long"}var f="";if(k>0){f=new Array(k);new SecureRandom().nextBytes(f);f=String.fromCharCode.apply(String,f)}var n=hextorstr(o(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+b+f)));var j=[];for(d=0;d<c-k-g-2;d+=1){j[d]=0}var e=String.fromCharCode.apply(String,j)+"\x01"+f;var h=pss_mgf1_str(n,e.length,o);var q=[];for(d=0;d<e.length;d+=1){q[d]=e.charCodeAt(d)^h.charCodeAt(d)}var p=(65280>>(8*c-m))&255;q[0]&=~p;for(d=0;d<g;d++){q.push(n.charCodeAt(d))}q.push(188);return _zeroPaddingOfSignature(this.doPrivate(new BigInteger(q)).toString(16),this.n.bitLength())};function _rsasign_getDecryptSignatureBI(a,d,c){var b=new RSAKey();b.setPublic(d,c);var e=b.doPublic(a);return e}function _rsasign_getHexDigestInfoFromSig(a,c,b){var e=_rsasign_getDecryptSignatureBI(a,c,b);var d=e.toString(16).replace(/^1f+00/,"");return d}function _rsasign_getAlgNameAndHashFromHexDisgestInfo(f){for(var e in KJUR.crypto.Util.DIGESTINFOHEAD){var d=KJUR.crypto.Util.DIGESTINFOHEAD[e];var b=d.length;if(f.substring(0,b)==d){var c=[e,f.substring(b)];return c}}return[]}RSAKey.prototype.verify=function(f,j){j=j.replace(_RE_HEXDECONLY,"");j=j.replace(/[ \n]+/g,"");var b=parseBigInt(j,16);if(b.bitLength()>this.n.bitLength()){return 0}var i=this.doPublic(b);var e=i.toString(16).replace(/^1f+00/,"");var g=_rsasign_getAlgNameAndHashFromHexDisgestInfo(e);if(g.length==0){return false}var d=g[0];var h=g[1];var a=function(k){return KJUR.crypto.Util.hashString(k,d)};var c=a(f);return(h==c)};RSAKey.prototype.verifyWithMessageHash=function(e,a){if(a.length!=Math.ceil(this.n.bitLength()/4)){return false}var b=parseBigInt(a,16);if(b.bitLength()>this.n.bitLength()){return 0}var h=this.doPublic(b);var g=h.toString(16).replace(/^1f+00/,"");var c=_rsasign_getAlgNameAndHashFromHexDisgestInfo(g);if(c.length==0){return false}var d=c[0];var f=c[1];return(f==e)};RSAKey.prototype.verifyPSS=function(c,b,a,f){var e=function(g){return KJUR.crypto.Util.hashHex(g,a)};var d=e(rstrtohex(c));if(f===undefined){f=-1}return this.verifyWithMessageHashPSS(d,b,a,f)};RSAKey.prototype.verifyWithMessageHashPSS=function(f,s,l,c){if(s.length!=Math.ceil(this.n.bitLength()/4)){return false}var k=new BigInteger(s,16);var r=function(i){return KJUR.crypto.Util.hashHex(i,l)};var j=hextorstr(f);var h=j.length;var g=this.n.bitLength()-1;var m=Math.ceil(g/8);var q;if(c===-1||c===undefined){c=h}else{if(c===-2){c=m-h-2}else{if(c<-2){throw"invalid salt length"}}}if(m<(h+c+2)){throw"data too long"}var a=this.doPublic(k).toByteArray();for(q=0;q<a.length;q+=1){a[q]&=255}while(a.length<m){a.unshift(0)}if(a[m-1]!==188){throw"encoded message does not end in 0xbc"}a=String.fromCharCode.apply(String,a);var d=a.substr(0,m-h-1);var e=a.substr(d.length,h);var p=(65280>>(8*m-g))&255;if((d.charCodeAt(0)&p)!==0){throw"bits beyond keysize not zero"}var n=pss_mgf1_str(e,d.length,r);var o=[];for(q=0;q<d.length;q+=1){o[q]=d.charCodeAt(q)^n.charCodeAt(q)}o[0]&=~p;var b=m-h-c-2;for(q=0;q<b;q+=1){if(o[q]!==0){throw"leftmost octets not zero"}}if(o[b]!==1){throw"0x01 marker not found"}return e===hextorstr(r(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+j+String.fromCharCode.apply(String,o.slice(-c)))))};RSAKey.SALT_LEN_HLEN=-1;RSAKey.SALT_LEN_MAX=-2;RSAKey.SALT_LEN_RECOVER=-2; function X509(){var k=ASN1HEX,j=k.getChildIdx,h=k.getV,b=k.getTLV,f=k.getVbyList,c=k.getTLVbyList,g=k.getIdxbyList,d=k.getVidx,i=k.oidname,a=X509,e=pemtohex;this.hex=null;this.version=0;this.foffset=0;this.aExtInfo=null;this.getVersion=function(){if(this.hex===null||this.version!==0){return this.version}if(c(this.hex,0,[0,0])!=="a003020102"){this.version=1;this.foffset=-1;return 1}this.version=3;return 3};this.getSerialNumberHex=function(){return f(this.hex,0,[0,1+this.foffset],"02")};this.getSignatureAlgorithmField=function(){return i(f(this.hex,0,[0,2+this.foffset,0],"06"))};this.getIssuerHex=function(){return c(this.hex,0,[0,3+this.foffset],"30")};this.getIssuerString=function(){return a.hex2dn(this.getIssuerHex())};this.getSubjectHex=function(){return c(this.hex,0,[0,5+this.foffset],"30")};this.getSubjectString=function(){return a.hex2dn(this.getSubjectHex())};this.getNotBefore=function(){var l=f(this.hex,0,[0,4+this.foffset,0]);l=l.replace(/(..)/g,"%$1");l=decodeURIComponent(l);return l};this.getNotAfter=function(){var l=f(this.hex,0,[0,4+this.foffset,1]);l=l.replace(/(..)/g,"%$1");l=decodeURIComponent(l);return l};this.getPublicKeyHex=function(){return k.getTLVbyList(this.hex,0,[0,6+this.foffset],"30")};this.getPublicKeyIdx=function(){return g(this.hex,0,[0,6+this.foffset],"30")};this.getPublicKeyContentIdx=function(){var l=this.getPublicKeyIdx();return g(this.hex,l,[1,0],"30")};this.getPublicKey=function(){return KEYUTIL.getKey(this.getPublicKeyHex(),null,"pkcs8pub")};this.getSignatureAlgorithmName=function(){return i(f(this.hex,0,[1,0],"06"))};this.getSignatureValueHex=function(){return f(this.hex,0,[2],"03",true)};this.verifySignature=function(n){var o=this.getSignatureAlgorithmName();var l=this.getSignatureValueHex();var m=c(this.hex,0,[0],"30");var p=new KJUR.crypto.Signature({alg:o});p.init(n);p.updateHex(m);return p.verify(l)};this.parseExt=function(u){var n,l,p;if(u===undefined){p=this.hex;if(this.version!==3){return -1}n=g(p,0,[0,7,0],"30");l=j(p,n)}else{p=pemtohex(u);var q=g(p,0,[0,3,0,0],"06");if(h(p,q)!="2a864886f70d01090e"){this.aExtInfo=new Array();return}n=g(p,0,[0,3,0,1,0],"30");l=j(p,n);this.hex=p}this.aExtInfo=new Array();for(var o=0;o<l.length;o++){var s={};s.critical=false;var r=j(p,l[o]);var m=0;if(r.length===3){s.critical=true;m=1}s.oid=k.hextooidstr(f(p,l[o],[0],"06"));var t=g(p,l[o],[1+m]);s.vidx=d(p,t);this.aExtInfo.push(s)}};this.getExtInfo=function(n){var l=this.aExtInfo;var o=n;if(!n.match(/^[0-9.]+$/)){o=KJUR.asn1.x509.OID.name2oid(n)}if(o===""){return undefined}for(var m=0;m<l.length;m++){if(l[m].oid===o){return l[m]}}return undefined};this.getExtBasicConstraints=function(){var n=this.getExtInfo("basicConstraints");if(n===undefined){return n}var l=h(this.hex,n.vidx);if(l===""){return{}}if(l==="0101ff"){return{cA:true}}if(l.substr(0,8)==="0101ff02"){var o=h(l,6);var m=parseInt(o,16);return{cA:true,pathLen:m}}throw"basicConstraints parse error"};this.getExtKeyUsageBin=function(){var o=this.getExtInfo("keyUsage");if(o===undefined){return""}var m=h(this.hex,o.vidx);if(m.length%2!=0||m.length<=2){throw"malformed key usage value"}var l=parseInt(m.substr(0,2));var n=parseInt(m.substr(2),16).toString(2);return n.substr(0,n.length-l)};this.getExtKeyUsageString=function(){var n=this.getExtKeyUsageBin();var l=new Array();for(var m=0;m<n.length;m++){if(n.substr(m,1)=="1"){l.push(X509.KEYUSAGE_NAME[m])}}return l.join(",")};this.getExtSubjectKeyIdentifier=function(){var l=this.getExtInfo("subjectKeyIdentifier");if(l===undefined){return l}return h(this.hex,l.vidx)};this.getExtAuthorityKeyIdentifier=function(){var p=this.getExtInfo("authorityKeyIdentifier");if(p===undefined){return p}var l={};var o=b(this.hex,p.vidx);var m=j(o,0);for(var n=0;n<m.length;n++){if(o.substr(m[n],2)==="80"){l.kid=h(o,m[n])}}return l};this.getExtExtKeyUsageName=function(){var p=this.getExtInfo("extKeyUsage");if(p===undefined){return p}var l=new Array();var o=b(this.hex,p.vidx);if(o===""){return l}var m=j(o,0);for(var n=0;n<m.length;n++){l.push(i(h(o,m[n])))}return l};this.getExtSubjectAltName=function(){var m=this.getExtSubjectAltName2();var l=new Array();for(var n=0;n<m.length;n++){if(m[n][0]==="DNS"){l.push(m[n][1])}}return l};this.getExtSubjectAltName2=function(){var p,s,r;var q=this.getExtInfo("subjectAltName");if(q===undefined){return q}var l=new Array();var o=b(this.hex,q.vidx);var m=j(o,0);for(var n=0;n<m.length;n++){r=o.substr(m[n],2);p=h(o,m[n]);if(r==="81"){s=hextoutf8(p);l.push(["MAIL",s])}if(r==="82"){s=hextoutf8(p);l.push(["DNS",s])}if(r==="84"){s=X509.hex2dn(p,0);l.push(["DN",s])}if(r==="86"){s=hextoutf8(p);l.push(["URI",s])}if(r==="87"){s=hextoip(p);l.push(["IP",s])}}return l};this.getExtCRLDistributionPointsURI=function(){var q=this.getExtInfo("cRLDistributionPoints");if(q===undefined){return q}var l=new Array();var m=j(this.hex,q.vidx);for(var o=0;o<m.length;o++){try{var r=f(this.hex,m[o],[0,0,0],"86");var p=hextoutf8(r);l.push(p)}catch(n){}}return l};this.getExtAIAInfo=function(){var p=this.getExtInfo("authorityInfoAccess");if(p===undefined){return p}var l={ocsp:[],caissuer:[]};var m=j(this.hex,p.vidx);for(var n=0;n<m.length;n++){var q=f(this.hex,m[n],[0],"06");var o=f(this.hex,m[n],[1],"86");if(q==="2b06010505073001"){l.ocsp.push(hextoutf8(o))}if(q==="2b06010505073002"){l.caissuer.push(hextoutf8(o))}}return l};this.getExtCertificatePolicies=function(){var o=this.getExtInfo("certificatePolicies");if(o===undefined){return o}var l=b(this.hex,o.vidx);var u=[];var s=j(l,0);for(var r=0;r<s.length;r++){var t={};var n=j(l,s[r]);t.id=i(h(l,n[0]));if(n.length===2){var m=j(l,n[1]);for(var q=0;q<m.length;q++){var p=f(l,m[q],[0],"06");if(p==="2b06010505070201"){t.cps=hextoutf8(f(l,m[q],[1]))}else{if(p==="2b06010505070202"){t.unotice=hextoutf8(f(l,m[q],[1,0]))}}}}u.push(t)}return u};this.readCertPEM=function(l){this.readCertHex(e(l))};this.readCertHex=function(l){this.hex=l;this.getVersion();try{g(this.hex,0,[0,7],"a3");this.parseExt()}catch(m){}};this.getInfo=function(){var m=X509;var B,u,z;B="Basic Fields\n";B+=" serial number: "+this.getSerialNumberHex()+"\n";B+=" signature algorithm: "+this.getSignatureAlgorithmField()+"\n";B+=" issuer: "+this.getIssuerString()+"\n";B+=" notBefore: "+this.getNotBefore()+"\n";B+=" notAfter: "+this.getNotAfter()+"\n";B+=" subject: "+this.getSubjectString()+"\n";B+=" subject public key info: \n";u=this.getPublicKey();B+=" key algorithm: "+u.type+"\n";if(u.type==="RSA"){B+=" n="+hextoposhex(u.n.toString(16)).substr(0,16)+"...\n";B+=" e="+hextoposhex(u.e.toString(16))+"\n"}z=this.aExtInfo;if(z!==undefined&&z!==null){B+="X509v3 Extensions:\n";for(var r=0;r<z.length;r++){var n=z[r];var A=KJUR.asn1.x509.OID.oid2name(n.oid);if(A===""){A=n.oid}var x="";if(n.critical===true){x="CRITICAL"}B+=" "+A+" "+x+":\n";if(A==="basicConstraints"){var v=this.getExtBasicConstraints();if(v.cA===undefined){B+=" {}\n"}else{B+=" cA=true";if(v.pathLen!==undefined){B+=", pathLen="+v.pathLen}B+="\n"}}else{if(A==="keyUsage"){B+=" "+this.getExtKeyUsageString()+"\n"}else{if(A==="subjectKeyIdentifier"){B+=" "+this.getExtSubjectKeyIdentifier()+"\n"}else{if(A==="authorityKeyIdentifier"){var l=this.getExtAuthorityKeyIdentifier();if(l.kid!==undefined){B+=" kid="+l.kid+"\n"}}else{if(A==="extKeyUsage"){var w=this.getExtExtKeyUsageName();B+=" "+w.join(", ")+"\n"}else{if(A==="subjectAltName"){var t=this.getExtSubjectAltName2();B+=" "+t+"\n"}else{if(A==="cRLDistributionPoints"){var y=this.getExtCRLDistributionPointsURI();B+=" "+y+"\n"}else{if(A==="authorityInfoAccess"){var p=this.getExtAIAInfo();if(p.ocsp!==undefined){B+=" ocsp: "+p.ocsp.join(",")+"\n"}if(p.caissuer!==undefined){B+=" caissuer: "+p.caissuer.join(",")+"\n"}}else{if(A==="certificatePolicies"){var o=this.getExtCertificatePolicies();for(var q=0;q<o.length;q++){if(o[q].id!==undefined){B+=" policy oid: "+o[q].id+"\n"}if(o[q].cps!==undefined){B+=" cps: "+o[q].cps+"\n"}}}}}}}}}}}}}B+="signature algorithm: "+this.getSignatureAlgorithmName()+"\n";B+="signature: "+this.getSignatureValueHex().substr(0,16)+"...\n";return B}}X509.hex2dn=function(f,b){if(b===undefined){b=0}if(f.substr(b,2)!=="30"){throw"malformed DN"}var c=new Array();var d=ASN1HEX.getChildIdx(f,b);for(var e=0;e<d.length;e++){c.push(X509.hex2rdn(f,d[e]))}c=c.map(function(a){return a.replace("/","\\/")});return"/"+c.join("/")};X509.hex2rdn=function(f,b){if(b===undefined){b=0}if(f.substr(b,2)!=="31"){throw"malformed RDN"}var c=new Array();var d=ASN1HEX.getChildIdx(f,b);for(var e=0;e<d.length;e++){c.push(X509.hex2attrTypeValue(f,d[e]))}c=c.map(function(a){return a.replace("+","\\+")});return c.join("+")};X509.hex2attrTypeValue=function(d,i){var j=ASN1HEX;var h=j.getV;if(i===undefined){i=0}if(d.substr(i,2)!=="30"){throw"malformed attribute type and value"}var g=j.getChildIdx(d,i);if(g.length!==2||d.substr(g[0],2)!=="06"){"malformed attribute type and value"}var b=h(d,g[0]);var f=KJUR.asn1.ASN1Util.oidHexToInt(b);var e=KJUR.asn1.x509.OID.oid2atype(f);var a=h(d,g[1]);var c=hextorstr(a);return e+"="+c};X509.getPublicKeyFromCertHex=function(b){var a=new X509();a.readCertHex(b);return a.getPublicKey()};X509.getPublicKeyFromCertPEM=function(b){var a=new X509();a.readCertPEM(b);return a.getPublicKey()};X509.getPublicKeyInfoPropOfCertPEM=function(c){var e=ASN1HEX;var g=e.getVbyList;var b={};var a,f,d;b.algparam=null;a=new X509();a.readCertPEM(c);f=a.getPublicKeyHex();b.keyhex=g(f,0,[1],"03").substr(2);b.algoid=g(f,0,[0,0],"06");if(b.algoid==="2a8648ce3d0201"){b.algparam=g(f,0,[0,1],"06")}return b};X509.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"]; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.jws=="undefined"||!KJUR.jws){KJUR.jws={}}KJUR.jws.JWS=function(){var b=KJUR,a=b.jws.JWS,c=a.isSafeJSONString;this.parseJWS=function(g,j){if((this.parsedJWS!==undefined)&&(j||(this.parsedJWS.sigvalH!==undefined))){return}var i=g.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(i==null){throw"JWS signature is not a form of 'Head.Payload.SigValue'."}var k=i[1];var e=i[2];var l=i[3];var n=k+"."+e;this.parsedJWS={};this.parsedJWS.headB64U=k;this.parsedJWS.payloadB64U=e;this.parsedJWS.sigvalB64U=l;this.parsedJWS.si=n;if(!j){var h=b64utohex(l);var f=parseBigInt(h,16);this.parsedJWS.sigvalH=h;this.parsedJWS.sigvalBI=f}var d=b64utoutf8(k);var m=b64utoutf8(e);this.parsedJWS.headS=d;this.parsedJWS.payloadS=m;if(!c(d,this.parsedJWS,"headP")){throw"malformed JSON string for JWS Head: "+d}}};KJUR.jws.JWS.sign=function(j,w,z,A,a){var x=KJUR,n=x.jws,r=n.JWS,h=r.readSafeJSONString,q=r.isSafeJSONString,d=x.crypto,l=d.ECDSA,p=d.Mac,c=d.Signature,u=JSON;var t,k,o;if(typeof w!="string"&&typeof w!="object"){throw"spHeader must be JSON string or object: "+w}if(typeof w=="object"){k=w;t=u.stringify(k)}if(typeof w=="string"){t=w;if(!q(t)){throw"JWS Head is not safe JSON string: "+t}k=h(t)}o=z;if(typeof z=="object"){o=u.stringify(z)}if((j==""||j==null)&&k.alg!==undefined){j=k.alg}if((j!=""&&j!=null)&&k.alg===undefined){k.alg=j;t=u.stringify(k)}if(j!==k.alg){throw"alg and sHeader.alg doesn't match: "+j+"!="+k.alg}var s=null;if(r.jwsalg2sigalg[j]===undefined){throw"unsupported alg name: "+j}else{s=r.jwsalg2sigalg[j]}var e=utf8tob64u(t);var m=utf8tob64u(o);var b=e+"."+m;var y="";if(s.substr(0,4)=="Hmac"){if(A===undefined){throw"mac key shall be specified for HS* alg"}var i=new p({alg:s,prov:"cryptojs",pass:A});i.updateString(b);y=i.doFinal()}else{if(s.indexOf("withECDSA")!=-1){var f=new c({alg:s});f.init(A,a);f.updateString(b);var g=f.sign();y=KJUR.crypto.ECDSA.asn1SigToConcatSig(g)}else{if(s!="none"){var f=new c({alg:s});f.init(A,a);f.updateString(b);y=f.sign()}}}var v=hextob64u(y);return b+"."+v};KJUR.jws.JWS.verify=function(w,B,n){var x=KJUR,q=x.jws,t=q.JWS,i=t.readSafeJSONString,e=x.crypto,p=e.ECDSA,s=e.Mac,d=e.Signature,m;if(typeof RSAKey!==undefined){m=RSAKey}var y=w.split(".");if(y.length!==3){return false}var f=y[0];var r=y[1];var c=f+"."+r;var A=b64utohex(y[2]);var l=i(b64utoutf8(y[0]));var k=null;var z=null;if(l.alg===undefined){throw"algorithm not specified in header"}else{k=l.alg;z=k.substr(0,2)}if(n!=null&&Object.prototype.toString.call(n)==="[object Array]"&&n.length>0){var b=":"+n.join(":")+":";if(b.indexOf(":"+k+":")==-1){throw"algorithm '"+k+"' not accepted in the list"}}if(k!="none"&&B===null){throw"key shall be specified to verify."}if(typeof B=="string"&&B.indexOf("-----BEGIN ")!=-1){B=KEYUTIL.getKey(B)}if(z=="RS"||z=="PS"){if(!(B instanceof m)){throw"key shall be a RSAKey obj for RS* and PS* algs"}}if(z=="ES"){if(!(B instanceof p)){throw"key shall be a ECDSA obj for ES* algs"}}if(k=="none"){}var u=null;if(t.jwsalg2sigalg[l.alg]===undefined){throw"unsupported alg name: "+k}else{u=t.jwsalg2sigalg[k]}if(u=="none"){throw"not supported"}else{if(u.substr(0,4)=="Hmac"){var o=null;if(B===undefined){throw"hexadecimal key shall be specified for HMAC"}var j=new s({alg:u,pass:B});j.updateString(c);o=j.doFinal();return A==o}else{if(u.indexOf("withECDSA")!=-1){var h=null;try{h=p.concatSigToASN1Sig(A)}catch(v){return false}var g=new d({alg:u});g.init(B);g.updateString(c);return g.verify(h)}else{var g=new d({alg:u});g.init(B);g.updateString(c);return g.verify(A)}}}};KJUR.jws.JWS.parse=function(g){var c=g.split(".");var b={};var f,e,d;if(c.length!=2&&c.length!=3){throw"malformed sJWS: wrong number of '.' splitted elements"}f=c[0];e=c[1];if(c.length==3){d=c[2]}b.headerObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(f));b.payloadObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(e));b.headerPP=JSON.stringify(b.headerObj,null," ");if(b.payloadObj==null){b.payloadPP=b64utoutf8(e)}else{b.payloadPP=JSON.stringify(b.payloadObj,null," ")}if(d!==undefined){b.sigHex=b64utohex(d)}return b};KJUR.jws.JWS.verifyJWT=function(e,l,r){var d=KJUR,j=d.jws,o=j.JWS,n=o.readSafeJSONString,p=o.inArray,f=o.includedArray;var k=e.split(".");var c=k[0];var i=k[1];var q=c+"."+i;var m=b64utohex(k[2]);var h=n(b64utoutf8(c));var g=n(b64utoutf8(i));if(h.alg===undefined){return false}if(r.alg===undefined){throw"acceptField.alg shall be specified"}if(!p(h.alg,r.alg)){return false}if(g.iss!==undefined&&typeof r.iss==="object"){if(!p(g.iss,r.iss)){return false}}if(g.sub!==undefined&&typeof r.sub==="object"){if(!p(g.sub,r.sub)){return false}}if(g.aud!==undefined&&typeof r.aud==="object"){if(typeof g.aud=="string"){if(!p(g.aud,r.aud)){return false}}else{if(typeof g.aud=="object"){if(!f(g.aud,r.aud)){return false}}}}var b=j.IntDate.getNow();if(r.verifyAt!==undefined&&typeof r.verifyAt==="number"){b=r.verifyAt}if(r.gracePeriod===undefined||typeof r.gracePeriod!=="number"){r.gracePeriod=0}if(g.exp!==undefined&&typeof g.exp=="number"){if(g.exp+r.gracePeriod<b){return false}}if(g.nbf!==undefined&&typeof g.nbf=="number"){if(b<g.nbf-r.gracePeriod){return false}}if(g.iat!==undefined&&typeof g.iat=="number"){if(b<g.iat-r.gracePeriod){return false}}if(g.jti!==undefined&&r.jti!==undefined){if(g.jti!==r.jti){return false}}if(!o.verify(e,l,r.alg)){return false}return true};KJUR.jws.JWS.includedArray=function(b,a){var c=KJUR.jws.JWS.inArray;if(b===null){return false}if(typeof b!=="object"){return false}if(typeof b.length!=="number"){return false}for(var d=0;d<b.length;d++){if(!c(b[d],a)){return false}}return true};KJUR.jws.JWS.inArray=function(d,b){if(b===null){return false}if(typeof b!=="object"){return false}if(typeof b.length!=="number"){return false}for(var c=0;c<b.length;c++){if(b[c]==d){return true}}return false};KJUR.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS384:"HmacSHA384",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none",};KJUR.jws.JWS.isSafeJSONString=function(c,b,d){var e=null;try{e=jsonParse(c);if(typeof e!="object"){return 0}if(e.constructor===Array){return 0}if(b){b[d]=e}return 1}catch(a){return 0}};KJUR.jws.JWS.readSafeJSONString=function(b){var c=null;try{c=jsonParse(b);if(typeof c!="object"){return null}if(c.constructor===Array){return null}return c}catch(a){return null}};KJUR.jws.JWS.getEncodedSignatureValueFromJWS=function(b){var a=b.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(a==null){throw"JWS signature is not a form of 'Head.Payload.SigValue'."}return a[1]};KJUR.jws.JWS.getJWKthumbprint=function(d){if(d.kty!=="RSA"&&d.kty!=="EC"&&d.kty!=="oct"){throw"unsupported algorithm for JWK Thumprint"}var a="{";if(d.kty==="RSA"){if(typeof d.n!="string"||typeof d.e!="string"){throw"wrong n and e value for RSA key"}a+='"e":"'+d.e+'",';a+='"kty":"'+d.kty+'",';a+='"n":"'+d.n+'"}'}else{if(d.kty==="EC"){if(typeof d.crv!="string"||typeof d.x!="string"||typeof d.y!="string"){throw"wrong crv, x and y value for EC key"}a+='"crv":"'+d.crv+'",';a+='"kty":"'+d.kty+'",';a+='"x":"'+d.x+'",';a+='"y":"'+d.y+'"}'}else{if(d.kty==="oct"){if(typeof d.k!="string"){throw"wrong k value for oct(symmetric) key"}a+='"kty":"'+d.kty+'",';a+='"k":"'+d.k+'"}'}}}var b=rstrtohex(a);var c=KJUR.crypto.Util.hashHex(b,"sha256");var e=hextob64u(c);return e};KJUR.jws.IntDate={};KJUR.jws.IntDate.get=function(c){var b=KJUR.jws.IntDate,d=b.getNow,a=b.getZulu;if(c=="now"){return d()}else{if(c=="now + 1hour"){return d()+60*60}else{if(c=="now + 1day"){return d()+60*60*24}else{if(c=="now + 1month"){return d()+60*60*24*30}else{if(c=="now + 1year"){return d()+60*60*24*365}else{if(c.match(/Z$/)){return a(c)}else{if(c.match(/^[0-9]+$/)){return parseInt(c)}}}}}}}throw"unsupported format: "+c};KJUR.jws.IntDate.getZulu=function(a){return zulutosec(a)};KJUR.jws.IntDate.getNow=function(){var a=~~(new Date()/1000);return a};KJUR.jws.IntDate.intDate2UTCString=function(a){var b=new Date(a*1000);return b.toUTCString()};KJUR.jws.IntDate.intDate2Zulu=function(e){var i=new Date(e*1000),h=("0000"+i.getUTCFullYear()).slice(-4),g=("00"+(i.getUTCMonth()+1)).slice(-2),b=("00"+i.getUTCDate()).slice(-2),a=("00"+i.getUTCHours()).slice(-2),c=("00"+i.getUTCMinutes()).slice(-2),f=("00"+i.getUTCSeconds()).slice(-2);return h+g+b+a+c+f+"Z"}; if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.jws=="undefined"||!KJUR.jws){KJUR.jws={}}KJUR.jws.JWSJS=function(){var c=KJUR,b=c.jws,a=b.JWS,d=a.readSafeJSONString;this.aHeader=[];this.sPayload="";this.aSignature=[];this.init=function(){this.aHeader=[];this.sPayload=undefined;this.aSignature=[]};this.initWithJWS=function(f){this.init();var e=f.split(".");if(e.length!=3){throw"malformed input JWS"}this.aHeader.push(e[0]);this.sPayload=e[1];this.aSignature.push(e[2])};this.addSignature=function(e,h,m,k){if(this.sPayload===undefined||this.sPayload===null){throw"there's no JSON-JS signature to add."}var l=this.aHeader.length;if(this.aHeader.length!=this.aSignature.length){throw"aHeader.length != aSignature.length"}try{var f=KJUR.jws.JWS.sign(e,h,this.sPayload,m,k);var j=f.split(".");var n=j[0];var g=j[2];this.aHeader.push(j[0]);this.aSignature.push(j[2])}catch(i){if(this.aHeader.length>l){this.aHeader.pop()}if(this.aSignature.length>l){this.aSignature.pop()}throw"addSignature failed: "+i}};this.verifyAll=function(h){if(this.aHeader.length!==h.length||this.aSignature.length!==h.length){return false}for(var g=0;g<h.length;g++){var f=h[g];if(f.length!==2){return false}var e=this.verifyNth(g,f[0],f[1]);if(e===false){return false}}return true};this.verifyNth=function(f,j,g){if(this.aHeader.length<=f||this.aSignature.length<=f){return false}var h=this.aHeader[f];var k=this.aSignature[f];var l=h+"."+this.sPayload+"."+k;var e=false;try{e=a.verify(l,j,g)}catch(i){return false}return e};this.readJWSJS=function(g){if(typeof g==="string"){var f=d(g);if(f==null){throw"argument is not safe JSON object string"}this.aHeader=f.headers;this.sPayload=f.payload;this.aSignature=f.signatures}else{try{if(g.headers.length>0){this.aHeader=g.headers}else{throw"malformed header"}if(typeof g.payload==="string"){this.sPayload=g.payload}else{throw"malformed signatures"}if(g.signatures.length>0){this.aSignature=g.signatures}else{throw"malformed signatures"}}catch(e){throw"malformed JWS-JS JSON object: "+e}}};this.getJSON=function(){return{headers:this.aHeader,payload:this.sPayload,signatures:this.aSignature}};this.isEmpty=function(){if(this.aHeader.length==0){return 1}return 0}};
import Bar from './Bar.js'; import Container from './Container.js'; export { Bar, Container };
/*=======================================*/ /* 注册测试功能的js */ /* @author fushenghua */ /* 2014年5月30日16:27:41 */ /*=======================================*/ $(document).ready(function(){ $("#sysAdminLogout").on('click',function(){ login(); }); }); function login(){ window.location.href="./system/login/logout"; } //左侧菜单切换 jQuery(document).on('click', '#lside .menubar li', function(elem) { var menu = jQuery(this); if (menu.is('.cascade')) { menu.toggleClass('open'); }else { menu.closest('.menubar').find('li').removeClass('active'); menu.closest('.menubar').find('.cascade').removeClass('open'); menu.closest('.cascade').addClass('open'); menu.addClass('active'); } var href = elem.attr("href"); // HACK IE outline menu.find('a').blur(); return false; });
import React from "react"; import Layout from "../../../../../components/layout"; import SEO from "../../../../../components/seo"; import {Bounce} from "react-reveal"; import ResourcesDisclaimer from "../../../../../common/resourcesDisclaimer"; import {MobileView, BrowserView} from "react-device-detect"; // Common import Breadcrumb from "../../../../../common/breadcrumb"; import BreadcrumbItem from "../../../../../common/breadcrumbItem"; import PDFFile from "../../../../../common/PDFFile"; import Carousel from "react-multi-carousel"; const Page = () => { // Responsive const responsive = { superLargeDesktop: { // the naming can be any, depends on you. breakpoint: {max: 4000, min: 3000}, items: 1 }, desktop: { breakpoint: {max: 3000, min: 1024}, items: 1 }, tablet: { breakpoint: {max: 1024, min: 464}, items: 1 }, mobile: { breakpoint: {max: 464, min: 0}, items: 1 } }; return ( <> <SEO keywords={[ `csec`, `English A`, `mc`, `multiple choice`, `mcq`, `cxc answers`, `cxc paper 1 answers`, `mcq answers`, `past papers`, `csec past paper answers`, `cxc past papers`, `paperbin`, `past paperbin`, `cxcguide`, `Raheem McDonald`, `cxc English A past paper solutions`, `2019`, `june`, `july`, `cxc`, `caribbean examination council` ]} title="CSEC English A 2013 Paper 1 Answers" description="Download free CSEC English A 2013 multiple choice answers for both January and June exas, and study online with our online study guide." /> <Layout> <section className="flex-1 full max-w-4xl px-4 mx-auto md:py-5"> <Breadcrumb> <BreadcrumbItem title="..." href="/resources" /> <BreadcrumbItem title="..." href="/resources/mcq" notLast /> <BreadcrumbItem title="..." href="/resources/mcq/csec" notLast /> <BreadcrumbItem href="/resources/mcq/csec/english-a" title="English A" notLast /> <BreadcrumbItem title="2013" href="/resources/mcq/csec" /> </Breadcrumb> </section> <MobileView> <Carousel autoPlay ssr={true} responsive={responsive} infinite={true} arrows={false} partialVisible={true} swipeable={true} dots={false} showDots={false} keyBoardControl={true} > <div className="bg-purple-700 p-6 text-white"> <h6 className="text-2xl"> All the past papers answers you need in one place! </h6> </div> <div className="bg-pink-500 p-6 text-white"> <Bounce> <h6 className="text-2xl"> Need answers for more science subjects? Get them{" "} <a href="/resources/mcq/csec/sciences" className="underline text-white" > here! </a> </h6> </Bounce> </div> </Carousel> </MobileView> <section className="flex-1 full max-w-6xl px-4 mx-auto py-3"> <br /> <h1 className="text-xl text-gray-700">English A 2013 MC Answers</h1> <br /> <p className="mt-0 mb-4 text-base text-gray-600"> These are the answers for the English A 2013 exams. </p> <div className="grid grid-cols-1 sm:grid-cols-1 md:grid-cols-1 lg:grid-cols-2 xl:grid-cols-2"> <div> <> <PDFFile title="Download the January answers" href="" /> <br /> <br /> <PDFFile title="Download the June answers" href="" /> <MobileView> <br /> <div id="disqus_thread"></div> </MobileView> <ResourcesDisclaimer /> </> </div> <div> <BrowserView> <div id="disqus_thread"></div> </BrowserView> </div> </div> </section> </Layout> </> ); }; export default Page;
import * as projGlobalConfig from 'ROOT_SOURCE/projGlobalConfig' export const CURRENT_PAGE = projGlobalConfig.CURRENT_PAGE export const PAGE_SIZE = projGlobalConfig.PAGE_SIZE export const TOTAL = projGlobalConfig.TOTAL export const RESPONSE_DESTRUST_KEY = projGlobalConfig.RESPONSE_DESTRUST_KEY export const RESPONSE_LIST_DESTRUST_KEY = projGlobalConfig.RESPONSE_LIST_DESTRUST_KEY
module["exports"] = [ "worldlink.com.np", "gmail.com", "yahoo.com", "hotmail.com" ];
(function(angular, moment) { angular.module('book-inventory-app.filters') .filter('formatLongDate', function() { return function(input) { var output; if (!input) return ''; return moment(new Date(input)).format('MMMM DD, YYYY'); }; }); })(angular, moment);
[{"Owner":"²Digitalgames","Date":"2015-12-14T13:01:52Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_Hello_co_ _lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_i need to apply _lt_span style_eq__qt_color_dd_rgb(40_co_40_co_40)_sm_font-family_dd_helvetica_co_ arial_co_ sans-serif_sm__qt__gt_renderingGroupId_eq_ 1 _sm_ to all meshes loaded in one babylon scene. _lt_/span_gt__lt_/p_gt__lt_pre class_eq__qt_ipsCode prettyprint_qt__gt_BABYLON.SceneLoader.ImportMesh(_qt__qt__co_ _qt_scenes/_qt__co_ _qt_InterfaceObjects.babylon_qt__co_ scene_co_ function (newMeshes) { var InterfaceMeshes _eq_ newMeshes InterfaceMeshes.renderingGroupId _eq_ 1_sm_})_sm__lt_/pre_gt__lt_p_gt_I want to avoid calling newMeshes[0] _co_newMeshes[1] ...and so on and apply to the whole array of meshes. Is that possible ?_lt_/p_gt__lt_p_gt_ _lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"RaananW","Date":"2015-12-14T13:05:07Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_well_co_ iterate _lt_img src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_smile.png_qt_ alt_eq__qt__dd_)_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/smile@2x.png 2x_qt_ width_eq__qt_20_qt_ height_eq__qt_20_qt__gt__lt_/p_gt__lt_pre class_eq__qt_ipsCode prettyprint_qt__gt_newMeshes.forEach(function(mesh) { mesh.renderingGroupId _eq_ 1_sm_})_sm__lt_/pre_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"²Digitalgames","Date":"2015-12-14T13:35:19Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt__lt_span_gt_I would not have found this by myself and its working ! Great _co_ thank you._lt_/span_gt__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt__lt_span_gt_But i would be interested how arrays are used or can be used in Babylon.js. I am using arrays alot in another scripting language. _lt_/span_gt__lt_/p_gt__lt_p_gt_What i found was smart array _co_ but it can´t see a connection to regular uses of arrays. _lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"RaananW","Date":"2015-12-14T13:43:53Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_Most of the arrays used in BabylonJS are the regular JavaScript arrays._lt_/p_gt__lt_p_gt_I find Mozilla_t_s pages very helpful - _lt_a href_eq__qt_https_dd_//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array_qt_ rel_eq__qt_external nofollow_qt__gt_https_dd_//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array_lt_/a_gt__lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_The SmartArray (implemented in Babylon.js) is seldom used. You can find the API here - _lt_a href_eq__qt_http_dd_//doc.babylonjs.com/classes/2.2/SmartArray_qt_ rel_eq__qt_external nofollow_qt__gt_http_dd_//doc.babylonjs.com/classes/2.2/SmartArray_lt_/a_gt__lt_/p_gt__lt_p_gt_It is a wrapper around the regular JS Array to add a bit more functionality. _lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Deltakosh","Date":"2015-12-14T16:35:37Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_The SmartArray is here for only one reason_dd_ the garbage collector._lt_/p_gt__lt_p_gt_ _lt_/p_gt__lt_p_gt_SmartArray has a way to clear its content without stressing the GC which is really important internally_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"}]
// ======================================================================================== // onload page // ======================================================================================== /** * [downloadJSAtOnload description] * @return {[type]} [description] */ function downloadJSAtOnload() { setTimeout(function() { $("#loadpage-preloader").fadeOut(); }, 500); } if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false); else if (window.attachEvent) window.attachEvent("onload", downloadJSAtOnload); else window.onload = downloadJSAtOnload; // ======================================================================================== // sidebar active // ======================================================================================== /** * [description] * @param {[type]} ) { var pathname [description] * @return {[type]} [description] */ $(document).ready(function() { var pathname = location.protocol + '//' + location.host + location.pathname; // $('#nav-accordion').find('a[href="'+pathname+'"]').closest('.sub-menu').children("a").addClass('active'); $('#nav-accordion').find('a[href="' + pathname + '"]').parents('.sub').css({ 'display': 'block' }); $('#nav-accordion').find('a[href="' + pathname + '"]').addClass('active').closest(".dcjq-parent-li").children("a").addClass('active'); var logingroup=$('#usergroupe').val(); //alert(logingroup); //Non aktifkan script ini di ganti dengan helper isDealerAkses(); /*if(logingroup=="Root"){ //$('#kd_dealer').removeClass("disabled-action"); $('#kd_dealer').removeAttr("disabled"); }else{ //$('#kd_dealer').addClass("disabled-action"); $('#kd_dealer').prop("disabled",true); }*/ }); // ======================================================================================== // modal // ======================================================================================== /** * [addForm description] * @param {[type]} url [description] */ function spinner() { return '<div class="modal-body">' + '<div class="modal-loading">' + '<i class="fa fa-spinner fa-spin"></i>' + '<h3>Mohon tunggu...</h3>' + '</div>' + '</div>'; } /** * [error_page description] * @param {[type]} status [description] * @return {[type]} [description] */ function error_page(status) { return '<div class="modal-header"> ' + '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> ' + '<h4 class="modal-title" id="myModalLabel" style="cursor: move;">Error message</h4> ' + '</div> ' + '<div class="modal-body" style="height:50px"> ' + ' <h5 class="modal-title" id="myModalLabel"><i class="fa fa-warning fa-fw"></i> ' + status + '</h5></div> ' + ' <div class="modal-footer"> ' + '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button> ' + '</div>'; } /** * [addForm description] * @param {[type]} url [description] */ function addForm(url) { //document.preventDefault(); var modal_id = $("#modal-button").attr('data-target'); var date = new Date(); $(modal_id).find(".modal-content").html(spinner()); $.getJSON(url, function(data, status) { //alert(status); //console.log(modal_id); if (status == 'success') { if (data.indexOf("A PHP Error") > -1) { //jika terjadi error output $(modal_id).find(".modal-content").html(error_page("Ada kegagalan proses. Silahkan hubungi IT")); } else { //data berhasil di load $(modal_id).find(".modal-content").html(data); } // console.log(data); // load jquery date and time date.setDate(date.getDate()); $('.date').datepicker({ format: 'dd/mm/yyyy', startDate: date, autoclose: true }); $('.datetime').datetimepicker({ format: 'DD/MM/YYYY', minDate: date }); // load jquery format number $(".input-number").ForceNumericOnly(); // load jquery form vaidation $(".submit-btn").on('click', function(event) { var formId = '#' + $(this).closest('form').attr('id'); var btnId = '#' + this.id; $(formId).valid(); $(formId).validate({ focusInvalid: false, invalidHandler: function(form, validator) { if (!validator.numberOfInvalids()) return; $('html, body').animate({ scrollTop: $(validator.errorList[0].element).offset().top }, 1000); } }); if (jQuery(formId).valid()) { // Do something event.preventDefault(); addValid(formId, btnId); } }); } else if (status == "timeout") { $(modal_id).find(".modal-content").html(error_page("Ada kegagalan koneksi server. Silahkan hubungi IT")); } else if (status == "error" || status == "parsererror") { $(modal_id).find(".modal-content").html(error_page("Ada kegagalan proses. Silahkan hubungi IT")); } else { $(modal_id).find(".modal-content").html(error_page("Ada kegagalan proses. Silahkan hubungi IT")); } }) .fail(function(jqXHR, textStatus, errorThrown) { $(modal_id).find(".modal-content").html(error_page("Ada kegagalan proses. Silahkan hubungi IT\n\r" + textStatus)); }); } /** * [description] * @param {[type]} ) { $(".modal-button").click(function(){ var id [description] * @return {[type]} [description] */ $(document).ready(function() { $(".modal-button").click(function() { var id = this.id; var url = $("#" + id).attr('url'); var modal_id = $("#" + id).attr('data-target'); var date = new Date(); $(modal_id).find(".modal-content").html(spinner()); $(modal_id).draggable({ handle: ".modal-header" }); $.getJSON(url, function(data, status) { if (status == 'success') { // var modal_id = $("#modal-button").attr('data-target'); if (data.indexOf("A PHP Error") > -1) { //jika terjadi error output $(modal_id).find(".modal-content").html(error_page("Ada kegagalan proses. Silahkan hubungi IT")); } else { //data berhasil di load $(modal_id).find(".modal-content").html(data); } date.setDate(date.getDate()); $('.date').datepicker({ format: 'dd/mm/yyyy', startDate: date, autoclose: true }); $('.datetime').datetimepicker({ format: 'DD/MM/YYYY', minDate: date }); } else if (status == "timeout") { $(modal_id).find(".modal-content").html(error_page("Ada kegagalan koneksi server. Silahkan hubungi IT")); } else if (status == "error" || status == "parsererror") { $(modal_id).find(".modal-content").html(error_page("Ada kegagalan proses. Silahkan hubungi IT")); } else { $(modal_id).find(".modal-content").html(error_page("Ada kegagalan proses. Silahkan hubungi IT")); } }) .fail(function(jqXHR, textStatus, errorThrown) { var modal_id = $("#modal-button").attr('data-target'); $(modal_id).find(".modal-content").html(error_page("Ada kegagalan proses. Silahkan hubungi IT\n\r" + textStatus)); }); }); }); // ======================================================================================== // modal dragable and resize // ======================================================================================== var modal_id = $("#modal-button").attr('data-target'); $(modal_id).draggable({ handle: ".modal-header" }); $(".xxd").draggable({ handle: ".modal-header" }); // ======================================================================================== // alert // ======================================================================================== // var myMessages = ['info', 'warning', 'error', 'success']; // define the messages types var myMessages = ['warning', 'error', 'success']; // define the messages types /** * [hideAllMessages description] * @return {[type]} [description] */ function hideAllMessages() { var messagesHeights = new Array(); // this array will store height for each for (i = 0; i < myMessages.length; i++) { messagesHeights[i] = $('.' + myMessages[i]).outerHeight(); $('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport } } /** * Posting data */ $(document).ready(function() { $(".update-btn").click(function() { var btnId = this.id; var defaultBtn = $(this).html(); // alert ($(this).parents('form')); var formData = $("#updateForm").serialize(); var act = $("#updateForm").attr('action'); $("#" + btnId).addClass("disabled"); $("#" + btnId).html("<i class='fa fa-spinner fa-spin'></i>"); $(".alert-message").fadeIn(); $.ajax({ url: act + '/' + btnId, type: 'POST', data: formData, dataType: "json", success: function(result) { if (result.status == true) { $('.success').animate({ top: "0" }, 500); $('.success').html(result.message); if (result.location != null) { setTimeout(function() { location.replace(result.location) }, 1000); } else { setTimeout(function() { location.reload(); }, 1000); } } else { $('.error').animate({ top: "0" }, 500); $('.error').html(result.message); setTimeout(function() { hideAllMessages(); $("#" + btnId).removeClass("disabled"); $("#" + btnId).html(defaultBtn); }, 2000); } } }); return false; }); $(".delete-btn").click(function() { var btnId = this.id; var defaultBtn = $(this).html(); var url = $(this).attr('url'); var result = confirm("Apakah anda yakin ingin menghapus data ini ?"); if (result) { $(this).html("<i data-toggle='tooltip' data-placement='left' title='hapus' class='fa fa-spinner fa-spin text-danger text'></i>"); $(".alert-message").fadeIn(); $.getJSON(url, function(data, status) { if (data.status == true) { $('.success').animate({ top: "0" }, 500); $('.success').html(data.message); if (data.location != null) { setTimeout(function() { location.replace(data.location) }, 1000); } } else { $('.error').animate({ top: "0" }, 500); $('.error').html(data.message); setTimeout(function() { hideAllMessages(); $("#" + btnId).html(defaultBtn); }, 2000); } }); return false; } }); $(".download-btn").click(function() { var btnId = this.id; var defaultBtn = $(this).html(); var url = $(this).attr('url'); $(this).html("<i class='fa fa-spinner fa-spin'></i> Loading"); $(".alert-message").fadeIn(); $.getJSON(url, function(data, status) { if (data.status == true) { $('.success').animate({ top: "0" }, 500); $('.success').html(data.message); // alert(http+"/stnk/download_udh?namafile="); location.replace(data.file); setTimeout(function(){ location.reload(); }, 2000); } else { $('.error').animate({ top: "0" }, 500); $('.error').html(data.message); setTimeout(function() { hideAllMessages(); $("#" + btnId).html(defaultBtn); }, 2000); } }); return false; }); }); function addData() { var defaultBtn = $("#submit-btn").html(); $("#submit-btn").addClass("disabled"); $("#submit-btn").html("<i class='fa fa-spinner fa-spin'></i> Loading"); $(".alert-message").fadeIn(); $('#addForm :input').removeAttr("disabled"); var formData = $("#addForm").serialize(); var act = $("#addForm").attr('action'); $.ajax({ url: act, type: 'POST', data: formData, dataType: "json", success: function(result) { if (result.status == true) { $('.success').html(result.message); $('.success').animate({ top: "0" }, 500); if (result.location != null) { setTimeout(function() { location.replace(result.location) }, 1000); } else { setTimeout(function() { location.reload(); }, 1000); } } else { $('.error').animate({top: "0"}, 500); $('.error').html(result.message); setTimeout(function() { hideAllMessages(); $("#submit-btn").removeClass("disabled"); $("#submit-btn").html(defaultBtn); return; }, 2000); } } }); return false; } function addValid(formId, btnId) { // alert(formId); var defaultBtn = $(btnId).html(); $(btnId).addClass("disabled"); $(btnId).html("<i class='fa fa-spinner fa-spin'></i> Loading"); $(".alert-message").fadeIn(); $('#loadpage').removeClass("hidden"); $(formId +" select").removeAttr("disabled"); $(formId +" select").removeClass("disabled-action"); var formData = $(formId).serialize(); var act = $(formId).attr('action'); $.ajax({ url: act, type: 'POST', data: formData, dataType: "json", success: function(result) { if (result.status == true) { $('.success').html(result.message); $('.success').animate({ top: "0" }, 500); if (result.location != null) { setTimeout(function() { location.replace(result.location) }, 1000); } else { setTimeout(function() { location.reload(); }, 1000); } } else { $('.error').animate({ top: "0" }, 500); $('.error').html(result.message); setTimeout(function() { hideAllMessages(); $(btnId).removeClass("disabled"); $(btnId).html(defaultBtn); $('#loadpage').addClass("hidden"); }, 2000); } } }); return false; } /** * Post data untuk update * @return {[type]} [description] * authors : Iswan P */ function updateData(url) { if (confirm('Yakin data ini akan di hapus')) { var defaultBtn = $("#submit-btn").html(); $("#submit-btn").addClass("disabled"); $("#submit-btn").html("<i class='fa fa-spinner fa-spin'></i> Loading"); $(".alert-message").fadeIn(); var formData = $("#addForm").serialize(); var act = url; //$("#addForm").attr('action'); $.ajax({ url: act, type: 'POST', //data: formData, dataType: "json", success: function(result) { if (result.status == true) { $('.success').html(result.message); $('.success').animate({ top: "0" }, 500); setTimeout(function() { //location.reload(); window.location = window.location }, 1000); } else { $('.error').animate({ top: "0" }, 500); $('.error').html(result.message); setTimeout(function() { hideAllMessages(); $("#submit-btn").removeClass("disabled"); $("#submit-btn").html(defaultBtn); }, 2000); } } }); } return false; } /** * Post data dengan bentuk JSON * @param {[string]} act [url posting] * authors : Iswan P */ function AddDataJSON(act) { var defaultBtn = $("#submit-btn").html(); $('#keluar').addClass("disabled"); $("#submit-btn").addClass("disabled"); $("#submit-btn").html("<i class='fa fa-spinner fa-spin'></i> Sedang Prosess..."); $(".alert-message").fadeIn(); jsondata = ($('#datajson').html().replace("\\", "")); jsondata = jsondata.replace(/\\/g, ''); var formData = { data: JSON.stringify(jsondata) }; //var act = $("#addForm").attr('action'); $.ajax({ url: act, type: 'POST', crossDomain: true, data: formData, dataType: "json", success: function(result) { //var result=JSON.parse(result); if (result.status == true) { $('.success').animate({ top: "10" }, 1000); $('.success').html(result.message); setTimeout(function() { //location.reload(); window.location = window.location; }, 1000); } else { $('.error').animate({ top: "0" }, 700); $('.error').html(result.message); setTimeout(function() { hideAllMessages(); $("#submit-btn").removeClass("disabled"); $("#keluar").removeClass("disabled"); $("#submit-btn").html(defaultBtn); }, 1000); } } }); return false; } $(document).ready(function() { // Initially, hide them all hideAllMessages(); // Show message /*for(var i=0;i<myMessages.length;i++) { showMessage(myMessages[i]); }*/ // When message is clicked, hide it $('.message').click(function() { $(this).animate({ top: -$(this).outerHeight() }, 500); }); // ======================================================================================== // footer height // ======================================================================================== /* var winHeight = $( window ).height(); var docHeight = $( document ).height(); if(docHeight <= winHeight) { // alert(docHeight+' lebih kecil dari layar '+winHeight); $("#footer-content").addClass("footer-responsive"); } else { $("#footer-content").removeClass("footer-responsive"); // alert(docHeight+' lebih besar dari layar '+winHeight); } */ // ======================================================================================== // typeahead // ======================================================================================== var ajaxUrl = $("#ajax-url").attr("url"); var length = $("#ajax-url").attr("length"); $("#keyword").typeahead({ source:function(query,process){ $('#fd, .fd').html("<i class='fa fa-spinner fa-spin'></i>"); return $.get(ajaxUrl,function(data){ data=$.parseJSON(data); $('#fd, .fd').html(''); return process(data.keyword); }) }, minLength:length, limit:20 }).focus(); $(".form-control").click(function() { var id = this.id; var inputUrl = $(this).attr("typeaheadurl"); var length = $(this).attr("length"); // alert(ajaxUrl); if (inputUrl != null) { $("#"+id).typeahead({ source:function(query,process){ $('#fd, .fd').html("<i class='fa fa-spinner fa-spin'></i>"); return $.get(inputUrl,function(data){ data=$.parseJSON(data); $('#fd, .fd').html(''); return process(data.keyword); }) }, minLength:length, limit:20 }).focus(); } }); // ======================================================================================== // checkbox typeahead // ======================================================================================== $('.combobox').combobox({ forceSelection: true, typeAhead: true }); // ======================================================================================== // filter input // ======================================================================================== /*$('#keyword').on('keyup keypress blur change', function(e) { $("tbody").html($("#keyword").val()); });*/ $("#filterForm .form-control, #filterForm span").click(function() { var id = this.id; // alert(id); $('#filterForm .form-control').on('change', function(e) { $("#filterForm").submit(); }); }); $("#filterForm .combobox").change(function() { var id = this.id; // alert(id); $("#filterForm").submit(); // $("#filterForm").submit(); }); // ======================================================================================== // date picker // ======================================================================================== var date = new Date(); date.setDate(date.getDate()); $('.date').datepicker({ format: 'dd/mm/yyyy', endDate: date, autoclose: true }); $('.datetime').datetimepicker({ format: 'DD/MM/YYYY', minDate: date/*, autoclose: true*/ }); /*$('.datetime').datetimepicker({ format: 'dd/mm/yyyy', endDate: date, autoclose: true });*/ // ======================================================================================== // table // ======================================================================================== // $("#tr-active").addClass('tr-active'); $("#tr-active").css({ 'background-color': 'rgba(255, 193, 7, 0.33)' }); setTimeout(function() { $("#tr-active").css({ 'background-color': '', 'transition': 'background 4s linear', '-webkit-transition': 'background 4s linear', '-moz-transition': 'background 4s linear' }); }, 1000); $(".input-number").ForceNumericOnly(); // ======================================================================================== // load jquery form vaidation // ======================================================================================== $(".submit-main-btn").click(function(event) { var formId = '#' + $(this).closest('form').attr('id'); var btnId = '#' + this.id; // alert(btnId); $(formId).valid(); $(formId).validate({ focusInvalid: false, invalidHandler: function(form, validator) { if (!validator.numberOfInvalids()) return; $('html, body').animate({ scrollTop: $(validator.errorList[0].element).offset().top }, 1000); } }); if (jQuery(formId).valid()) { // Do something event.preventDefault(); addValid(formId, btnId); } }); // ======================================================================================== // disable action button // ======================================================================================== if ($('a').hasClass("remove-button")) { $(".remove-button").remove(); } // ======================================================================================== // table responsive // ======================================================================================== var $table = $('table.table'); if(!$table.hasClass('tablex')){ $table.floatThead({ scrollContainer: function($table) { return $table.closest('.table-responsive'); } }); } // ======================================================================================== // panel heading cursor // ======================================================================================== $(".tools").closest('.panel-heading').css({ "cursor": "pointer" }); // ======================================================================================== // sticky header // ======================================================================================== if ($("#tab-header").hasClass('sticky')) { $(function() { var stickyHeaderTop = $('#tab-header').offset().top; var stickyHeaderButtom = $(document).height() - 100; /* alert(stickyHeaderTop); alert(stickyHeaderButtom);*/ $(window).scroll(function() { if ($(window).scrollTop() >= stickyHeaderTop) { // if ($(window).scrollTop() + $(window).height() >= stickyHeaderButtom) { /*alert(stickyHeaderTop); alert($(window).scrollTop());*/ $('.tab-content').css('margin-top', $('#tab-header').outerHeight(true)); $('#tab-header').addClass('tab-header'); /*$('#tab-header').css({ position: 'fixed', bottom: '100px', right: '27px' });*/ } else { $('#tab-header').removeClass('tab-header'); $('#tab-header').css({ position: 'static', bottom: '0px' }); $('.tab-content').css('margin-top', '0px'); } }); }); } }); //document ready function ending jQuery.fn.ForceNumericOnly = function() { return this.each(function() { $(this).keydown(function(e) { var key = e.charCode || e.keyCode || 0; // allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY // home, end, period, and numpad decimal return ( key == 8 || key == 9 || key == 13 || key == 46 || key == 110 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105)); }); }); }; /** * [convertDate description] * @param {[type]} inputFormat [description] * @return {[type]} dd/mm/yyyy [description] */ function convertDate(inputFormat) { if(!inputFormat){return;} function pad(s) { return (s < 10) ? '0' + s : s; } var d = new Date(inputFormat); return [pad(d.getDate()), pad(d.getMonth() + 1), d.getFullYear()].join('/'); } function DateToSql(inputFormat) { function pad(s) { return (s < 10) ? '0' + s : s; } var d = new Date(inputFormat); return [ d.getFullYear(),pad(d.getDate()), pad(d.getMonth() + 1)].join(''); } // left padding s with c to a total of n chars function pad_left(s, c, n) { if (! s || ! c || s.length >= n) { return s; } var max = (n - s.length)/c.length; for (var i = 0; i < max; i++) { s = c + s; } return s; } // right padding s with c to a total of n chars function pad_right(s, c, n) { if (! s || ! c || s.length >= n) { return s; } var max = (n - s.length)/c.length; for (var i = 0; i < max; i++) { s += c; } return s; } function result_message(result){ if (result.status == true){ $('.success').animate({ top: "0" }, 500); $('.success').html(result.message); setTimeout(function(){ location.reload(); }, 2000); }else{ $('.error').animate({ top: "0" }, 500); $('.error').html(result.message); setTimeout(function () { hideAllMessages(); //$("#reject-btn").removeClass("disabled"); //$("#reject-btn").html(defaultBtn); }, 4000); } } $.extend({ ucwords : function(str) { strVal = ''; str = str.split(' '); for (var chr = 0; chr < str.length; chr++) { strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' ' } return strVal } }); function stripslashes(str) { return(str)? str.replace(/\\'/g,'\'').replace(/\"/g,'"').replace(/\\\\/g,'\\').replace(/\\0/g,'\0'):false; } // ======================================================================================== // breadcrumb // ======================================================================================== $( "<div class='box-footer clearfix'></div>" ).insertAfter( ".breadcrumb" );
import React, { Component } from "react"; import { Link, withRouter } from "react-router-dom"; import withStyles from "@material-ui/styles/withStyles"; import Typography from "@material-ui/core/Typography"; import Button from "@material-ui/core/Button"; import BaseDialog from "./BaseDialog"; import SwipeableViews from "react-swipeable-views"; import MobileStepper from "@material-ui/core/MobileStepper"; import { autoPlay } from "react-swipeable-views-utils"; const logo = require("../../images/logo.svg"); const AutoPlaySwipeableViews = autoPlay(SwipeableViews); const tutorialSteps = [ { label: "A first label", description: "This is the first item on the label", imgPath: "https://images.unsplash.com/photo-1537944434965-cf4679d1a598?auto=format&fit=crop&w=400&h=250&q=60", }, { label: "A second label", description: "This is the second item on the label", imgPath: "https://images.unsplash.com/photo-1538032746644-0212e812a9e7?auto=format&fit=crop&w=400&h=250&q=60", }, { label: "A third label", description: "This is the third item on the label", imgPath: "https://images.unsplash.com/photo-1537996194471-e657df975ab4?auto=format&fit=crop&w=400&h=250&q=80", }, { label: "A fifth label", description: "This is the fifth item on the label", imgPath: "https://images.unsplash.com/photo-1518732714860-b62714ce0c59?auto=format&fit=crop&w=400&h=250&q=60", }, { label: "Other label", description: "This is other label", imgPath: "https://images.unsplash.com/photo-1512341689857-198e7e2f3ca8?auto=format&fit=crop&w=400&h=250&q=60", }, ]; const styles = (theme) => ({ container: { maxWidth: 600, flexGrow: 1, textAlign: "center", display: "flex", flexDirection: "column", justifyContent: "center", }, stepsContainer: { marginLeft: 72, textAlign: "left", marginTop: 20, height: 65, }, bottomMargin: { marginBottom: theme.spacing(2), }, }); class SwipeDialog extends Component { state = { activeStep: 0, }; handleNext = () => { this.setState((prevState) => ({ activeStep: prevState.activeStep + 1, })); }; handleBack = () => { this.setState((prevState) => ({ activeStep: prevState.activeStep - 1, })); }; handleStepChange = (activeStep) => { this.setState({ activeStep }); }; render() { const { classes } = this.props; const maxSteps = tutorialSteps.length; const { activeStep } = this.state; return ( <BaseDialog {...this.props}> <div className={classes.container}> <div className={classes.gutterBottom}> <img width={100} src={logo} alt="" /> </div> <div> <AutoPlaySwipeableViews axis="x" index={activeStep} onChangeIndex={this.handleStepChange} enableMouseEvents > {tutorialSteps.map((step, index) => ( <div key={step.label}> {Math.abs(activeStep - index) <= 2 ? ( <img className={classes.img} src={step.imgPath} alt={step.label} /> ) : null} </div> ))} </AutoPlaySwipeableViews> <MobileStepper steps={maxSteps} position="static" activeStep={activeStep} className={classes.mobileStepper} nextButton={ <Button size="small" onClick={this.handleNext} disabled={activeStep === maxSteps - 1} > Next </Button> } backButton={ <Button size="small" onClick={this.handleBack} disabled={activeStep === 0} > Back </Button> } /> </div> <div className={classes.stepsContainer}> <Typography style={{ textTransform: "uppercase" }} color="secondary" gutterBottom > {tutorialSteps[activeStep].label} </Typography> <Typography variant="body2" gutterBottom> {tutorialSteps[activeStep].description} </Typography> </div> <div> <Button component={Link} to="/dashboard" variant="contained" onClick={this.handleClose} color="primary" autoFocus > Getting started </Button> </div> </div> </BaseDialog> ); } } export default withRouter(withStyles(styles)(SwipeDialog));
module.exports = {name: 'react-native-auth0', version: '2.13.0'};
export * from '@styled-icons/remix-fill/VolumeDown';
const fs = require('fs-extra'); const path = require('path'); const glob = require('glob'); const sass = require('node-sass'); const postcss = require('postcss'); const postcssCalc = require('postcss-calc'); // 保留原状 const cwd = process.cwd(); const { logger } = require('../utils'); const { collectVarsInfo } = require('./utils/collect-vars-info'); const shouldBeCssVar = require('./utils/should-be-css-var'); const fontScssVar = { 'font-custom-path': '//i.alicdn.com/artascope-font/20160419204543/font/', 'font-custom-name': 'Roboto', 'font-name-thin': 'roboto-thin', 'font-name-light': 'roboto-light', 'font-name-regular': 'roboto-regular', 'font-name-medium': 'roboto-medium', 'font-name-bold': 'roboto-bold', }; module.exports = async function() { // generate temp files for [core/utility, core/style] const corePaths = glob.sync('src/core/@(utility|style)/*.scss'); const indexScssPath = path.join(cwd, 'src/core/index.scss'); await Promise.all( corePaths.map(async cPath => { const varsInfo = await collectVarsInfo(cPath, indexScssPath); let scss2cssContent = ''; Object.entries(varsInfo).forEach(([name, { value, resolvedValue }]) => { if (shouldBeCssVar(name, value)) { scss2cssContent += `$${name}: var(--${name}, ${resolvedValue});\n`; scss2cssContent += `$varMap: map-merge($varMap, (var(--${name}, ${resolvedValue}): ${resolvedValue}));\n`; } else { scss2cssContent += `$${name}: ${resolvedValue};\n`; } }); let cssvarDefaultContent = ''; Object.entries(varsInfo).forEach(([name, { value, resolvedValue }]) => { if (shouldBeCssVar(name, value)) { cssvarDefaultContent += `--${name}: ${resolvedValue};\n`; } }); cssvarDefaultContent = `:root {\n${cssvarDefaultContent}}\n`; Object.keys(fontScssVar).forEach(fontScssVarName => { if (varsInfo[fontScssVarName]) { fontScssVar[fontScssVarName] = varsInfo[fontScssVarName].resolvedValue; if (fontScssVarName === 'font-custom-path') { fontScssVar[fontScssVarName] = fontScssVar[fontScssVarName].replace(/"/gi, ''); } } }); const newPath = cPath.replace('core', 'core-temp'); fs.outputFileSync(newPath, scss2cssContent); fs.outputFileSync(newPath.replace('.scss', '-def-default.css'), cssvarDefaultContent); }) ); // generate [core-temp/index.scss, core-temp/index-noreset.scss, core-temp/reset.scss] const indexPaths = glob.sync('src/core/@(index|index-noreset|reset).scss'); indexPaths.forEach(p => { const indexScssContent = fs.readFileSync(p, 'utf8'); fs.outputFileSync(p.replace('core', 'core-temp'), indexScssContent); }); // copy [core/util/**.scss] to [core-temp/util/**.scss] const utilPaths = glob.sync('src/core/util/**.scss'); utilPaths.forEach(p => { const indexScssContent = fs.readFileSync(p, 'utf8'); fs.outputFileSync(p.replace('core', 'core-temp'), indexScssContent); }); // generate [base] style const coreBasePaths = glob.sync('src/core/base/*.scss'); coreBasePaths.forEach(cPath => { let mainScssContent = fs.readFileSync(cPath, 'utf8'); fs.outputFileSync(cPath.replace('core', 'core-temp'), mainScssContent); if (path.basename(cPath) === '_typography.scss') { Object.keys(fontScssVar).forEach(key => { const reg = new RegExp(`#{\\$${key}}`, 'ig'); mainScssContent = mainScssContent.replace(reg, fontScssVar[key]); }); } const mainScss2 = ` @import "src/core-temp/util/_varMap.scss"; @import "src/core-temp/style/_global.scss"; @import "src/core-temp/style/_size.scss"; @import "src/core-temp/style/_color.scss"; @import "src/core-temp/style/_corner.scss"; @import "src/core-temp/style/_font.scss"; @import "src/core-temp/style/_line.scss"; @import "src/core-temp/style/_shadow.scss"; @import "src/core-temp/style/_motion.scss"; $css-prefix: 'next-'; ${mainScssContent}`; const result = sass.renderSync({ includePaths: [path.join(cwd, 'core-temp')], data: mainScss2, }); const css = result.css.toString(); const output = postcss() .use(postcssCalc()) .process(css).css; fs.outputFileSync(cPath.replace('.scss', '-def-default.css').replace('core', 'core-temp'), output); }); logger.success('> [Core] empty and generate src/core-temp successfully!'); };
import React from "react"; import uuid from "uuid/v1"; const SvgCylinder = props => { const gradientId = uuid(); return ( <svg viewBox="0 0 24 26" width="1em" height="1em" {...props}> <defs> <linearGradient id={gradientId} x1="0%" y1="50%" y2="50%"> <stop offset="0%" stopColor="#4DA6FF" /> <stop offset="100%" stopColor="#4DE1FF" /> </linearGradient> </defs> <g fill="none" fillRule="evenodd"> <path fill={`url(#${gradientId})`} d="M.005 5.809v13.117c0 3.206 4.549 5.805 10.16 5.805 5.612 0 10.16-2.599 10.16-5.805V5.81c0-3.206-4.548-5.805-10.16-5.805C4.554.004.005 2.603.005 5.81" transform="translate(1.818 .364)" /> <path fill="#4DE1FF" d="M22.144 6.173c0 3.205-4.55 5.804-10.16 5.804-5.612 0-10.161-2.599-10.161-5.804 0-3.206 4.549-5.805 10.16-5.805 5.612 0 10.161 2.599 10.161 5.805" /> </g> </svg> ); }; export default SvgCylinder;
import _tagged_template_literal from "@swc/helpers/src/_tagged_template_literal.mjs"; function _templateObject() { var data = _tagged_template_literal([ "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2028 2029 0085 t v f b r n" ]); return _templateObject = function _templateObject() { return data; }, data; } !function() { for(var _len = arguments.length, x = new Array(_len), _key = 0; _key < _len; _key++)x[_key] = arguments[_key]; }(_templateObject());
if (performance.getEntriesByType("navigation")[0].type === "back_forward") { location.reload(true); } const phoneInput = document.querySelector(".phoneInput"); const input1 = document.querySelector("#phone"); const submit = document.querySelector("#submit"); const registerForm = document.querySelector(".registerForm"); const stage = document.querySelector(".stage"); const password = document.querySelector("#password"); const invalid = document.querySelector("#invalid"); const success1 = document.querySelector("#success1"); const success2 = document.querySelector("#success2"); const success3 = document.querySelector("#success3"); const danger1 = document.querySelector("#danger1"); const danger2 = document.querySelector("#danger2"); const danger3 = document.querySelector("#danger3"); const con1 = document.querySelector(".con1"); const con2 = document.querySelector(".con2"); const con3 = document.querySelector(".con3"); const email = document.querySelector('#username') const params = new URLSearchParams(window.location.search) console.log(params) let homeEmail; if(params.has('username')){ homeEmail = params.get('username') email.value = homeEmail } window.intlTelInput(input1, { separateDialCode: true, utilsScript: "../public/build/js/utils.js", }); registerForm.addEventListener("submit", () => { input1.removeEventListener("input", checkPhone); input1.value = myCode.innerText + input1.value; }); let validPass = false; const checkPhone = (e) => { const pattern = /\D/; if (pattern.test(input1.value)) { phoneInput.style.display = "block"; submit.classList.add("disabled"); input1.classList.add("is-invalid"); } else { phoneInput.style.display = "none"; input1.classList.remove("is-invalid"); submit.classList.remove("disabled"); } }; input1.addEventListener("input", checkPhone); check.addEventListener("click", () => { if (check.checked == true) { password.setAttribute("type", "text"); } else { password.setAttribute("type", "password"); } }); submit.setAttribute("class", "btn btn-primary disabled"); let pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*[*.!\\@$%^&(){}[\]]).{8,255}$/; let pattern1 = /.{8,255}/; let pattern2 = /(?=.*\d)(?=.*[A-Z])/; let pattern3 = /(?=.*[*.!\\@$%^&(){}[\]])/; password.addEventListener("keyup", () => { console.log(password.value); let result = pattern.test(password.value); let result1 = pattern1.test(password.value); let result2 = pattern2.test(password.value); let result3 = pattern3.test(password.value); if (!result) { invalid.style.color = "#dc3545"; danger1.style.display = "inline"; danger2.style.display = "inline"; danger3.style.display = "inline"; success1.style.display = "none"; success2.style.display = "none"; success3.style.display = "none"; submit.setAttribute("class", "btn btn-primary disabled"); if (result1) { con1.style.color = "green"; danger1.style.display = "none"; success1.style.display = "inline"; success1.style.color = "green"; } else { con1.style.color = "#dc3545"; danger1.style.color = "#dc3545"; danger1.style.display = "inline"; success1.style.display = "none"; } if (result2) { con3.style.color = "green"; danger3.style.display = "none"; success3.style.display = "inline"; success3.style.color = "green"; } else { con3.style.color = "#dc3545"; danger3.style.color = "#dc3545"; danger3.style.display = "inline"; success3.style.display = "none"; } if (result3) { con2.style.color = "green"; danger2.style.display = "none"; success2.style.display = "inline"; success2.style.color = "green"; } else { con2.style.color = "#dc3545"; danger2.style.color = "#dc3545"; danger2.style.display = "inline"; success2.style.display = "none"; } } else { con1.style.color = "green"; danger1.style.display = "none"; success1.style.display = "inline"; success1.style.color = "green"; con2.style.color = "green"; danger2.style.display = "none"; success2.style.display = "inline"; success2.style.color = "green"; con3.style.color = "green"; danger3.style.display = "none"; success3.style.display = "inline"; success3.style.color = "green"; con3.style.color = "green"; submit.removeAttribute("class"); submit.setAttribute("class", "btn btn-primary"); invalid.style.color = "green"; danger1.style.display = "none"; danger2.style.display = "none"; danger3.style.display = "none"; success1.style.display = "inline"; success2.style.display = "inline"; success3.style.display = "inline"; invalid.style.display = "block"; } }); password.addEventListener("blur", () => { invalid.style.display = "none"; }); var dropdownElementList = [].slice.call( document.querySelectorAll(".dropdown-toggle") ); var dropdownList = dropdownElementList.map(function (dropdownToggleEl) { return new bootstrap.Dropdown(dropdownToggleEl); }); let instances, ulList, instances1; let data = { Afghanistan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AF.svg", "Åland Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AX.svg", Albania: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AL.svg", Algeria: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/DZ.svg", "American Samoa": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AS.svg", Andorra: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AD.svg", Angola: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AO.svg", Anguilla: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AI.svg", Antarctica: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AQ.svg", "Antigua and Barbuda": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AG.svg", Argentina: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AR.svg", Armenia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AM.svg", Aruba: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AW.svg", Australia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AU.svg", Austria: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AT.svg", Azerbaijan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AZ.svg", Bahrain: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BH.svg", Bahamas: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BS.svg", Bangladesh: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BD.svg", Barbados: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BB.svg", Belarus: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BY.svg", Belgium: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BE.svg", Belize: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BZ.svg", Benin: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BJ.svg", Bermuda: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BM.svg", Bhutan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BT.svg", "Bolivia, Plurinational State of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BO.svg", "Bonaire, Sint Eustatius and Saba": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BQ.svg", "Bosnia and Herzegovina": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BA.svg", Botswana: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BW.svg", "Bouvet Island": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BV.svg", Brazil: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BR.svg", "British Indian Ocean Territory": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/IO.svg", "Brunei Darussalam": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BN.svg", Bulgaria: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BG.svg", "Burkina Faso": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BF.svg", Burundi: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BI.svg", Cambodia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KH.svg", Cameroon: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CM.svg", Canada: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CA.svg", "Cape Verde": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CV.svg", "Cayman Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KY.svg", "Central African Republic": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CF.svg", Chad: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TD.svg", Chile: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CL.svg", China: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CN.svg", "Christmas Island": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CX.svg", "Cocos (Keeling) Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CC.svg", Colombia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CO.svg", Comoros: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KM.svg", Congo: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CG.svg", "Congo, the Democratic Republic of the": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CD.svg", "Cook Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CK.svg", "Costa Rica": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CR.svg", "Côte d'Ivoire": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CI.svg", Croatia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/HR.svg", Cuba: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CU.svg", Curaçao: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CW.svg", Cyprus: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CY.svg", "Czech Republic": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CZ.svg", Denmark: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/DK.svg", Djibouti: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/DJ.svg", Dominica: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/DM.svg", "Dominican Republic": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/DO.svg", Ecuador: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/EC.svg", Egypt: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/EG.svg", "El Salvador": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SV.svg", "Equatorial Guinea": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GQ.svg", Eritrea: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ER.svg", Estonia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/EE.svg", Ethiopia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ET.svg", "Falkland Islands (Malvinas)": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/FK.svg", "Faroe Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/FO.svg", Fiji: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/FJ.svg", Finland: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/FI.svg", France: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/FR.svg", "French Guiana": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GF.svg", "French Polynesia": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PF.svg", "French Southern Territories": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TF.svg", Gabon: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GA.svg", Gambia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GM.svg", Georgia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GE.svg", Germany: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/DE.svg", Ghana: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GH.svg", Gibraltar: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GI.svg", Greece: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GR.svg", Greenland: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GL.svg", Grenada: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GD.svg", Guadeloupe: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GP.svg", Guam: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GU.svg", Guatemala: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GT.svg", Guernsey: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GG.svg", Guinea: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GN.svg", "Guinea-Bissau": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GW.svg", Guyana: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GY.svg", Haiti: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/HT.svg", "Heard Island and McDonald Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/HM.svg", "Holy See (Vatican City State)": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/VA.svg", Honduras: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/HN.svg", "Hong Kong": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/HK.svg", Hungary: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/HU.svg", Iceland: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/IS.svg", India: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/IN.svg", Indonesia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ID.svg", "Iran, Islamic Republic of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/IR.svg", Iraq: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/IQ.svg", Ireland: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/IE.svg", "Isle of Man": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/IM.svg", Israel: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/IL.svg", Italy: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/IT.svg", Jamaica: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/JM.svg", Japan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/JP.svg", Jersey: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/JE.svg", Jordan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/JO.svg", Kazakhstan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KZ.svg", Kenya: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KE.svg", Kiribati: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KI.svg", "Korea, Democratic People's Republic of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KP.svg", "Korea, Republic of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KR.svg", Kuwait: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KW.svg", Kyrgyzstan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KG.svg", "Lao People's Democratic Republic": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LA.svg", Latvia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LV.svg", Lebanon: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LB.svg", Lesotho: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LS.svg", Liberia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LR.svg", Libya: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LY.svg", Liechtenstein: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LI.svg", Lithuania: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LT.svg", Luxembourg: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LU.svg", Macao: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MO.svg", "Macedonia, the Former Yugoslav Republic of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MK.svg", Madagascar: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MG.svg", Malawi: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MW.svg", Malaysia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MY.svg", Maldives: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MV.svg", Mali: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ML.svg", Malta: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MT.svg", "Marshall Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MH.svg", Martinique: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MQ.svg", Mauritania: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MR.svg", Mauritius: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MU.svg", Mayotte: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/YT.svg", Mexico: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MX.svg", "Micronesia, Federated States of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/FM.svg", "Moldova, Republic of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MD.svg", Monaco: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MC.svg", Mongolia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MN.svg", Montenegro: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ME.svg", Montserrat: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MS.svg", Morocco: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MA.svg", Mozambique: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MZ.svg", Myanmar: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MM.svg", Namibia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NA.svg", Nauru: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NR.svg", Nepal: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NP.svg", Netherlands: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NL.svg", "New Caledonia": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NC.svg", " New Zealand": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NZ.svg", Nicaragua: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NI.svg", Niger: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NE.svg", Nigeria: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NG.svg", Niue: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NU.svg", "Norfolk Island": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NF.svg", "Northern Mariana Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MP.svg", Norway: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/NO.svg", Oman: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/OM.svg", Pakistan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PK.svg", Palau: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PW.svg", "Palestine, State of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PS.svg", Panama: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PA.svg", "Papua New Guinea": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PG.svg", Paraguay: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PY.svg", Peru: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PE.svg", Philippines: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PH.svg", Pitcairn: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PN.svg", Poland: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PL.svg", Portugal: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PT.svg", "Puerto Rico": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PR.svg", Qatar: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/QA.svg", Réunion: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/RE.svg", Romania: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/RO.svg", "Russian Federation": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/RU.svg", Rwanda: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/RW.svg", "Saint Barthélemy": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/BL.svg", "Saint Helena, Ascension and Tristan da Cunha": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SH.svg", "Saint Kitts and Nevis": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/KN.svg", "Saint Lucia": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LC.svg", "Saint Martin (French part)": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/MF.svg", "Saint Pierre and Miquelon": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/PM.svg", "Saint Vincent and the Grenadines": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/VC.svg", Samoa: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/WS.svg", "San Marino ": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SM.svg", "Sao Tome and Principe": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ST.svg", "Saudi Arabia": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SA.svg", Senegal: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SN.svg", Serbia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/RS.svg", Seychelles: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SC.svg", "Sierra Leone": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SL.svg", Singapore: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SG.svg", "Sint Maarten (Dutch part)": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SX.svg", Slovakia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SK.svg", Slovenia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SI.svg", "Solomon Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SB.svg", Somalia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SO.svg", "South Africa": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ZA.svg", "South Georgia and the South Sandwich Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GS.svg", "South Sudan": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SS.svg", Spain: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ES.svg", "Sri Lanka": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/LK.svg", Sudan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SD.svg", Suriname: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SR.svg", "Svalbard and Jan Mayen": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SJ.svg", Swaziland: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SZ.svg", Sweden: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SE.svg", Switzerland: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/CH.svg", "Syrian Arab Republic": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/SY.svg", "Taiwan, Province of China": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TW.svg", Tajikistan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TJ.svg", "Tanzania, United Republic of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TZ.svg", Thailand: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TH.svg", "Timor-Leste": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TL.svg", Togo: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TG.svg", Tokelau: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TK.svg", Tonga: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TO.svg", "Trinidad and Tobago": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TT.svg", Tunisia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TN.svg", Turkey: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TR.svg", Turkmenistan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TM.svg", "Turks and Caicos Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TC.svg", Tuvalu: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/TV.svg", Uganda: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/UG.svg", Ukraine: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/UA.svg", "United Arab Emirates": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/AE.svg", "United Kingdom": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/GB.svg", "United States": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/US.svg", "United States Minor Outlying Islands": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/UM.svg", Uruguay: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/UY.svg", Uzbekistan: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/UZ.svg", Vanuatu: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/VU.svg", "Venezuela, Bolivarian Republic of": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/VE.svg", "Viet Nam": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/VN.svg", "Virgin Islands, British": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/VG.svg", "Virgin Islands, U.S": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/VI.svg", "Wallis and Futuna": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/WF.svg", "Western Sahara": "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/EH.svg", Yemen: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/YE.svg", Zambia: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ZM.svg", Zimbabwe: "https://cdn.jsdelivr.net/npm/country-flag-emoji-json@2.0.0/dist/images/ZW.svg", }; var countryInp = document.querySelector(".country"); var stateInp = document.querySelector(".state"); var cityInp = document.querySelector(".city"); document.addEventListener("DOMContentLoaded", function () { instances = M.Autocomplete.init(countryInp, { limit: 5, data, }); instances1 = M.Autocomplete.init(stateInp, { limit: 5, data: {}, }); instances2 = M.Autocomplete.init(cityInp, { limit: 5, data: {}, }); }); let data1, object; countryInp.addEventListener("change", async () => { if (data.hasOwnProperty(countryInp.value)) { countryInp.classList.remove("is-invalid"); submit.classList.remove("disabled"); } else { submit.classList.add("disabled"); countryInp.classList.add("is-invalid"); } stateInp.addEventListener("focusin", async () => { if (data.hasOwnProperty(countryInp.value)) { data1 = await axios.post( "https://countriesnow.space/api/v0.1/countries/states", { country: countryInp.value, } ); const dataList = data1.data.data.states; console.log(data1.data.data.states); cityData = dataList.reduce( (obj, item) => ((obj[item.name] = null), obj), {} ); instances1.updateData(cityData); } }); let data2; cityInp.addEventListener("focusin", async () => { if (stateInp.value in cityData) { data2 = await axios.post( "https://countriesnow.space/api/v0.1/countries/state/cities", { country: countryInp.value, state: stateInp.value, } ); console.log(data2.data.data); const dataList = data2.data.data; cityData2 = dataList.reduce((obj, item) => ((obj[item] = null), obj), {}); console.log(cityData2); instances2.updateData(cityData2); } }); stateInp.addEventListener("change", async () => { if (stateInp.value in cityData) { stateInp.classList.remove("is-invalid"); submit.classList.remove("disabled"); } else { stateInp.classList.add("is-invalid"); submit.classList.add("disabled"); } }); cityInp.addEventListener("change", async () => { if (cityInp.value in cityData2) { cityInp.classList.remove("is-invalid"); submit.classList.remove("disabled"); } else { cityInp.classList.add("is-invalid"); submit.classList.add("disabled"); } }); }); password.addEventListener("focus", () => (invalid.style.display = "block"));
import React from "react"; import TextField from "@material-ui/core/TextField"; import Grid from "@material-ui/core/Grid"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import Button from "@material-ui/core/Button"; import LoadingButton from "@components/loading/LoadingButton"; const CreateAddressForm = props => { const { values: { receiver_full_name, receiver_phone_number, state, city, postal_address, postal_code }, errors, handleSubmit, handleChange, handleClose } = props; return ( <React.Fragment> <DialogContent dividers> <Grid container spacing={2}> <Grid item md={6} xs={12}> <TextField label="receiver full name" placeholder="Enter receiver full name" variant="outlined" margin="normal" name="receiver_full_name" autoComplete="receiver_full_name" helperText={errors.receiver_full_name} error={Boolean(errors.receiver_full_name)} value={receiver_full_name} onChange={handleChange} required fullWidth autoFocus /> </Grid> <Grid item md={6} xs={12}> <TextField label="receiver phone number" placeholder="Enter receiver phone number" variant="outlined" margin="normal" name="receiver_phone_number" autoComplete="receiver_phone_number" helperText={errors.receiver_phone_number} error={Boolean(errors.receiver_phone_number)} value={receiver_phone_number} onChange={handleChange} required fullWidth /> </Grid> <Grid item md={6} xs={12}> <TextField label="State" placeholder="Enter state" variant="outlined" margin="normal" name="state" autoComplete="state" helperText={errors.state} error={Boolean(errors.state)} value={state} onChange={handleChange} required fullWidth /> </Grid> <Grid item md={6} xs={12}> <TextField label="City" placeholder="Enter city" variant="outlined" margin="normal" name="city" autoComplete="city" helperText={errors.city} error={Boolean(errors.city)} value={city} onChange={handleChange} required fullWidth /> </Grid> <Grid item md={12} xs={12}> <TextField label="Postal address" placeholder="Enter postal address" variant="outlined" margin="normal" name="postal_address" autoComplete="postal_address" rows="3" helperText={errors.postal_address} error={Boolean(errors.postal_address)} value={postal_address} onChange={handleChange} required fullWidth multiline /> </Grid> <Grid item md={6} xs={12}> <TextField label="Postal code" placeholder="Enter postal code with out dash" variant="outlined" margin="normal" name="postal_code" autoComplete="postal_code" helperText={errors.postal_code} error={Boolean(errors.postal_code)} value={postal_code} onChange={handleChange} required fullWidth /> </Grid> </Grid> </DialogContent> <DialogActions> <Button onClick={handleClose} size="large" variant="outlined"> Cancel </Button> <LoadingButton onClick={handleSubmit} size="large" variant="outlined" color="primary" > Add </LoadingButton> </DialogActions> </React.Fragment> ); }; export default CreateAddressForm;
const fs = require('fs'); // Add 'export as namespace pc' to the end of the file let path = './types/index.d.ts'; let ts = (fs.readFileSync(path, 'utf8')).toString(); ts = ts + '\n\nexport as namespace pc;\n'; fs.writeFileSync(path, ts); // Create a regex that matches any string starting with Class< and ending with > const regex = /Class<(.*?)>/g; const paths = [ './types/framework/components/script/component.d.ts', './types/script/script-attributes.d.ts', './types/script/script-registry.d.ts', './types/script/script.d.ts' ]; paths.forEach(path => { ts = (fs.readFileSync(path, 'utf8')).toString(); ts = ts.replace(regex, 'typeof ScriptType'); fs.writeFileSync(path, ts); }); // Fix up description parameter for VertexFormat constructor because tsc // doesn't recognize it as an array path = './types/graphics/vertex-format.d.ts'; ts = (fs.readFileSync(path, 'utf8')).toString(); ts = ts.replace('}, vertexCount?: number);', '}[], vertexCount?: number);'); fs.writeFileSync(path, ts);
var SIGN_UP_IN_VALUE = 1; function signin(){ trySignin(); loadingImage( true, 200 ); //simulateLoginSuccess(); simulateLoginFail(); } function signup2( event ){ } function signup(){ trySignup(); loadingImage( true, 200 ); //simulateSignupSuccess(); simulateSignupFailure(); //alert(); } function signupinSwitch( val ){ var signin_el = document.getElementById("fields-1"); var signup_el = document.getElementById("fields-2"); var underl_el = document.getElementById("selection1"); var signup_text_el = document.getElementById("signup"); var signin_text_el = document.getElementById("signin"); if( val === SIGN_UP_IN_VALUE ) return; if( val === 1 ){ underl_el.style.left = "16px"; SIGN_UP_IN_VALUE = 1; signin_text_el.className = "selected"; signup_text_el.className = "unselected"; moveX2( underl_el, 101, 16, -20 ); signUpSlideOut(); } if( val === 2 ){ SIGN_UP_IN_VALUE = 2; signup_text_el.className = "selected"; signin_text_el.className = "unselected"; moveX2( underl_el, 16, 101, inc = 20, dur = 2 ); signInSlideOut(); } } function popup(){ dimscreen( true, 100 ); dimAlertShow( 200 ); // dimscreen( false ); } function trySignin(){ var signin_el = document.getElementById("fields-1"); moveX2( signin_el, 16, -300, inc = -20, dur = 2 ); fadeOut( signin_el, 0 ); } function trySignup(){ var signin_el = document.getElementById("fields-2"); moveX2( signin_el, 16, -300, inc = -20, dur = 2 ); fadeOut( signin_el, 0 ); } function simulateLoginSuccess(){ var el1 = document.getElementById("rings"); el1.style.backgroundImage = "url(imgs/rings.svg?" + Math.random() + ")"; el1.style.display = "block"; el1.style.backgroundSize = "100%"; el1.style.opacity = "1"; var el3 = document.getElementById("successtext"); el3.style.display = "block"; el3.style.backgroundSize = "0"; var el4 = document.getElementById("logintextG"); el4.style.display = "block"; el4.style.backgroundSize = "0"; el4.style.opacity = "1"; window.setTimeout(function() { var el = document.getElementById("rings"); shrinkOut( el ); var el = document.getElementById("loginsuccess"); growIn( el, 20 ); growIn( el3, 50, 3 ); growIn( el4, 50, 3 ); //setStyleAtTime( el4, "display", "none", 1800 ); }, 4000 ); } function signupFailure(){ var el1 = document.getElementById("rings"); var el2 = document.getElementById("signupfailure"); var el3 = document.getElementById("failtext"); var el4 = document.getElementById("signuptextR"); el2.style.display = "block"; el2.style.opacity = "1"; el2.style.backgroundSize = "0%"; shrinkOut( el1 ); el2.style.color = "red"; growIn( el2, 28 ); shakeLoginBox( 200 ); growIn( el3, 30, 10 ); growIn( el4, 60, 5 ); fadeOut( el2, 1800 ); fadeOut( el1, 1800 ); fadeOut( el3, 1750 ); fadeOut( el4, 1750 ); var signin_el = document.getElementById("fields-2"); signin_el.style.left = "16px"; signin_el.style.display = "block"; fadeIn( signin_el, 1680 ); setStyleAtTime( el3, "display", "none", 1800 ); setStyleAtTime( el4, "display", "none", 1800 ); setStyleAtTime( el1, "display", "none", 1800 ); setStyleAtTime( el2, "display", "none", 1800 ); setStyleAtTime( el2, "color", "transparent", 1800 ); } function signupSuccess(){ var el = document.getElementById("rings"); shrinkOut( el ); var el = document.getElementById("signupsuccess"); growIn( el, 26 ); el.style.color = "white"; SIGN_UP_IN_VALUE = 1; var signin_el = document.getElementById("fields-1"); var signup_el = document.getElementById("fields-2"); var underl_el = document.getElementById("selection1"); underl_el.style.left = "16px"; var signup_text_el = document.getElementById("signup"); var signin_text_el = document.getElementById("signin"); signin_text_el.className = "selected"; signup_text_el.className = "unselected"; var el1 = document.getElementById("rings"); var el2 = document.getElementById("signupsuccess"); el1.style.display = "block"; el2.style.display = "block"; el1.style.opacity = "1"; el2.style.opacity = "1"; el2.style.backgroundSize = "0%"; el1.style.backgroundSize = "100%"; el1.style.backgroundImage = "url(imgs/rings.svg?" + Math.random() + ")"; var el3 = document.getElementById("successtext"); el3.style.display = "block"; el3.style.backgroundSize = "0"; el3.style.opacity = "1"; growIn( el3, 50, 5 ); var el4 = document.getElementById("signuptextG"); el4.style.display = "block"; el4.style.backgroundSize = "0"; el4.style.opacity = "1"; growIn( el4, 50, 5 ); shrinkOut( el1 ); growIn( el2, 28 ); fadeOut( el2, 1800 ); fadeOut( el1, 1800 ); fadeOut( el3, 1700 ) fadeOut( el4, 1700 ) signin_el.style.left = "16px"; signin_el.style.display = "block"; fadeIn( signin_el, 1800 ); setStyleAtTime( el1, "display", "none", 1800 ); setStyleAtTime( el2, "display", "none", 1800 ); setStyleAtTime( el3, "display", "none", 1800 ); setStyleAtTime( el4, "display", "none", 1800 ); setStyleAtTime( el2, "color", "transparent", 1800 ); } function simulateSignupSuccess(){ var el1 = document.getElementById("rings"); el1.style.backgroundImage = "url(imgs/rings.svg?" + Math.random() + ")"; el1.style.display = "block"; el1.style.backgroundSize = "100%"; el1.style.opacity = "1"; window.setTimeout(function() { signupSuccess(); }, 4000 ); } function simulateSignupFailure(){ var el1 = document.getElementById("rings"); el1.style.backgroundImage = "url(imgs/rings.svg?" + Math.random() + ")"; el1.style.display = "block"; el1.style.backgroundSize = "100%"; el1.style.opacity = "1"; var el3 = document.getElementById("failtext"); el3.style.display = "block"; el3.style.backgroundSize = "0"; el3.style.opacity = "1"; var el4 = document.getElementById("signuptextR"); el4.style.display = "block"; el4.style.backgroundSize = "0"; el4.style.opacity = "1"; window.setTimeout(function() { signupFailure(); }, 4000 ); } function simulateLoginFail(){ var el1 = document.getElementById("rings"); var el2 = document.getElementById("loginfail"); el1.style.display = "block"; el2.style.display = "block"; el1.style.opacity = "1"; el2.style.opacity = "1"; el2.style.backgroundSize = "0%"; el1.style.backgroundSize = "100%"; el1.style.backgroundImage = "url(imgs/rings.svg?" + Math.random() + ")"; var el3 = document.getElementById("failtext"); el3.style.display = "block"; el3.style.backgroundSize = "0"; el3.style.opacity = "1"; var el4 = document.getElementById("logintextR"); el4.style.display = "block"; el4.style.backgroundSize = "0"; el4.style.opacity = "1"; window.setTimeout(function() { shrinkOut( el1 ); el2.style.color = "red"; growIn( el2, 28 ); shakeLoginBox( 250 ); growIn( el3, 30, 10 ); growIn( el4, 60, 5 ); fadeOut( el2, 1500 ); fadeOut( el1, 1800 ); fadeOut( el3, 1500 ); fadeOut( el4, 1500 ); var signin_el = document.getElementById("fields-1"); signin_el.style.left = "16px"; signin_el.style.display = "block"; fadeIn( signin_el, 1900 ); setStyleAtTime( el1, "display", "none", 1800 ); setStyleAtTime( el2, "display", "none", 1800 ); setStyleAtTime( el3, "display", "none", 1800 ); setStyleAtTime( el4, "display", "none", 1800 ); setStyleAtTime( el2, "color", "transparent", 1800 ); }, 4000 ); } function setStyleAtTime( el, style, val, time ){ window.setTimeout(function() { el.style[style] = val; }, time ); } function noDisplayTime( el, time ){ window.setTimeout(function() { el.style.display = "none"; }, time ); } function growIn( el, growth, dur ){ el.style.display = "block"; if(dur === undefined ) dur = 10; var inc = 3; var test = 0; var left = 0; var amt = 0; for( var i = 0; i < growth; i++ ){ time = dur * i; window.setTimeout(function() { amt = inc*test++; size = amt; el.style.backgroundSize = size + "px"; test++; }, time); } } function shrinkOut( el, delay ){ if(delay === undefined) delay = 0; window.setTimeout(function() { var dur = 20; var inc = 30; var size = 0; var test = 0; var left = 0; var amt = 0; for( var i = 0; i < 31; i++ ){ time = dur * i; window.setTimeout(function() { amt = inc*test++; size = 300 - amt; el.style.backgroundSize = size + "px"; test++; }, time); } }, delay); } function loadingImage( bool, delay ){ var el = document.getElementById("rings"); if( delay === undefined ) delay = 0; window.setTimeout(function() { if( bool ) el.style.display = "block"; else el.style.display = "none"; }, delay); } function notifOff(){ var el = document.getElementById("notif"); el.style.display = "none"; var loginbox = document.getElementById("blanket"); loginbox.style.display = "none"; } function dimAlertShow( delay ){ var el = document.getElementById("notif"); if( delay === undefined ) delay = 0; window.setTimeout(function() { el.style.top = "-200px"; el.style.display = "block"; moveY( el, -100, 200, 50, 2 ); }, delay); el.onclick = function(){ notifOff(); } } function dimscreen( bool, delay ){ var loginbox = document.getElementById("blanket"); if( delay === undefined ) delay = 0; window.setTimeout(function() { if( bool ) loginbox.style.display = "block"; else loginbox.style.display = "none"; }, delay ); } function shakeLoginBox( starttime ){ var loginbox = document.getElementById("login"); //var firstX = getNums(loginbox.style.width); var pos0 = "calc(50% - 150px)"; var pos1 = "calc(50% - 160px)"; var pos2 = "calc(50% - 150px)"; var pos3 = "calc(50% - 140px)"; var pos1B = "calc(50% - 155px)"; var pos3B = "calc(50% - 145px)"; if(starttime === undefined ) starttime = 0; var time = starttime; var t = 30; window.setTimeout(function() { loginbox.style.left = pos1; }, time += t); window.setTimeout(function() { loginbox.style.left = pos2; }, time += t); window.setTimeout(function() { loginbox.style.left = pos3; }, time += t); window.setTimeout(function() { loginbox.style.left = pos0; }, time += t); window.setTimeout(function() { loginbox.style.left = pos1; }, time += t); window.setTimeout(function() { loginbox.style.left = pos2; }, time += t); window.setTimeout(function() { loginbox.style.left = pos3; }, time += t); window.setTimeout(function() { loginbox.style.left = pos0; }, time += t); window.setTimeout(function() { loginbox.style.left = pos1B; }, time += t); window.setTimeout(function() { loginbox.style.left = pos2; }, time += t); window.setTimeout(function() { loginbox.style.left = pos3B; }, time += t); window.setTimeout(function() { loginbox.style.left = pos0; }, time += t); } function signInSlideOut(){ var signin_el = document.getElementById("fields-1"); var signup_el = document.getElementById("fields-2"); moveX2( signin_el, 16, -300, inc = -20, dur = 2 ); fadeOut( signin_el, 0 ); signup_el.style.left = "16px"; signup_el.style.display = "block"; fadeIn( signup_el, 220 ); signup_el.style.opacity = 0.0; signup_el.style.display = "block"; } function signUpSlideOut(){ var signin_el = document.getElementById("fields-1"); var signup_el = document.getElementById("fields-2"); moveX2( signup_el, 16, -300, inc = -20, dur = 2 ); fadeOut( signup_el, 0 ); signin_el.style.left = "16px"; signin_el.style.display = "block"; fadeIn( signin_el, 220 ); signup_el.style.opacity = 0.0; signup_el.style.display = "block"; } function fadeOut( ele, delay ){ window.setTimeout(function() { callbackCreate( ele, "opacity", 1.0, 0.0, -0.2, 10 ); }, delay); } function fadeIn( ele, delay ){ window.setTimeout(function() { callbackCreate( ele, "opacity", 0.0, 1.0, 0.2, 10 ); }, delay); } function moveX2( el, from, to, by, dur ){ callbackCreate( el, "left", from, to, by, dur, "px"); // el, styl, start, end, inc, dur, unit } function moveY( el, from, to, by, dur, unit ){ if( unit === undefined ) unit = "px"; callbackCreate( el, "top", from, to, by, dur, unit ); // el, styl, start, end, inc, dur, unit } function callbackCreate( el, styl, start, end, inc, dur, unit ){ var times = []; var values = []; var fcns = []; if( unit === undefined ) unit = ""; var ob = {} ob.styl = undefined; ob.tims = []; ob.vals = []; ob.fcns = []; var len = Math.ceil((end - start) / inc); for(var i = 0 ; i < len; i++ ){ ob.tims.push( i * dur ); ob.vals.push( start + ( i * inc ) ); ob.fcns.push(function( val ){ el.style[styl] = val + unit; console.log( val ); }); } ob.tims.push( len * dur ); ob.vals.push( end ); ob.fcns.push(function( val ){ el.style[styl] = val + unit; console.log( val ); }); callback( ob ); } function callback( ob ){ // * fcns - array of functions to be run at the corresponding index in the time array // * times - start times for corresponding function indices - times scale: 1000 equals 1 second, 1 equals a millisecond // * example - callback([fnc1, fnc2], [time1 = 200, time2 = 700]); var fcns = ob.fcns; var times = ob.tims; if (fcns.length <= 0) return; (function chain(i) { if (i >= fcns.length || typeof fcns[i] !== 'function') return; window.setTimeout(function() { fcns[i]( ob.vals[i] ); chain(i + 1); }, times[i]); })(0); }
const through2 = require('through2') const GulpError = require('./gulp-error').partial('gulp-compile-cache') // 编译缓存gulp插件 module.exports = function gulpCompileCache(options = {}) { const { hit = () => {}, // 命中回调 } = options return through2.obj(function (file, enc, next) { if (file.isNull()) { return next(null, file) } try { const { checkFileCached } = file.context if (checkFileCached(file)) { // 命中回调 hit(file) // 终止流 return next(null, null) } } catch (e) { throw GulpError(file, e) } next(null, file) }) }
(function( window, undefined ) { kendo.cultures["pa-Arab-PK"] = { name: "pa-Arab-PK", numberFormat: { pattern: ["- n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { name: "Pakistani Rupee", abbr: "PKR", pattern: ["-$ n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "Rs" } }, calendars: { standard: { days: { names: ["پير","منگل","بدھ","جمعرات","جمعه","هفته","اتوار"], namesAbbr: ["پير","منگل","بدھ","جمعرات","جمعه","هفته","اتوار"], namesShort: ["پ","م","ب","ج","ج","ه","ا"] }, months: { names: ["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","ستمبر","اکتوبر","نومبر","دسمبر"], namesAbbr: ["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","ستمبر","اکتوبر","نومبر","دسمبر"] }, AM: ["AM","am","AM"], PM: ["PM","pm","PM"], patterns: { d: "dd-MM-yy", D: "dd MMMM yyyy dddd", F: "dd MMMM yyyy dddd h.mm.ss tt", g: "dd-MM-yy h.mm tt", G: "dd-MM-yy h.mm.ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "h.mm tt", T: "h.mm.ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "-", ":": ".", firstDay: 1 } } } })(this);
var webpack = require("webpack"); var path = require("path"); module.exports = { devtool: "eval-source-map", entry: "./src/main/index.ts", output: { filename: "./dist/index.js" }, resolve: { extensions: [".js", ".json", ".ts"] }, module: { rules: [ { enforce: "pre", exclude: /node_modules/, test: /\.ts$/, use: { loader: "tslint-loader", options: { emitErrors: true } } }, { test: /\.ts$/, include: [path.join(__dirname, "src")], use: "awesome-typescript-loader" } ] }, target: "electron-main", devServer: { overlay: true } }
var crypto = require('crypto'); var moment = require('moment'); // 首页-签到有礼-免费抽-赢三星Galaxy Z(试试手气) var transParams = (data) => { let params = new URLSearchParams(); for (let item in data) { params.append(item, data['' + item + '']); } return params; }; function w() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {} , t = []; return Object.keys(e).forEach((function (a) { t.push("".concat(a, "=").concat(encodeURIComponent(e[a]))) } )), t.join("&") } var sign = (data) => { let str = 'integralofficial&' let params = [] data.forEach((v, i) => { if (v) { params.push('arguments' + (i + 1) + v) } }); return crypto.createHash('md5').update(str + params.join('&')).digest('hex') } function encryption(data, key) { var iv = ""; var cipherEncoding = 'base64'; var cipher = crypto.createCipheriv('aes-128-ecb', key, iv); cipher.setAutoPadding(true); return Buffer.concat([cipher.update(data), cipher.final()]).toString(cipherEncoding); } var dailyCheapStorePage = { getGoodsList: async (axios, options) => { let phone = encryption(options.user, 'gb6YCccUvth75Tm2') const useragent = `Mozilla/5.0 (Linux; Android 7.1.2; SM-G977N Build/LMY48Z; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36; unicom{version:android@8.0200,desmobile:${options.user}};devicetype{deviceBrand:samsung,deviceModel:SM-G977N};{yw_code:} ` let result = await axios.request({ headers: { "user-agent": useragent, "referer": `https://wxapp.msmds.cn/`, "origin": "https://wxapp.msmds.cn" }, url: `https://wxapp.msmds.cn/jplus/api/change/collect/chip/gift/v1/home/info`, method: 'POST', data: transParams({ 'channelId': 'LT_channel', 'phone': phone, 'token': options.ecs_token, 'sourceCode': 'lt_cheapStore' }) }) result.data.data.list.forEach(g => { console.log('已有【' + g.giftName + '】碎片', `(${g.haveCount}/${g.limitCode})`) }) return result.data.data }, doTask: async (axios, options) => { const useragent = `Mozilla/5.0 (Linux; Android 7.1.2; SM-G977N Build/LMY48Z; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36; unicom{version:android@8.0200,desmobile:${options.user}};devicetype{deviceBrand:samsung,deviceModel:SM-G977N};{yw_code:}` let searchParams = {} let result = await axios.request({ baseURL: 'https://m.client.10010.com/', headers: { "user-agent": useragent, "referer": `https://img.client.10010.com/`, "origin": "https://img.client.10010.com" }, url: `https://m.client.10010.com/mobileService/openPlatform/openPlatLine.htm?to_url=https://wxapp.msmds.cn/h5/react_web/unicom/cheapStorePage?source=unicom&duanlianjieabc=tbkEG`, method: 'GET', transformResponse: (data, headers) => { if ('location' in headers) { let uu = new URL(headers.location) let pp = {} for (let p of uu.searchParams) { pp[p[0]] = p[1] } if ('ticket' in pp) { searchParams = pp } } return data } }).catch(err => console.log(err)) let jar1 = result.config.jar let cookiesJson = jar1.toJSON() let ecs_token = cookiesJson.cookies.find(i => i.key == 'ecs_token') if (!ecs_token) { throw new Error('ecs_token缺失') } ecs_token = ecs_token.value let phone = encryption(options.user, 'gb6YCccUvth75Tm2') let playCounts = 0 let bottleCount = 0 // 每6个小时6次机会,可使用能量瓶重置机会 let tryn = 5 do { let res = await dailyCheapStorePage.getGoodsList(axios, { ...options, ecs_token, phone }) playCounts = res.playCounts bottleCount = res.bottleCount console.log('剩余能量瓶:', bottleCount, '剩余游戏机会:', playCounts) if ('times' in res) { console.log('每6个小时6次机会', moment(new Date(res.times)).format('YYYY-MM-DD HH:mm:ss') + ' 后可再次尝试') } if (!playCounts) {// 用完机会再使用能量瓶重置 console.log('尝试使用能量瓶重置机会') let bs = 1 if (!bottleCount) { bs = await dailyCheapStorePage.getBottle(axios, { ...options, jar: jar1, searchParams, ecs_token }) } if (bs === 2) { break } else if (bs === 1) { await dailyCheapStorePage.bottleExpend(axios, { ...options, jar: jar1, searchParams, ecs_token }) playCounts = 6 console.log('重置机会成功+', playCounts) } else if (bs === 0) { // 防止错误循环 tryn = tryn - 1 if (!tryn) { console.log('出现错误,重试重置机会超过5次,跳过任务') break } else { console.log('出现错误,重试重置机会') continue } } } let a = { 'channelId': 'LT_channel', 'code': '', "phone": phone, 'token': ecs_token, 'sourceCode': 'lt_cheapStore' } let timestamp = moment().format('YYYYMMDDHHmmss') result = await axios.request({ headers: { "user-agent": useragent, "referer": `https://wxapp.msmds.cn/h5/react_web/unicom/cheapStorePage?source=unicom&type=02&ticket=${searchParams.ticket}&version=android@8.0200&timestamp=${timestamp}&desmobile=${options.user}&num=0&postage=${searchParams.postage}&duanlianjieabc=tbkEG&userNumber=${options.user}`, "origin": "https://wxapp.msmds.cn" }, url: `https://wxapp.msmds.cn/jplus/api/change/collect/chip/gift/v1/play/luck/draw?` + w(a), method: 'POST' }) if (result.data.code !== 200) { console.log('提交任务失败', result.data.msg) if (result.data.msg.indexOf('请勿频繁操作') !== -1) { throw new Error('取消本次任务') } } else { let data = result.data.data let good = res.list.find(f => f.giftId === data.giftId) console.log('提交任务成功,获得', good.giftName, '累计商品碎片x' + data.fragmentCount, data.desc + data.playCounts) } if (playCounts) { console.log('等待15秒再继续') await new Promise((resolve, reject) => setTimeout(resolve, 15 * 1000)) } } while (playCounts) console.log('进入下一轮的尝试等待期') }, getBottleState: async (axios, options) => { const { jar, searchParams, ecs_token } = options const useragent = `Mozilla/5.0 (Linux; Android 7.1.2; SM-G977N Build/LMY48Z; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36; unicom{version:android@8.0200,desmobile:${options.user}};devicetype{deviceBrand:samsung,deviceModel:SM-G977N};{yw_code:}` let phone = encryption(options.user, 'gb6YCccUvth75Tm2') let a = { 'channelId': 'LT_channel', "phone": phone, 'isDetails': 'false', 'token': ecs_token, 'sourceCode': 'lt_cheapStore' } let timestamp = moment().format('YYYYMMDDHHmmss') result = await axios.request({ headers: { "user-agent": useragent, "referer": `https://wxapp.msmds.cn/h5/react_web/unicom/cheapStorePage?source=unicom&type=02&ticket=${searchParams.ticket}&version=android@8.0200&timestamp=${timestamp}&desmobile=${options.user}&num=0&postage=${searchParams.postage}&duanlianjieabc=tbkEG&userNumber=${options.user}`, "origin": "https://wxapp.msmds.cn" }, url: `https://wxapp.msmds.cn/jplus/api/change/collect/chip/gift/v1/bottle/add`, method: 'POST', data: transParams(a) }) if (result.data.code !== 200) { console.log('查询能量瓶状态失败', result.data.msg) } else { if (result.data.data.status === 1) { if ('times' in result.data.data) { let m = moment(new Date(result.data.data.times)).format('YYYY-MM-DD HH:mm:ss') + ' 后可再次尝试' console.log(result.data.data.text, m) return false } } else { return true } } return false }, // 获取能量瓶 4个小时只能获取3次能量瓶的机会 getBottle: async (axios, options) => { const { jar, searchParams, ecs_token } = options let state = await dailyCheapStorePage.getBottleState(axios, options) if (!state) { console.log('跳过获取能量瓶') return 2 } const useragent = `Mozilla/5.0 (Linux; Android 7.1.2; SM-G977N Build/LMY48Z; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36; unicom{version:android@8.0200,desmobile:${options.user}};devicetype{deviceBrand:samsung,deviceModel:SM-G977N};{yw_code:}` let phone = encryption(options.user, 'gb6YCccUvth75Tm2') // 每4小时3次, 等每轮机会用完再获取 let params = { 'arguments1': '', 'arguments2': '', 'arguments3': '', 'arguments4': new Date().getTime(), 'arguments6': '', 'arguments7': '', 'arguments8': '', 'arguments9': '', 'netWay': 'Wifi', 'remark': '签到小游戏买什么都省申请便利店抽奖', 'version': `android@8.0200`, 'codeId': 945535693 } params['sign'] = sign([params.arguments1, params.arguments2, params.arguments3, params.arguments4]) params['orderId'] = crypto.createHash('md5').update(new Date().getTime() + '').digest('hex') params['arguments4'] = new Date().getTime() let result = await require('./taskcallback').reward(axios, { ...options, params, jar }) let a = { 'channelId': 'LT_channel', "phone": phone, 'isDetails': 'false', 'token': ecs_token, 'videoOrderNo': params['orderId'], 'sourceCode': 'lt_cheapStore' } let timestamp = moment().format('YYYYMMDDHHmmss') result = await axios.request({ headers: { "user-agent": useragent, "referer": `https://wxapp.msmds.cn/h5/react_web/unicom/cheapStorePage?source=unicom&type=02&ticket=${searchParams.ticket}&version=android@8.0200&timestamp=${timestamp}&desmobile=${options.user}&num=0&postage=${searchParams.postage}&duanlianjieabc=tbkEG&userNumber=${options.user}`, "origin": "https://wxapp.msmds.cn" }, url: `https://wxapp.msmds.cn/jplus/api/change/collect/chip/gift/v1/bottle/add`, method: 'POST', data: transParams(a) }) if (result.data.code !== 200) { console.log('提交任务失败', result.data.msg) } else { if (result.data.data.status === 0) { console.log('提交任务成功', `获得能量瓶+${result.data.data.bottleCounts}`) return 1 } else { console.log('提交任务成功', `已无法获得能量瓶`, result.data.data.text) return 2 } } console.log('等待5秒再继续') await new Promise((resolve, reject) => setTimeout(resolve, 5 * 1000)) return 0 }, // 能量瓶兑换机会 bottleExpend: async (axios, options) => { const { jar, searchParams, ecs_token } = options const useragent = `Mozilla/5.0 (Linux; Android 7.1.2; SM-G977N Build/LMY48Z; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36; unicom{version:android@8.0200,desmobile:${options.user}};devicetype{deviceBrand:samsung,deviceModel:SM-G977N};{yw_code:}` let phone = encryption(options.user, 'gb6YCccUvth75Tm2') let a = { 'channelId': 'LT_channel', "phone": phone, 'token': ecs_token, 'sourceCode': 'lt_cheapStore' } let timestamp = moment().format('YYYYMMDDHHmmss') result = await axios.request({ headers: { "user-agent": useragent, "referer": `https://wxapp.msmds.cn/h5/react_web/unicom/cheapStorePage?source=unicom&type=02&ticket=${searchParams.ticket}&version=android@8.0200&timestamp=${timestamp}&desmobile=${options.user}&num=0&postage=${searchParams.postage}&duanlianjieabc=tbkEG&userNumber=${options.user}`, "origin": "https://wxapp.msmds.cn" }, url: `https://wxapp.msmds.cn/jplus/api/change/collect/chip/gift/v1/bottle/expend`, method: 'POST', data: transParams(a) }) if (result.data.code !== 200) { console.log('提交任务失败', result.data.msg) } else { console.log('提交任务成功', `能量瓶兑换抽奖机会成功`) } } } module.exports = dailyCheapStorePage
var environment = process.env.NODE_ENV || 'development' var config = require('../knexfile.js')[environment] module.exports = require('knex')(config)
/* eslint-env jest */ const { axe } = require('jest-axe') const { render, getExamples } = require('../../../lib/jest-helpers') const examples = getExamples('table') describe('Table', () => { it('default example passes accessibility tests', async () => { const $ = render('table', examples.default) const results = await axe($.html()) expect(results).toHaveNoViolations() }) it('renders with classes', () => { const $ = render('table', { 'classes': 'custom-class-goes-here', 'rows': [ [ { 'text': 'January' }, { 'text': '£85', 'format': 'numeric' } ], [ { 'text': 'February' }, { 'text': '£165', 'format': 'numeric' } ] ] }) const $component = $('.govuk-table') expect($component.hasClass('custom-class-goes-here')).toBeTruthy() }) it('renders with caption text', () => { const $ = render('table', examples['table-with-caption-and-head']) const $caption = $('.govuk-table__caption') expect($caption.text()).toBe('Caption 1 : Months and rates') }) it('renders the caption size class', () => { const $ = render('table', examples['table-with-caption-and-head']) const $caption = $('.govuk-table__caption') expect($caption.hasClass('govuk-heading-m')).toBeTruthy() }) it('renders first cell in every row as a <th> element with correct `govuk-table__header` class and `scope=row` attribute', () => { const $ = render('table', { 'firstCellIsHeader': true, 'rows': [ [ { 'text': 'January' }, { 'text': '£85', 'format': 'numeric' }, { 'text': '£95', 'format': 'numeric' } ], [ { 'text': 'February' }, { 'text': '£75', 'format': 'numeric' }, { 'text': '£55', 'format': 'numeric' } ] ] }) const $component = $('.govuk-table') const $tableBody = $component.find('.govuk-table .govuk-table__body') const $firstTableRow = $tableBody.find('.govuk-table__row:first-child') const $firstTableHeader = $firstTableRow.find('.govuk-table__header:first-child') expect($firstTableHeader.get(0).tagName).toEqual('th') expect($firstTableHeader.attr('scope')).toEqual('row') expect($firstTableHeader.hasClass('govuk-table__header')).toBeTruthy() const $lastTableRow = $tableBody.find('.govuk-table__row:last-child') const $lastTableHeader = $lastTableRow.find('.govuk-table__header:first-child') expect($lastTableHeader.get(0).tagName).toEqual('th') expect($lastTableHeader.attr('scope')).toEqual('row') expect($lastTableHeader.hasClass('govuk-table__header')).toBeTruthy() }) it('renders with thead', () => { const args = examples['table-with-head'] const $ = render('table', args) const $component = $('.govuk-table') const $tableHead = $component.find('.govuk-table__head') const $tableHeadRow = $tableHead.find('.govuk-table__row') const $tableHeadCell = $tableHeadRow.find('.govuk-table__header') expect($tableHead).toHaveLength(1) expect($tableHeadRow).toHaveLength(1) expect($tableHeadCell).toHaveLength(3) }) it('renders table header cell `format` attribute correctly', () => { const $ = render('table', { 'head': [ { 'text': 'Month you apply' }, { 'text': 'Rate for bicycles', 'format': 'numeric' }, { 'text': 'Rate for vehicles', 'format': 'numeric' } ], 'rows': [ [ { 'text': 'January' }, { 'text': '£85', 'format': 'numeric' } ], [ { 'text': 'February' }, { 'text': '£165', 'format': 'numeric' } ] ] }) const $component = $('.govuk-table') const $tableHeadCell = $component.find('.govuk-table__head .govuk-table__header') expect($tableHeadCell.eq(1).attr('class')).toMatch('govuk-table__header--numeric') }) describe('rows and cells', () => { const $ = render('table', examples.default) const $component = $('.govuk-table') const $tableBody = $component.find('.govuk-table__body') const $tableRow = $component.find('.govuk-table__row') const $tableCell = $component.find('.govuk-table__cell') it('renders one tbody element', () => { expect($tableBody).toHaveLength(1) }) it('renders the specified number of rows', () => { expect($tableRow).toHaveLength(3) }) it('renders the specified number of cells in row 1', () => { expect($tableRow.eq(0).find($tableCell)).toHaveLength(3) }) it('renders the specified number of cells in row 2', () => { expect($tableRow.eq(1).find($tableCell)).toHaveLength(3) }) it('renders the specified number of cells in row 3', () => { expect($tableRow.eq(2).find($tableCell)).toHaveLength(3) }) it('renders correct text in cell 1 of row 1', () => { expect($tableRow.eq(0).find($tableCell).eq(0).text()).toEqual('January') }) it('renders correct text in cell 2 of row 1', () => { expect($tableRow.eq(0).find($tableCell).eq(1).text()).toEqual('£85') }) it('renders correct text in cell 3 of row 1', () => { expect($tableRow.eq(0).find($tableCell).eq(2).text()).toEqual('£95') }) }) it('renders cell with html', () => { const $ = render('table', { 'rows': [ [ { 'text': 'January' }, { 'html': '<em>85</em>', 'format': 'numeric' }, { 'text': '£165', 'format': 'numeric' } ] ] }) const $component = $('.govuk-table') const $tableBody = $component.find('.govuk-table__body') const $tableRow = $tableBody.find('.govuk-table__row') const $tableCell = $tableRow.find('.govuk-table__cell') expect($tableCell.eq(1).html()).toEqual('<em>85</em>') }) it('renders cell escaped html in text', () => { const $ = render('table', { 'rows': [ [ { 'text': 'January' }, { 'text': '<em>85</em>', 'format': 'numeric' }, { 'text': '£165', 'format': 'numeric' } ] ] }) const $component = $('.govuk-table') const $tableBody = $component.find('.govuk-table__body') const $tableRow = $tableBody.find('.govuk-table__row') const $tableCell = $tableRow.find('.govuk-table__cell') expect($tableCell.eq(1).html()).toEqual('&lt;em&gt;85&lt;/em&gt;') }) it('renders cell `format` attribute correctly', () => { const $ = render('table', { 'rows': [ [ { 'text': 'January' }, { 'text': '£85', 'format': 'numeric' } ], [ { 'text': 'February' }, { 'text': '£165', 'format': 'numeric' } ] ] }) const $component = $('.govuk-table') const $tableCell = $component.find('.govuk-table__body .govuk-table__cell') expect($tableCell.eq(1).attr('class')).toMatch('govuk-table__cell--numeric') }) it('renders cell `colspan` attribute correctly', () => { const $ = render('table', { 'rows': [ [ { 'text': 'January' }, { 'text': '£85', 'format': 'numeric', 'colspan': 2 } ], [ { 'text': 'February' }, { 'text': '£165', 'format': 'numeric' } ] ] }) const $component = $('.govuk-table') const $tableCell = $component.find('.govuk-table__body .govuk-table__row .govuk-table__cell') expect($tableCell.eq(1).attr('colspan')).toEqual('2') }) it('renders cell `rowspan` attribute correctly', () => { const $ = render('table', { 'rows': [ [ { 'text': 'January' }, { 'text': '£85', 'format': 'numeric', 'rowspan': 2 } ], [ { 'text': 'February' }, { 'text': '£165', 'format': 'numeric' } ] ] }) const $component = $('.govuk-table') const $tableCell = $component.find('.govuk-table__body .govuk-table__row .govuk-table__cell') expect($tableCell.eq(1).attr('rowspan')).toEqual('2') }) it('renders with attributes', () => { const $ = render('table', { 'attributes': { 'attribute-1': 'yes', 'attribute-2': 'no' }, 'rows': [ [ { 'text': 'January' }, { 'text': '£85', 'format': 'numeric' } ], [ { 'text': 'February' }, { 'text': '£165', 'format': 'numeric' } ] ] }) const $component = $('.govuk-table') expect($component.attr('attribute-1')).toEqual('yes') expect($component.attr('attribute-2')).toEqual('no') }) })
// For output.filename configuration: // // Change "component-name" in this file to your real component name! // DO NOT CHANGE "[name]", which denotes the entry property names that webpack automatically inserts for you! module.exports = { entry: { dev: ['webpack/hot/dev-server', './main.js', './demo/demo.js'], dist: ['./main.js'] }, output: { path: './', filename: 'build/[name].component-name.js', libraryTarget: 'umd' }, externals: [ { 'react': { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } }, { 'react-dom': { root: 'ReactDOM', commonjs2: 'react-dom', commonjs: 'react-dom', amd: 'react-dom' } } ], contentBase: './demo', // for webpack dev server module: { preLoaders: [ { test: /\.js$/, loader: 'eslint', exclude: /node_modules/ } ], loaders: [ { test: /\.scss$/, loader: 'style!css!sass' // sass -> css -> javascript -> inline style }, { test: /\.js$/, loader: 'babel', query: { cacheDirectory: true, presets: ['es2015', 'react', 'stage-0'] } }, { test: /\.json$/, loader: 'json' } ] } };
function getFileDirectory(filename) { const array = filename.split('/') return array[array.length - 2] } export function getFilename(filename) { const array = filename.split('/') return array[array.length - 1] } export function getFileRoot(filename) { let array = filename.split('/') const directory = getFileDirectory(filename) if (directory === undefined) { return } array = array.slice(0, array.length - 2) array = array.map((x) => x[0]) array.push(directory) array = array.join('/') array = `${array}/` return array } export function getChangeTypeColor(changeType) { if (changeType === 'D') { return 'text-pink-600' } else { return 'text-blue-400' } }
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['en-nf'] = [ 'en-NF', [['a', 'p'], ['am', 'pm'], u], [['am', 'pm'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ], u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'AUD', '$', 'Australian Dollar', {'AUD': ['$'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, 'ltr', plural, [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
/* global describe, it, require */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Check whether an element is a finite number isFiniteNumber = require( 'validate.io-finite' ), // Check whether an element is `NaN` isnan = require( 'validate.io-nan' ), // Module to be tested: partial = require( './../lib/partial.js' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'partial quantile', function tests() { var validationData = require( './fixtures/partial.json' ), data = validationData.data, expected = validationData.expected.map( function( d ) { if (d === 'Inf' ) { return Number.POSITIVE_INFINITY; } if ( d === '-Inf' ) { return Number.NEGATIVE_INFINITY; } return d; }), alpha = validationData.alpha, beta = validationData.beta; it( 'should export a function', function test() { expect( partial ).to.be.a( 'function' ); }); it( 'should partially apply the quantile function of the Beta distribution for given parameter values', function test() { var quantile; quantile = partial( alpha, beta ); expect( quantile ).to.be.a( 'function' ); }); it( 'should return a function which evaluates the quantile function', function test() { var quantile, actual; quantile = partial( alpha, beta ); for ( var i = 0; i < data.length; i++ ) { actual = quantile( data[ i ] ); if ( isFiniteNumber( actual ) && isFiniteNumber( expected[ i ] ) ) { assert.closeTo( actual, expected[ i ] , 1e-12 ); } } }); it( 'should return `NaN` if provided `NaN` as input', function test() { var quantile = partial( alpha, beta ); assert.isTrue( isnan( quantile( NaN ) ) ); }); it( 'should return `NaN` if provided a number outside [0,1]', function test() { var quantile = partial( alpha, beta ); assert.isTrue( isnan( quantile( 1.1 ) ) ); assert.isTrue( isnan( quantile( -0.1 ) ) ); }); });
import React from 'react' import Enzyme, { shallow, mount } from 'enzyme' import Adapter from 'enzyme-adapter-react-16' import GranuleResultsBody from '../GranuleResultsBody' import GranuleResultsList from '../GranuleResultsList' import GranuleResultsTable from '../GranuleResultsTable' Enzyme.configure({ adapter: new Adapter() }) beforeEach(() => { jest.clearAllMocks() }) function setup(options = { mount: false }, overrideProps) { const props = { collectionId: 'collectionId', directDistributionInformation: {}, focusedGranuleId: '', granulesMetadata: { one: { id: 'two', browseFlag: true, onlineAccessFlag: true, dayNightFlag: 'DAY', formattedTemporal: [ '2019-04-28 00:00:00', '2019-04-29 23:59:59' ], thumbnail: '/fake/path/image.jpg', title: 'Granule title one', links: [ { rel: 'http://linkrel/data#', title: 'linktitle', href: 'http://linkhref' } ] }, two: { id: 'two', browseFlag: true, onlineAccessFlag: true, dayNightFlag: 'DAY', formattedTemporal: [ '2019-04-28 00:00:00', '2019-04-29 23:59:59' ], thumbnail: '/fake/path/image.jpg', title: 'Granule title two', links: [ { rel: 'http://linkrel/data#', title: 'linktitle', href: 'http://linkhref' } ] } }, granuleQuery: {}, granuleSearchResults: { allIds: ['one', 'two'], hits: '2', isLoaded: true, isLoading: false, loadTime: 1123, timerStart: null }, isOpenSearch: false, loadNextPage: jest.fn(), location: { search: 'value' }, onAddGranuleToProjectCollection: jest.fn(), onExcludeGranule: jest.fn(), onFocusedGranuleChange: jest.fn(), onMetricsDataAccess: jest.fn(), onRemoveGranuleFromProjectCollection: jest.fn(), panelView: 'list', portal: {}, project: {}, ...overrideProps } let enzymeWrapper if (options.mount) { enzymeWrapper = mount(<GranuleResultsBody {...props} />) } else { enzymeWrapper = shallow(<GranuleResultsBody {...props} />) } return { enzymeWrapper, props } } describe('GranuleResultsBody component', () => { test('renders itself correctly', () => { const { enzymeWrapper, props } = setup() const { collectionId, loadNextPage, onExcludeGranule, onFocusedGranuleChange, onMetricsDataAccess } = props const resultsList = enzymeWrapper.find(GranuleResultsList) expect(enzymeWrapper.exists()).toEqual(true) expect(enzymeWrapper.prop('className')).toBe('granule-results-body') expect(resultsList.props()).toEqual(expect.objectContaining({ collectionId, itemCount: 2, loadMoreItems: loadNextPage, onExcludeGranule, onFocusedGranuleChange, onMetricsDataAccess, visibleMiddleIndex: null })) }) test('renders GranuleResultsTable', () => { const { enzymeWrapper, props } = setup({ panelView: 'table' }) const { collectionId, loadNextPage, onExcludeGranule, onFocusedGranuleChange, onMetricsDataAccess } = props const resultsTable = enzymeWrapper.find(GranuleResultsTable) expect(resultsTable.props()).toEqual(expect.objectContaining({ collectionId, itemCount: 2, loadMoreItems: loadNextPage, onExcludeGranule, onFocusedGranuleChange, onMetricsDataAccess, visibleMiddleIndex: null })) }) test('adds a dummy item when the first granules are loading', () => { const { enzymeWrapper, props } = setup(true, { granuleSearchResults: { allIds: [], isLoading: true } }) const resultsList = enzymeWrapper.find(GranuleResultsList) expect(resultsList.props()).toEqual(expect.objectContaining({ granules: [], itemCount: 1 })) resultsList.props().loadMoreItems() expect(props.loadNextPage).toHaveBeenCalledTimes(0) }) test('adds a dummy item when new granules are loading', () => { const { enzymeWrapper, props } = setup() const resultsList = enzymeWrapper.find(GranuleResultsList) expect(resultsList.props()).toEqual(expect.objectContaining({ itemCount: 2 })) resultsList.props().loadMoreItems() expect(props.loadNextPage).toHaveBeenCalledTimes(1) }) test('does not add a dummy item when all collections are loaded', () => { const { enzymeWrapper, props } = setup(true, { granulesMetadata: { one: { id: 'two', browseFlag: true, onlineAccessFlag: true, dayNightFlag: 'DAY', formattedTemporal: [ '2019-04-28 00:00:00', '2019-04-29 23:59:59' ], thumbnail: '/fake/path/image.jpg', title: 'Granule title one', links: [ { rel: 'http://linkrel/data#', title: 'linktitle', href: 'http://linkhref' } ] } }, granuleQuery: {}, granuleSearchResults: { allIds: ['one'], hits: 1, isLoaded: true, isLoading: false, loadTime: 1123, timerStart: null } }) const resultsList = enzymeWrapper.find(GranuleResultsList) expect(resultsList.props()).toEqual(expect.objectContaining({ itemCount: 1 })) resultsList.props().loadMoreItems() expect(props.loadNextPage).toHaveBeenCalledTimes(1) }) test('passes the granules to a single GranuleResultsList component', () => { const { enzymeWrapper } = setup() expect(enzymeWrapper.find(GranuleResultsList).length).toEqual(1) expect(enzymeWrapper.find(GranuleResultsList).props().granules[0]).toEqual( expect.objectContaining({ title: 'Granule title one' }) ) expect(enzymeWrapper.find(GranuleResultsList).props().granules[1]).toEqual( expect.objectContaining({ title: 'Granule title two' }) ) }) test('passes the onMetricsDataAccess callback to the GranuleResultsList component', () => { const { enzymeWrapper, props } = setup() expect(enzymeWrapper.find(GranuleResultsList).length).toEqual(1) expect(enzymeWrapper.find(GranuleResultsList).props().onMetricsDataAccess) .toEqual(props.onMetricsDataAccess) }) test('renders the correct search time', () => { const { enzymeWrapper } = setup() expect(enzymeWrapper.find('.granule-results-body__search-time-value').text()).toEqual('1.1s') }) describe('isItemLoaded', () => { describe('when there is no next page', () => { test('returns true', () => { const { enzymeWrapper } = setup(true, { granulesMetadata: { one: { id: 'one', browseFlag: true, onlineAccessFlag: true, dayNightFlag: 'DAY', formattedTemporal: [ '2019-04-28 00:00:00', '2019-04-29 23:59:59' ], thumbnail: '/fake/path/image.jpg', title: 'Granule title one', links: [ { rel: 'http://linkrel/data#', title: 'linktitle', href: 'http://linkhref' } ] } }, granuleSearchResults: { allIds: ['one'], hits: 1, isLoading: false, isLoaded: true, loadTime: 1150, timerStart: null } }) const resultsList = enzymeWrapper.find(GranuleResultsList) expect(resultsList.props().isItemLoaded(1)).toEqual(true) }) }) describe('when there is a next page and the item is loaded', () => { test('returns false', () => { const { enzymeWrapper } = setup(true, { granulesMetadata: { one: { id: 'one', browseFlag: true, onlineAccessFlag: true, dayNightFlag: 'DAY', formattedTemporal: [ '2019-04-28 00:00:00', '2019-04-29 23:59:59' ], thumbnail: '/fake/path/image.jpg', title: 'Granule title one', links: [ { rel: 'http://linkrel/data#', title: 'linktitle', href: 'http://linkhref' } ] } }, granuleSearchResults: { allIds: ['one'], hits: '2', isLoading: false, isLoaded: true, loadTime: 1150, timerStart: null } }) const resultsList = enzymeWrapper.find(GranuleResultsList) expect(resultsList.props().isItemLoaded(2)).toEqual(false) }) }) }) describe('isGranuleInProject', () => { test('when the granule is added to the project', () => { const { enzymeWrapper } = setup({}, { project: { collections: { allIds: ['collectionId'], byId: { collectionId: { granules: { addedGranuleIds: ['one'] } } } } } }) const resultsList = enzymeWrapper.find(GranuleResultsList) expect(resultsList.prop('isGranuleInProject')('one')).toBe(true) expect(resultsList.prop('isGranuleInProject')('two')).toBe(false) }) test('when all granules are added to the project', () => { const { enzymeWrapper } = setup({}, { project: { collections: { allIds: ['collectionId'], byId: { collectionId: {} } } } }) const resultsList = enzymeWrapper.find(GranuleResultsList) expect(resultsList.prop('isGranuleInProject')('one')).toBe(true) expect(resultsList.prop('isGranuleInProject')('two')).toBe(true) }) test('when granules are removed from the project', () => { const { enzymeWrapper } = setup({}, { project: { collections: { allIds: ['collectionId'], byId: { collectionId: { granules: { removedGranuleIds: ['one'] } } } } } }) const resultsList = enzymeWrapper.find(GranuleResultsList) expect(resultsList.prop('isGranuleInProject')('one')).toBe(false) expect(resultsList.prop('isGranuleInProject')('two')).toBe(true) }) }) })
export const nextStep = () => { return { type: 'NEXT_STEP' } } export const clickCell = (row, column) => { return { type: 'CLICK_CELL', row, column } }
// const EmailService = require('../../lib'); describe('EmailService Tests', () => { describe('#constructor', () => { describe('Positive tests', () => { it('Should create service instance', () => { // let emailService = new EmailService(); }); }); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var environment_1 = require("../../environment"); var util = require("../../util"); var shader_compiler = require("./shader_compiler"); var NAN_UNIFORM_NAME = 'NaN'; function shouldUploadNaNUniform() { return !environment_1.ENV.get('WEBGL_FLOAT_TEXTURE_ENABLED'); } function compileProgram(gpgpu, program, inputs, output) { var userCode = program.userCode; var inputInfos = inputs.map(function (input, i) { var shapeInfo = { logicalShape: input.shape, texShape: input.getTextureShapeRC() }; return { name: program.variableNames[i], shapeInfo: shapeInfo }; }); var inShapeInfos = inputInfos.map(function (x) { return x.shapeInfo; }); var outShapeInfo = { logicalShape: output.shape, texShape: output.getTextureShapeRC() }; var source = shader_compiler.makeShader(inputInfos, outShapeInfo, userCode, program.supportsBroadcasting === true); var webGLProgram = gpgpu.createProgram(source); var uniformLocations = {}; for (var i = 0; i < program.variableNames.length; i++) { var uniformName = program.variableNames[i]; uniformLocations[uniformName] = gpgpu.getUniformLocation(webGLProgram, uniformName); } if (shouldUploadNaNUniform()) { uniformLocations[NAN_UNIFORM_NAME] = gpgpu.getUniformLocation(webGLProgram, NAN_UNIFORM_NAME); } return { program: program, source: source, webGLProgram: webGLProgram, uniformLocations: uniformLocations, gpgpu: gpgpu, inShapeInfos: inShapeInfos, outShapeInfo: outShapeInfo }; } exports.compileProgram = compileProgram; function validateBinaryAndProgram(shapeInfos, inputs) { if (shapeInfos.length !== inputs.length) { throw Error("Binary was compiled with " + shapeInfos.length + " inputs, but " + ("was executed with " + inputs.length + " inputs")); } shapeInfos.forEach(function (s, i) { var shapeA = s.logicalShape; var texShapeA = s.texShape; var shapeB = inputs[i].shape; var texShapeB = inputs[i].getTextureShapeRC(); if (!util.arraysEqual(shapeA, shapeB)) { throw Error("Binary was compiled with different shapes than " + ("the current args. Shapes " + shapeA + " and " + shapeB + " must match")); } if (!util.arraysEqual(texShapeA, texShapeB)) { throw Error("Binary was compiled with different texture shapes than the" + (" current args. Shape " + texShapeA + " and " + texShapeB + " must match")); } }); } function runProgram(binary, inputs, output, customSetup) { validateBinaryAndProgram(binary.inShapeInfos, inputs); validateBinaryAndProgram([binary.outShapeInfo], [output]); var outTex = output.getTexture(); var outTexShape = output.getTextureShapeRC(); var gpgpu = binary.gpgpu; gpgpu.setOutputMatrixTexture(outTex, outTexShape[0], outTexShape[1]); gpgpu.setProgram(binary.webGLProgram); inputs.forEach(function (input, i) { var tex = input.getTexture(); var variableName = binary.program.variableNames[i]; var variableUniformLocation = binary.uniformLocations[variableName]; gpgpu.setInputMatrixTexture(tex, variableUniformLocation, i); }); if (shouldUploadNaNUniform()) { gpgpu.gl.uniform1f(binary.uniformLocations[NAN_UNIFORM_NAME], NaN); } if (customSetup != null) { customSetup(gpgpu, binary.webGLProgram); } gpgpu.executeProgram(); } exports.runProgram = runProgram; function makeShaderKey(program, inputs, output) { var params = program.params; var keyStart = inputs.concat(output).map(function (x) { return x.shape + '_' + x.getTextureShapeRC(); }); var keyEnd = params.map(String); var key = [program.constructor.name]; key.push((program.supportsBroadcasting === true).toString()); key = key.concat(keyStart, keyEnd); return key.join('_'); } exports.makeShaderKey = makeShaderKey; //# sourceMappingURL=gpgpu_math.js.map
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var BitmapText = require('./BitmapText'); var GameObjectFactory = require('../../GameObjectFactory'); /** * Creates a new Bitmap Text Game Object and adds it to the Scene. * * BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. * * During rendering for each letter of the text is rendered to the display, proportionally spaced out and aligned to * match the font structure. * * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability * to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by * processing the font texture in an image editor, applying fills and any other effects required. * * To create multi-line text insert \r, \n or \r\n escape codes into the text string. * * To create a BitmapText data files you need a 3rd party app such as: * * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/ * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner * Littera (Web-based, free): http://kvazars.com/littera/ * * For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of * converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson * * Note: This method will only be available if the Bitmap Text Game Object has been built into Phaser. * * @method Phaser.GameObjects.GameObjectFactory#bitmapText * @since 3.0.0 * * @param {number} x - The x position of the Game Object. * @param {number} y - The y position of the Game Object. * @param {string} font - The key of the font to use from the BitmapFont cache. * @param {(string|string[])} [text] - The string, or array of strings, to be set as the content of this Bitmap Text. * @param {number} [size] - The font size to set. * @param {integer} [align=0] - The alignment of the text in a multi-line BitmapText object. * * @return {Phaser.GameObjects.BitmapText} The Game Object that was created. */ GameObjectFactory.register('bitmapText', function (x, y, font, text, size, align) { return this.displayList.add(new BitmapText(this.scene, x, y, font, text, size, align)); }); // When registering a factory function 'this' refers to the GameObjectFactory context. // // There are several properties available to use: // // this.scene - a reference to the Scene that owns the GameObjectFactory // this.displayList - a reference to the Display List the Scene owns // this.updateList - a reference to the Update List the Scene owns
define('aurelia-path',['exports'], function (exports) { exports.__esModule = true; exports.relativeToFile = relativeToFile; exports.join = join; exports.buildQueryString = buildQueryString; exports.parseQueryString = parseQueryString; function trimDots(ary) { for (var i = 0; i < ary.length; ++i) { var part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 0 || i === 1 && ary[2] === '..' || ary[i - 1] === '..') { continue; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } function relativeToFile(name, file) { var fileParts = file && file.split('/'); var nameParts = name.trim().split('/'); if (nameParts[0].charAt(0) === '.' && fileParts) { var normalizedBaseParts = fileParts.slice(0, fileParts.length - 1); nameParts.unshift.apply(nameParts, normalizedBaseParts); } trimDots(nameParts); return nameParts.join('/'); } function join(path1, path2) { if (!path1) { return path2; } if (!path2) { return path1; } var schemeMatch = path1.match(/^([^/]*?:)\//); var scheme = schemeMatch && schemeMatch.length > 0 ? schemeMatch[1] : ''; path1 = path1.substr(scheme.length); var urlPrefix = undefined; if (path1.indexOf('///') === 0 && scheme === 'file:') { urlPrefix = '///'; } else if (path1.indexOf('//') === 0) { urlPrefix = '//'; } else if (path1.indexOf('/') === 0) { urlPrefix = '/'; } else { urlPrefix = ''; } var trailingSlash = path2.slice(-1) === '/' ? '/' : ''; var url1 = path1.split('/'); var url2 = path2.split('/'); var url3 = []; for (var i = 0, ii = url1.length; i < ii; ++i) { if (url1[i] === '..') { url3.pop(); } else if (url1[i] === '.' || url1[i] === '') { continue; } else { url3.push(url1[i]); } } for (var i = 0, ii = url2.length; i < ii; ++i) { if (url2[i] === '..') { url3.pop(); } else if (url2[i] === '.' || url2[i] === '') { continue; } else { url3.push(url2[i]); } } return scheme + urlPrefix + url3.join('/') + trailingSlash; } function buildQueryString(params) { var pairs = []; var keys = Object.keys(params || {}).sort(); var encode = encodeURIComponent; var encodeKey = function encodeKey(k) { return encode(k).replace('%24', '$'); }; for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; var value = params[key]; if (value === null || value === undefined) { continue; } if (Array.isArray(value)) { var arrayKey = encodeKey(key) + '[]'; for (var j = 0, l = value.length; j < l; j++) { pairs.push(arrayKey + '=' + encode(value[j])); } } else { pairs.push(encodeKey(key) + '=' + encode(value)); } } if (pairs.length === 0) { return ''; } return pairs.join('&'); } function parseQueryString(queryString) { var queryParams = {}; if (!queryString || typeof queryString !== 'string') { return queryParams; } var query = queryString; if (query.charAt(0) === '?') { query = query.substr(1); } var pairs = query.split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); var key = decodeURIComponent(pair[0]); var keyLength = key.length; var isArray = false; var value = undefined; if (!key) { continue; } else if (pair.length === 1) { value = true; } else { if (keyLength > 2 && key.slice(keyLength - 2) === '[]') { isArray = true; key = key.slice(0, keyLength - 2); if (!queryParams[key]) { queryParams[key] = []; } } value = pair[1] ? decodeURIComponent(pair[1]) : ''; } if (isArray) { queryParams[key].push(value); } else { queryParams[key] = value; } } return queryParams; } }); define('aurelia-pal',['exports'], function (exports) { exports.__esModule = true; exports.AggregateError = AggregateError; exports.initializePAL = initializePAL; function AggregateError(message, innerError, skipIfAlreadyAggregate) { if (innerError) { if (innerError.innerError && skipIfAlreadyAggregate) { return innerError; } if (innerError.stack) { message += '\n------------------------------------------------\ninner error: ' + innerError.stack; } } var e = new Error(message); if (innerError) { e.innerError = innerError; } return e; } var FEATURE = {}; exports.FEATURE = FEATURE; var PLATFORM = { noop: function noop() {}, eachModule: function eachModule() {} }; exports.PLATFORM = PLATFORM; PLATFORM.global = (function () { if (typeof self !== 'undefined') { return self; } if (typeof global !== 'undefined') { return global; } return new Function('return this')(); })(); var DOM = {}; exports.DOM = DOM; function initializePAL(callback) { if (typeof Object.getPropertyDescriptor !== 'function') { Object.getPropertyDescriptor = function (subject, name) { var pd = Object.getOwnPropertyDescriptor(subject, name); var proto = Object.getPrototypeOf(subject); while (typeof pd === 'undefined' && proto !== null) { pd = Object.getOwnPropertyDescriptor(proto, name); proto = Object.getPrototypeOf(proto); } return pd; }; } callback(PLATFORM, FEATURE, DOM); } }); define('aurelia-metadata',['exports', 'core-js', 'aurelia-pal'], function (exports, _coreJs, _aureliaPal) { exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.decorators = decorators; exports.deprecated = deprecated; exports.mixin = mixin; exports.protocol = protocol; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var theGlobal = _aureliaPal.PLATFORM.global; var emptyMetadata = Object.freeze({}); var metadataContainerKey = '__metadata__'; if (typeof theGlobal.Reflect === 'undefined') { theGlobal.Reflect = {}; } if (typeof theGlobal.Reflect.getOwnMetadata === 'undefined') { Reflect.getOwnMetadata = function (metadataKey, target, targetKey) { return ((target[metadataContainerKey] || emptyMetadata)[targetKey] || emptyMetadata)[metadataKey]; }; } if (typeof theGlobal.Reflect.defineMetadata === 'undefined') { Reflect.defineMetadata = function (metadataKey, metadataValue, target, targetKey) { var metadataContainer = target.hasOwnProperty(metadataContainerKey) ? target[metadataContainerKey] : target[metadataContainerKey] = {}; var targetContainer = metadataContainer[targetKey] || (metadataContainer[targetKey] = {}); targetContainer[metadataKey] = metadataValue; }; } if (typeof theGlobal.Reflect.metadata === 'undefined') { Reflect.metadata = function (metadataKey, metadataValue) { return function (target, targetKey) { Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey); }; }; } var metadata = { resource: 'aurelia:resource', paramTypes: 'design:paramtypes', properties: 'design:properties', get: function get(metadataKey, target, targetKey) { if (!target) { return undefined; } var result = metadata.getOwn(metadataKey, target, targetKey); return result === undefined ? metadata.get(metadataKey, Object.getPrototypeOf(target), targetKey) : result; }, getOwn: function getOwn(metadataKey, target, targetKey) { if (!target) { return undefined; } return Reflect.getOwnMetadata(metadataKey, target, targetKey); }, define: function define(metadataKey, metadataValue, target, targetKey) { Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey); }, getOrCreateOwn: function getOrCreateOwn(metadataKey, Type, target, targetKey) { var result = metadata.getOwn(metadataKey, target, targetKey); if (result === undefined) { result = new Type(); Reflect.defineMetadata(metadataKey, result, target, targetKey); } return result; } }; exports.metadata = metadata; var originStorage = new Map(); var unknownOrigin = Object.freeze({ moduleId: undefined, moduleMember: undefined }); var Origin = (function () { function Origin(moduleId, moduleMember) { _classCallCheck(this, Origin); this.moduleId = moduleId; this.moduleMember = moduleMember; } Origin.get = function get(fn) { var origin = originStorage.get(fn); if (origin === undefined) { _aureliaPal.PLATFORM.eachModule(function (key, value) { for (var _name in value) { var exp = value[_name]; if (exp === fn) { originStorage.set(fn, origin = new Origin(key, _name)); return true; } } if (value === fn) { originStorage.set(fn, origin = new Origin(key, 'default')); return true; } }); } return origin || unknownOrigin; }; Origin.set = function set(fn, origin) { originStorage.set(fn, origin); }; return Origin; })(); exports.Origin = Origin; function decorators() { for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) { rest[_key] = arguments[_key]; } var applicator = function applicator(target, key, descriptor) { var i = rest.length; if (key) { descriptor = descriptor || { value: target[key], writable: true, configurable: true, enumerable: true }; while (i--) { descriptor = rest[i](target, key, descriptor) || descriptor; } Object.defineProperty(target, key, descriptor); } else { while (i--) { target = rest[i](target) || target; } } return target; }; applicator.on = applicator; return applicator; } function deprecated(optionsOrTarget, maybeKey, maybeDescriptor) { function decorator(target, key, descriptor) { var methodSignature = target.constructor.name + '#' + key; var options = maybeKey ? {} : optionsOrTarget || {}; var message = 'DEPRECATION - ' + methodSignature; if (typeof descriptor.value !== 'function') { throw new SyntaxError('Only methods can be marked as deprecated.'); } if (options.message) { message += ' - ' + options.message; } return _extends({}, descriptor, { value: function deprecationWrapper() { if (options.error) { throw new Error(message); } else { console.warn(message); } return descriptor.value.apply(this, arguments); } }); } return maybeKey ? decorator(optionsOrTarget, maybeKey, maybeDescriptor) : decorator; } function mixin(behavior) { var instanceKeys = Object.keys(behavior); function _mixin(possible) { var decorator = function decorator(target) { var resolvedTarget = typeof target === 'function' ? target.prototype : target; for (var _iterator = instanceKeys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var property = _ref; Object.defineProperty(resolvedTarget, property, { value: behavior[property], writable: true }); } }; return possible ? decorator(possible) : decorator; } return _mixin; } function alwaysValid() { return true; } function noCompose() {} function ensureProtocolOptions(options) { if (options === undefined) { options = {}; } else if (typeof options === 'function') { options = { validate: options }; } if (!options.validate) { options.validate = alwaysValid; } if (!options.compose) { options.compose = noCompose; } return options; } function createProtocolValidator(validate) { return function (target) { var result = validate(target); return result === true; }; } function createProtocolAsserter(name, validate) { return function (target) { var result = validate(target); if (result !== true) { throw new Error(result || name + ' was not correctly implemented.'); } }; } function protocol(name, options) { options = ensureProtocolOptions(options); var result = function result(target) { var resolvedTarget = typeof target === 'function' ? target.prototype : target; options.compose(resolvedTarget); result.assert(resolvedTarget); Object.defineProperty(resolvedTarget, 'protocol:' + name, { enumerable: false, configurable: false, writable: false, value: true }); }; result.validate = createProtocolValidator(options.validate); result.assert = createProtocolAsserter(name, options.validate); return result; } protocol.create = function (name, options) { options = ensureProtocolOptions(options); var hidden = 'protocol:' + name; var result = function result(target) { var decorator = protocol(name, options); return target ? decorator(target) : decorator; }; result.decorates = function (obj) { return obj[hidden] === true; }; result.validate = createProtocolValidator(options.validate); result.assert = createProtocolAsserter(name, options.validate); return result; }; }); define('aurelia-loader',['exports', 'core-js', 'aurelia-path', 'aurelia-metadata'], function (exports, _coreJs, _aureliaPath, _aureliaMetadata) { exports.__esModule = true; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var TemplateDependency = function TemplateDependency(src, name) { _classCallCheck(this, TemplateDependency); this.src = src; this.name = name; }; exports.TemplateDependency = TemplateDependency; var TemplateRegistryEntry = (function () { function TemplateRegistryEntry(address) { _classCallCheck(this, TemplateRegistryEntry); this.templateIsLoaded = false; this.factoryIsReady = false; this.resources = null; this.dependencies = null; this.address = address; this.onReady = null; this._template = null; this._factory = null; } TemplateRegistryEntry.prototype.addDependency = function addDependency(src, name) { var finalSrc = typeof src === 'string' ? _aureliaPath.relativeToFile(src, this.address) : _aureliaMetadata.Origin.get(src).moduleId; this.dependencies.push(new TemplateDependency(finalSrc, name)); }; _createClass(TemplateRegistryEntry, [{ key: 'template', get: function get() { return this._template; }, set: function set(value) { var address = this.address; var requires = undefined; var current = undefined; var src = undefined; var dependencies = undefined; this._template = value; this.templateIsLoaded = true; requires = value.content.querySelectorAll('require'); dependencies = this.dependencies = new Array(requires.length); for (var i = 0, ii = requires.length; i < ii; ++i) { current = requires[i]; src = current.getAttribute('from'); if (!src) { throw new Error('<require> element in ' + address + ' has no "from" attribute.'); } dependencies[i] = new TemplateDependency(_aureliaPath.relativeToFile(src, address), current.getAttribute('as')); if (current.parentNode) { current.parentNode.removeChild(current); } } } }, { key: 'factory', get: function get() { return this._factory; }, set: function set(value) { this._factory = value; this.factoryIsReady = true; } }]); return TemplateRegistryEntry; })(); exports.TemplateRegistryEntry = TemplateRegistryEntry; var Loader = (function () { function Loader() { _classCallCheck(this, Loader); this.templateRegistry = {}; } Loader.prototype.map = function map(id, source) { throw new Error('Loaders must implement map(id, source).'); }; Loader.prototype.normalizeSync = function normalizeSync(moduleId, relativeTo) { throw new Error('Loaders must implement normalizeSync(moduleId, relativeTo).'); }; Loader.prototype.loadModule = function loadModule(id) { throw new Error('Loaders must implement loadModule(id).'); }; Loader.prototype.loadAllModules = function loadAllModules(ids) { throw new Error('Loader must implement loadAllModules(ids).'); }; Loader.prototype.loadTemplate = function loadTemplate(url) { throw new Error('Loader must implement loadTemplate(url).'); }; Loader.prototype.loadText = function loadText(url) { throw new Error('Loader must implement loadText(url).'); }; Loader.prototype.applyPluginToUrl = function applyPluginToUrl(url, pluginName) { throw new Error('Loader must implement applyPluginToUrl(url, pluginName).'); }; Loader.prototype.addPlugin = function addPlugin(pluginName, implementation) { throw new Error('Loader must implement addPlugin(pluginName, implementation).'); }; Loader.prototype.getOrCreateTemplateRegistryEntry = function getOrCreateTemplateRegistryEntry(address) { return this.templateRegistry[address] || (this.templateRegistry[address] = new TemplateRegistryEntry(address)); }; return Loader; })(); exports.Loader = Loader; }); define('aurelia-loader-default',['exports', 'aurelia-loader', 'aurelia-pal', 'aurelia-metadata'], function (exports, _aureliaLoader, _aureliaPal, _aureliaMetadata) { exports.__esModule = true; 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var TextTemplateLoader = (function () { function TextTemplateLoader() { _classCallCheck(this, TextTemplateLoader); } TextTemplateLoader.prototype.loadTemplate = function loadTemplate(loader, entry) { return loader.loadText(entry.address).then(function (text) { entry.template = _aureliaPal.DOM.createTemplateFromMarkup(text); }); }; return TextTemplateLoader; })(); exports.TextTemplateLoader = TextTemplateLoader; function ensureOriginOnExports(executed, name) { var target = executed; var key = undefined; var exportedValue = undefined; if (target.__useDefault) { target = target['default']; } _aureliaMetadata.Origin.set(target, new _aureliaMetadata.Origin(name, 'default')); for (key in target) { exportedValue = target[key]; if (typeof exportedValue === 'function') { _aureliaMetadata.Origin.set(exportedValue, new _aureliaMetadata.Origin(name, key)); } } return executed; } var DefaultLoader = (function (_Loader) { _inherits(DefaultLoader, _Loader); function DefaultLoader() { _classCallCheck(this, DefaultLoader); _Loader.call(this); this.textPluginName = 'text'; this.moduleRegistry = {}; this.useTemplateLoader(new TextTemplateLoader()); var that = this; this.addPlugin('template-registry-entry', { 'fetch': function fetch(address) { var entry = that.getOrCreateTemplateRegistryEntry(address); return entry.templateIsLoaded ? entry : that.templateLoader.loadTemplate(that, entry).then(function (x) { return entry; }); } }); } DefaultLoader.prototype.useTemplateLoader = function useTemplateLoader(templateLoader) { this.templateLoader = templateLoader; }; DefaultLoader.prototype.loadAllModules = function loadAllModules(ids) { var loads = []; for (var i = 0, ii = ids.length; i < ii; ++i) { loads.push(this.loadModule(ids[i])); } return Promise.all(loads); }; DefaultLoader.prototype.loadTemplate = function loadTemplate(url) { return this._import(this.applyPluginToUrl(url, 'template-registry-entry')); }; DefaultLoader.prototype.loadText = function loadText(url) { return this._import(this.applyPluginToUrl(url, this.textPluginName)); }; return DefaultLoader; })(_aureliaLoader.Loader); exports.DefaultLoader = DefaultLoader; _aureliaPal.PLATFORM.Loader = DefaultLoader; if (!_aureliaPal.PLATFORM.global.System || !_aureliaPal.PLATFORM.global.System['import']) { if (_aureliaPal.PLATFORM.global.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) { _aureliaPal.PLATFORM.eachModule = function (callback) { var defined = requirejs.s.contexts._.defined; for (var key in defined) { try { if (callback(key, defined[key])) return; } catch (e) {} } }; } else { _aureliaPal.PLATFORM.eachModule = function (callback) {}; } DefaultLoader.prototype._import = function (moduleId) { return new Promise(function (resolve, reject) { require([moduleId], resolve, reject); }); }; DefaultLoader.prototype.loadModule = function (id) { var _this = this; var existing = this.moduleRegistry[id]; if (existing) { return Promise.resolve(existing); } return new Promise(function (resolve, reject) { require([id], function (m) { _this.moduleRegistry[id] = m; resolve(ensureOriginOnExports(m, id)); }, reject); }); }; DefaultLoader.prototype.map = function (id, source) {}; DefaultLoader.prototype.normalizeSync = function (moduleId, relativeTo) { return moduleId; }; DefaultLoader.prototype.applyPluginToUrl = function (url, pluginName) { return pluginName + '!' + url; }; DefaultLoader.prototype.addPlugin = function (pluginName, implementation) { define(pluginName, [], { 'load': function load(name, req, onload) { var address = req.toUrl(name); var result = implementation.fetch(address); Promise.resolve(result).then(onload); } }); }; } else { _aureliaPal.PLATFORM.eachModule = function (callback) { var modules = System._loader.modules; for (var key in modules) { try { if (callback(key, modules[key].module)) return; } catch (e) {} } }; System.set('text', System.newModule({ 'translate': function translate(load) { return 'module.exports = "' + load.source.replace(/(["\\])/g, '\\$1').replace(/[\f]/g, '\\f').replace(/[\b]/g, '\\b').replace(/[\n]/g, '\\n').replace(/[\t]/g, '\\t').replace(/[\r]/g, '\\r').replace(/[\u2028]/g, '\\u2028').replace(/[\u2029]/g, '\\u2029') + '";'; } })); DefaultLoader.prototype._import = function (moduleId) { return System['import'](moduleId); }; DefaultLoader.prototype.loadModule = function (id) { var _this2 = this; var newId = System.normalizeSync(id); var existing = this.moduleRegistry[newId]; if (existing) { return Promise.resolve(existing); } return System['import'](newId).then(function (m) { _this2.moduleRegistry[newId] = m; return ensureOriginOnExports(m, newId); }); }; DefaultLoader.prototype.map = function (id, source) { System.map[id] = source; }; DefaultLoader.prototype.normalizeSync = function (moduleId, relativeTo) { return System.normalizeSync(moduleId, relativeTo); }; DefaultLoader.prototype.applyPluginToUrl = function (url, pluginName) { return url + '!' + pluginName; }; DefaultLoader.prototype.addPlugin = function (pluginName, implementation) { System.set(pluginName, System.newModule({ 'fetch': function fetch(load, _fetch) { var result = implementation.fetch(load.address); return Promise.resolve(result).then(function (x) { load.metadata.result = x; return ''; }); }, 'instantiate': function instantiate(load) { return load.metadata.result; } })); }; } }); define('aurelia-task-queue',['exports', 'aurelia-pal'], function (exports, _aureliaPal) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var hasSetImmediate = typeof setImmediate === 'function'; function makeRequestFlushFromMutationObserver(flush) { var toggle = 1; var observer = _aureliaPal.DOM.createMutationObserver(flush); var node = _aureliaPal.DOM.createTextNode(''); observer.observe(node, { characterData: true }); return function requestFlush() { toggle = -toggle; node.data = toggle; }; } function makeRequestFlushFromTimer(flush) { return function requestFlush() { var timeoutHandle = setTimeout(handleFlushTimer, 0); var intervalHandle = setInterval(handleFlushTimer, 50); function handleFlushTimer() { clearTimeout(timeoutHandle); clearInterval(intervalHandle); flush(); } }; } function onError(error, task) { if ('onError' in task) { task.onError(error); } else if (hasSetImmediate) { setImmediate(function () { throw error; }); } else { setTimeout(function () { throw error; }, 0); } } var TaskQueue = (function () { function TaskQueue() { var _this = this; _classCallCheck(this, TaskQueue); this.microTaskQueue = []; this.microTaskQueueCapacity = 1024; this.taskQueue = []; this.requestFlushMicroTaskQueue = makeRequestFlushFromMutationObserver(function () { return _this.flushMicroTaskQueue(); }); this.requestFlushTaskQueue = makeRequestFlushFromTimer(function () { return _this.flushTaskQueue(); }); } TaskQueue.prototype.queueMicroTask = function queueMicroTask(task) { if (this.microTaskQueue.length < 1) { this.requestFlushMicroTaskQueue(); } this.microTaskQueue.push(task); }; TaskQueue.prototype.queueTask = function queueTask(task) { if (this.taskQueue.length < 1) { this.requestFlushTaskQueue(); } this.taskQueue.push(task); }; TaskQueue.prototype.flushTaskQueue = function flushTaskQueue() { var queue = this.taskQueue; var index = 0; var task = undefined; this.taskQueue = []; try { while (index < queue.length) { task = queue[index]; task.call(); index++; } } catch (error) { onError(error, task); } }; TaskQueue.prototype.flushMicroTaskQueue = function flushMicroTaskQueue() { var queue = this.microTaskQueue; var capacity = this.microTaskQueueCapacity; var index = 0; var task = undefined; try { while (index < queue.length) { task = queue[index]; task.call(); index++; if (index > capacity) { for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } } catch (error) { onError(error, task); } queue.length = 0; }; return TaskQueue; })(); exports.TaskQueue = TaskQueue; }); define('aurelia-logging',['exports'], function (exports) { exports.__esModule = true; exports.getLogger = getLogger; exports.addAppender = addAppender; exports.setLevel = setLevel; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var logLevel = { none: 0, error: 1, warn: 2, info: 3, debug: 4 }; exports.logLevel = logLevel; var loggers = {}; var currentLevel = logLevel.none; var appenders = []; var slice = Array.prototype.slice; var loggerConstructionKey = {}; function log(logger, level, args) { var i = appenders.length; var current = undefined; args = slice.call(args); args.unshift(logger); while (i--) { current = appenders[i]; current[level].apply(current, args); } } function debug() { if (currentLevel < 4) { return; } log(this, 'debug', arguments); } function info() { if (currentLevel < 3) { return; } log(this, 'info', arguments); } function warn() { if (currentLevel < 2) { return; } log(this, 'warn', arguments); } function error() { if (currentLevel < 1) { return; } log(this, 'error', arguments); } function connectLogger(logger) { logger.debug = debug; logger.info = info; logger.warn = warn; logger.error = error; } function createLogger(id) { var logger = new Logger(id, loggerConstructionKey); if (appenders.length) { connectLogger(logger); } return logger; } function getLogger(id) { return loggers[id] || (loggers[id] = createLogger(id)); } function addAppender(appender) { appenders.push(appender); if (appenders.length === 1) { for (var key in loggers) { connectLogger(loggers[key]); } } } function setLevel(level) { currentLevel = level; } var Logger = (function () { function Logger(id, key) { _classCallCheck(this, Logger); if (key !== loggerConstructionKey) { throw new Error('You cannot instantiate "Logger". Use the "getLogger" API instead.'); } this.id = id; } Logger.prototype.debug = function debug(message) {}; Logger.prototype.info = function info(message) {}; Logger.prototype.warn = function warn(message) {}; Logger.prototype.error = function error(message) {}; return Logger; })(); exports.Logger = Logger; }); define('aurelia-logging-console',['exports', 'aurelia-pal', 'aurelia-logging'], function (exports, _aureliaPal, _aureliaLogging) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function (global) { global.console = global.console || {}; var con = global.console; var prop = undefined; var method = undefined; var empty = {}; var dummy = function dummy() {}; var properties = 'memory'.split(','); var methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' + 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(','); while (prop = properties.pop()) if (!con[prop]) con[prop] = empty; while (method = methods.pop()) if (!con[method]) con[method] = dummy; })(_aureliaPal.PLATFORM.global); if (_aureliaPal.PLATFORM.global.console && typeof console.log === 'object') { ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'].forEach(function (method) { console[method] = this.bind(console[method], console); }, Function.prototype.call); } var ConsoleAppender = (function () { function ConsoleAppender() { _classCallCheck(this, ConsoleAppender); } ConsoleAppender.prototype.debug = function debug(logger) { for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } console.debug.apply(console, ['DEBUG [' + logger.id + ']'].concat(rest)); }; ConsoleAppender.prototype.info = function info(logger) { for (var _len2 = arguments.length, rest = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { rest[_key2 - 1] = arguments[_key2]; } console.info.apply(console, ['INFO [' + logger.id + ']'].concat(rest)); }; ConsoleAppender.prototype.warn = function warn(logger) { for (var _len3 = arguments.length, rest = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { rest[_key3 - 1] = arguments[_key3]; } console.warn.apply(console, ['WARN [' + logger.id + ']'].concat(rest)); }; ConsoleAppender.prototype.error = function error(logger) { for (var _len4 = arguments.length, rest = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { rest[_key4 - 1] = arguments[_key4]; } console.error.apply(console, ['ERROR [' + logger.id + ']'].concat(rest)); }; return ConsoleAppender; })(); exports.ConsoleAppender = ConsoleAppender; }); define('aurelia-history',['exports'], function (exports) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var History = (function () { function History() { _classCallCheck(this, History); } History.prototype.activate = function activate(options) { throw new Error('History must implement activate().'); }; History.prototype.deactivate = function deactivate() { throw new Error('History must implement deactivate().'); }; History.prototype.navigate = function navigate(fragment, options) { throw new Error('History must implement navigate().'); }; History.prototype.navigateBack = function navigateBack() { throw new Error('History must implement navigateBack().'); }; History.prototype.setTitle = function setTitle(title) { throw new Error('History must implement setTitle().'); }; return History; })(); exports.History = History; }); define('aurelia-history-browser',['exports', 'core-js', 'aurelia-pal', 'aurelia-history'], function (exports, _coreJs, _aureliaPal, _aureliaHistory) { exports.__esModule = true; 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; }; })(); exports.configure = configure; 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var LinkHandler = (function () { function LinkHandler() { _classCallCheck(this, LinkHandler); } LinkHandler.prototype.activate = function activate(history) {}; LinkHandler.prototype.deactivate = function deactivate() {}; return LinkHandler; })(); exports.LinkHandler = LinkHandler; var DefaultLinkHandler = (function (_LinkHandler) { _inherits(DefaultLinkHandler, _LinkHandler); function DefaultLinkHandler() { var _this = this; _classCallCheck(this, DefaultLinkHandler); _LinkHandler.call(this); this.handler = function (e) { var _DefaultLinkHandler$getEventInfo = DefaultLinkHandler.getEventInfo(e); var shouldHandleEvent = _DefaultLinkHandler$getEventInfo.shouldHandleEvent; var href = _DefaultLinkHandler$getEventInfo.href; if (shouldHandleEvent) { e.preventDefault(); _this.history.navigate(href); } }; } DefaultLinkHandler.prototype.activate = function activate(history) { if (history._hasPushState) { this.history = history; _aureliaPal.DOM.addEventListener('click', this.handler, true); } }; DefaultLinkHandler.prototype.deactivate = function deactivate() { _aureliaPal.DOM.removeEventListener('click', this.handler); }; DefaultLinkHandler.getEventInfo = function getEventInfo(event) { var info = { shouldHandleEvent: false, href: null, anchor: null }; var target = DefaultLinkHandler.findClosestAnchor(event.target); if (!target || !DefaultLinkHandler.targetIsThisWindow(target)) { return info; } if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { return info; } var href = target.getAttribute('href'); info.anchor = target; info.href = href; var hasModifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey; var isRelative = href && !(href.charAt(0) === '#' || /^[a-z]+:/i.test(href)); info.shouldHandleEvent = !hasModifierKey && isRelative; return info; }; DefaultLinkHandler.findClosestAnchor = function findClosestAnchor(el) { while (el) { if (el.tagName === 'A') { return el; } el = el.parentNode; } }; DefaultLinkHandler.targetIsThisWindow = function targetIsThisWindow(target) { var targetWindow = target.getAttribute('target'); var win = _aureliaPal.PLATFORM.global; return !targetWindow || targetWindow === win.name || targetWindow === '_self' || targetWindow === 'top' && win === win.top; }; return DefaultLinkHandler; })(LinkHandler); exports.DefaultLinkHandler = DefaultLinkHandler; function configure(config) { config.singleton(_aureliaHistory.History, BrowserHistory); config.transient(LinkHandler, DefaultLinkHandler); } var BrowserHistory = (function (_History) { _inherits(BrowserHistory, _History); _createClass(BrowserHistory, null, [{ key: 'inject', value: [LinkHandler], enumerable: true }]); function BrowserHistory(linkHandler) { _classCallCheck(this, BrowserHistory); _History.call(this); this._isActive = false; this._checkUrlCallback = this._checkUrl.bind(this); this.location = _aureliaPal.PLATFORM.location; this.history = _aureliaPal.PLATFORM.history; this.linkHandler = linkHandler; } BrowserHistory.prototype.activate = function activate(options) { if (this._isActive) { throw new Error('History has already been activated.'); } var wantsPushState = !!options.pushState; this._isActive = true; this.options = Object.assign({}, { root: '/' }, this.options, options); this.root = ('/' + this.options.root + '/').replace(rootStripper, '/'); this._wantsHashChange = this.options.hashChange !== false; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); var eventName = undefined; if (this._hasPushState) { eventName = 'popstate'; } else if (this._wantsHashChange) { eventName = 'hashchange'; } _aureliaPal.PLATFORM.addEventListener(eventName, this._checkUrlCallback); if (this._wantsHashChange && wantsPushState) { var loc = this.location; var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root; if (!this._hasPushState && !atRoot) { this.fragment = this._getFragment(null, true); this.location.replace(this.root + this.location.search + '#' + this.fragment); return true; } else if (this._hasPushState && atRoot && loc.hash) { this.fragment = this._getHash().replace(routeStripper, ''); this.history.replaceState({}, _aureliaPal.DOM.title, this.root + this.fragment + loc.search); } } if (!this.fragment) { this.fragment = this._getFragment(); } this.linkHandler.activate(this); if (!this.options.silent) { return this._loadUrl(); } }; BrowserHistory.prototype.deactivate = function deactivate() { _aureliaPal.PLATFORM.removeEventListener('popstate', this._checkUrlCallback); _aureliaPal.PLATFORM.removeEventListener('hashchange', this._checkUrlCallback); this._isActive = false; this.linkHandler.deactivate(); }; BrowserHistory.prototype.navigate = function navigate(fragment) { var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _ref$trigger = _ref.trigger; var trigger = _ref$trigger === undefined ? true : _ref$trigger; var _ref$replace = _ref.replace; var replace = _ref$replace === undefined ? false : _ref$replace; if (fragment && absoluteUrl.test(fragment)) { this.location.href = fragment; return true; } if (!this._isActive) { return false; } fragment = this._getFragment(fragment || ''); if (this.fragment === fragment && !replace) { return false; } this.fragment = fragment; var url = this.root + fragment; if (fragment === '' && url !== '/') { url = url.slice(0, -1); } if (this._hasPushState) { url = url.replace('//', '/'); this.history[replace ? 'replaceState' : 'pushState']({}, _aureliaPal.DOM.title, url); } else if (this._wantsHashChange) { updateHash(this.location, fragment, replace); } else { return this.location.assign(url); } if (trigger) { return this._loadUrl(fragment); } }; BrowserHistory.prototype.navigateBack = function navigateBack() { this.history.back(); }; BrowserHistory.prototype.setTitle = function setTitle(title) { _aureliaPal.DOM.title = title; }; BrowserHistory.prototype._getHash = function _getHash() { return this.location.hash.substr(1); }; BrowserHistory.prototype._getFragment = function _getFragment(fragment, forcePushState) { var root = undefined; if (!fragment) { if (this._hasPushState || !this._wantsHashChange || forcePushState) { fragment = this.location.pathname + this.location.search; root = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(root)) { fragment = fragment.substr(root.length); } } else { fragment = this._getHash(); } } return '/' + fragment.replace(routeStripper, ''); }; BrowserHistory.prototype._checkUrl = function _checkUrl() { var current = this._getFragment(); if (current !== this.fragment) { this._loadUrl(); } }; BrowserHistory.prototype._loadUrl = function _loadUrl(fragmentOverride) { var fragment = this.fragment = this._getFragment(fragmentOverride); return this.options.routeHandler ? this.options.routeHandler(fragment) : false; }; return BrowserHistory; })(_aureliaHistory.History); exports.BrowserHistory = BrowserHistory; var routeStripper = /^#?\/*|\s+$/g; var rootStripper = /^\/+|\/+$/g; var trailingSlash = /\/$/; var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; function updateHash(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { location.hash = '#' + fragment; } } }); define('aurelia-event-aggregator',['exports', 'aurelia-logging'], function (exports, _aureliaLogging) { exports.__esModule = true; exports.includeEventsIn = includeEventsIn; exports.configure = configure; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var logger = _aureliaLogging.getLogger('event-aggregator'); var Handler = (function () { function Handler(messageType, callback) { _classCallCheck(this, Handler); this.messageType = messageType; this.callback = callback; } Handler.prototype.handle = function handle(message) { if (message instanceof this.messageType) { this.callback.call(null, message); } }; return Handler; })(); var EventAggregator = (function () { function EventAggregator() { _classCallCheck(this, EventAggregator); this.eventLookup = {}; this.messageHandlers = []; } EventAggregator.prototype.publish = function publish(event, data) { var subscribers = undefined; var i = undefined; if (typeof event === 'string') { subscribers = this.eventLookup[event]; if (subscribers) { subscribers = subscribers.slice(); i = subscribers.length; try { while (i--) { subscribers[i](data, event); } } catch (e) { logger.error(e); } } } else { subscribers = this.messageHandlers.slice(); i = subscribers.length; try { while (i--) { subscribers[i].handle(event); } } catch (e) { logger.error(e); } } }; EventAggregator.prototype.subscribe = function subscribe(event, callback) { var handler = undefined; var subscribers = undefined; if (typeof event === 'string') { handler = callback; subscribers = this.eventLookup[event] || (this.eventLookup[event] = []); } else { handler = new Handler(event, callback); subscribers = this.messageHandlers; } subscribers.push(handler); return { dispose: function dispose() { var idx = subscribers.indexOf(handler); if (idx !== -1) { subscribers.splice(idx, 1); } } }; }; EventAggregator.prototype.subscribeOnce = function subscribeOnce(event, callback) { var sub = this.subscribe(event, function (a, b) { sub.dispose(); return callback(a, b); }); return sub; }; return EventAggregator; })(); exports.EventAggregator = EventAggregator; function includeEventsIn(obj) { var ea = new EventAggregator(); obj.subscribeOnce = function (event, callback) { return ea.subscribeOnce(event, callback); }; obj.subscribe = function (event, callback) { return ea.subscribe(event, callback); }; obj.publish = function (event, data) { ea.publish(event, data); }; return ea; } function configure(config) { config.instance(EventAggregator, includeEventsIn(config.aurelia)); } }); define('aurelia-binding',['exports', 'core-js', 'aurelia-pal', 'aurelia-task-queue', 'aurelia-metadata'], function (exports, _coreJs, _aureliaPal, _aureliaTaskQueue, _aureliaMetadata) { exports.__esModule = true; 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; }; })(); exports.camelCase = camelCase; exports.createOverrideContext = createOverrideContext; exports.getContextFor = getContextFor; exports.createScopeForTest = createScopeForTest; exports.connectable = connectable; exports.subscriberCollection = subscriberCollection; exports.calcSplices = calcSplices; exports.projectArraySplices = projectArraySplices; exports.getChangeRecords = getChangeRecords; exports.getArrayObserver = _getArrayObserver; exports.getMapObserver = _getMapObserver; exports.hasDeclaredDependencies = hasDeclaredDependencies; exports.declarePropertyDependencies = declarePropertyDependencies; exports.computedFrom = computedFrom; exports.valueConverter = valueConverter; exports.bindingBehavior = bindingBehavior; 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function camelCase(name) { return name.charAt(0).toLowerCase() + name.slice(1); } function createOverrideContext(bindingContext, parentOverrideContext) { return { bindingContext: bindingContext, parentOverrideContext: parentOverrideContext || null }; } function getContextFor(name, scope, ancestor) { var oc = scope.overrideContext; if (ancestor) { while (ancestor && oc) { ancestor--; oc = oc.parentOverrideContext; } if (ancestor || !oc) { return undefined; } return name in oc ? oc : oc.bindingContext; } while (oc && !(name in oc) && !(oc.bindingContext && name in oc.bindingContext)) { oc = oc.parentOverrideContext; } if (oc) { return name in oc ? oc : oc.bindingContext; } return scope.bindingContext || scope.overrideContext; } function createScopeForTest(bindingContext, parentBindingContext) { if (parentBindingContext) { return { bindingContext: bindingContext, overrideContext: createOverrideContext(bindingContext, createOverrideContext(parentBindingContext)) }; } return { bindingContext: bindingContext, overrideContext: createOverrideContext(bindingContext) }; } var sourceContext = 'Binding:source'; exports.sourceContext = sourceContext; var slotNames = []; var versionSlotNames = []; for (var i = 0; i < 100; i++) { slotNames.push('_observer' + i); versionSlotNames.push('_observerVersion' + i); } function addObserver(observer) { var observerSlots = this._observerSlots === undefined ? 0 : this._observerSlots; var i = observerSlots; while (i-- && this[slotNames[i]] !== observer) {} if (i === -1) { i = 0; while (this[slotNames[i]]) { i++; } this[slotNames[i]] = observer; observer.subscribe(sourceContext, this); if (i === observerSlots) { this._observerSlots = i + 1; } } if (this._version === undefined) { this._version = 0; } this[versionSlotNames[i]] = this._version; } function observeProperty(obj, propertyName) { var observer = this.observerLocator.getObserver(obj, propertyName); addObserver.call(this, observer); } function observeArray(array) { var observer = this.observerLocator.getArrayObserver(array); addObserver.call(this, observer); } function unobserve(all) { var i = this._observerSlots; while (i--) { if (all || this[versionSlotNames[i]] !== this._version) { var observer = this[slotNames[i]]; this[slotNames[i]] = null; if (observer) { observer.unsubscribe(sourceContext, this); } } } } function connectable() { return function (target) { target.prototype.observeProperty = observeProperty; target.prototype.observeArray = observeArray; target.prototype.unobserve = unobserve; }; } function addSubscriber(context, callable) { if (this.hasSubscriber(context, callable)) { return false; } if (!this._context0) { this._context0 = context; this._callable0 = callable; return true; } if (!this._context1) { this._context1 = context; this._callable1 = callable; return true; } if (!this._context2) { this._context2 = context; this._callable2 = callable; return true; } if (!this._contextsRest) { this._contextsRest = [context]; this._callablesRest = [callable]; return true; } this._contextsRest.push(context); this._callablesRest.push(callable); return true; } function removeSubscriber(context, callable) { if (this._context0 === context && this._callable0 === callable) { this._context0 = null; this._callable0 = null; return true; } if (this._context1 === context && this._callable1 === callable) { this._context1 = null; this._callable1 = null; return true; } if (this._context2 === context && this._callable2 === callable) { this._context2 = null; this._callable2 = null; return true; } var rest = this._contextsRest; var index = undefined; if (!rest || !rest.length || (index = rest.indexOf(context)) === -1 || this._callablesRest[index] !== callable) { return false; } rest.splice(index, 1); this._callablesRest.splice(index, 1); return true; } var tempContextsRest = [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]; var tempCallablesRest = [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]; function callSubscribers(newValue, oldValue) { var context0 = this._context0; var callable0 = this._callable0; var context1 = this._context1; var callable1 = this._callable1; var context2 = this._context2; var callable2 = this._callable2; var length = !this._contextsRest ? 0 : this._contextsRest.length; var i = length; if (length) { while (i--) { tempContextsRest[i] = this._contextsRest[i]; tempCallablesRest[i] = this._callablesRest[i]; } } if (context0) { if (callable0) { callable0.call(context0, newValue, oldValue); } else { context0(newValue, oldValue); } } if (context1) { if (callable1) { callable1.call(context1, newValue, oldValue); } else { context1(newValue, oldValue); } } if (context2) { if (callable2) { callable2.call(context2, newValue, oldValue); } else { context2(newValue, oldValue); } } for (i = 0; i < length; i++) { var callable = tempCallablesRest[i]; var context = tempContextsRest[i]; if (callable) { callable.call(context, newValue, oldValue); } else { context(newValue, oldValue); } tempContextsRest[i] = null; tempCallablesRest[i] = null; } } function hasSubscribers() { return !!(this._context0 || this._context1 || this._context2 || this._contextsRest && this._contextsRest.length); } function hasSubscriber(context, callable) { var has = this._context0 === context && this._callable0 === callable || this._context1 === context && this._callable1 === callable || this._context2 === context && this._callable2 === callable; if (has) { return true; } var index = undefined; var contexts = this._contextsRest; if (!contexts || (index = contexts.length) === 0) { return false; } var callables = this._callablesRest; while (index--) { if (contexts[index] === context && callables[index] === callable) { return true; } } return false; } function subscriberCollection() { return function (target) { target.prototype.addSubscriber = addSubscriber; target.prototype.removeSubscriber = removeSubscriber; target.prototype.callSubscribers = callSubscribers; target.prototype.hasSubscribers = hasSubscribers; target.prototype.hasSubscriber = hasSubscriber; }; } function isIndex(s) { return +s === s >>> 0; } function toNumber(s) { return +s; } function newSplice(index, removed, addedCount) { return { index: index, removed: removed, addedCount: addedCount }; } var EDIT_LEAVE = 0; var EDIT_UPDATE = 1; var EDIT_ADD = 2; var EDIT_DELETE = 3; function ArraySplice() {} ArraySplice.prototype = { calcEditDistances: function calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd) { var rowCount = oldEnd - oldStart + 1; var columnCount = currentEnd - currentStart + 1; var distances = new Array(rowCount); var i, j, north, west; for (i = 0; i < rowCount; ++i) { distances[i] = new Array(columnCount); distances[i][0] = i; } for (j = 0; j < columnCount; ++j) { distances[0][j] = j; } for (i = 1; i < rowCount; ++i) { for (j = 1; j < columnCount; ++j) { if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) distances[i][j] = distances[i - 1][j - 1];else { north = distances[i - 1][j] + 1; west = distances[i][j - 1] + 1; distances[i][j] = north < west ? north : west; } } } return distances; }, spliceOperationsFromEditDistances: function spliceOperationsFromEditDistances(distances) { var i = distances.length - 1; var j = distances[0].length - 1; var current = distances[i][j]; var edits = []; while (i > 0 || j > 0) { if (i == 0) { edits.push(EDIT_ADD); j--; continue; } if (j == 0) { edits.push(EDIT_DELETE); i--; continue; } var northWest = distances[i - 1][j - 1]; var west = distances[i - 1][j]; var north = distances[i][j - 1]; var min; if (west < north) min = west < northWest ? west : northWest;else min = north < northWest ? north : northWest; if (min == northWest) { if (northWest == current) { edits.push(EDIT_LEAVE); } else { edits.push(EDIT_UPDATE); current = northWest; } i--; j--; } else if (min == west) { edits.push(EDIT_DELETE); i--; current = west; } else { edits.push(EDIT_ADD); j--; current = north; } } edits.reverse(); return edits; }, calcSplices: function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { var prefixCount = 0; var suffixCount = 0; var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); if (currentStart == 0 && oldStart == 0) prefixCount = this.sharedPrefix(current, old, minLength); if (currentEnd == current.length && oldEnd == old.length) suffixCount = this.sharedSuffix(current, old, minLength - prefixCount); currentStart += prefixCount; oldStart += prefixCount; currentEnd -= suffixCount; oldEnd -= suffixCount; if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return []; if (currentStart == currentEnd) { var splice = newSplice(currentStart, [], 0); while (oldStart < oldEnd) splice.removed.push(old[oldStart++]); return [splice]; } else if (oldStart == oldEnd) return [newSplice(currentStart, [], currentEnd - currentStart)]; var ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); var splice = undefined; var splices = []; var index = currentStart; var oldIndex = oldStart; for (var i = 0; i < ops.length; ++i) { switch (ops[i]) { case EDIT_LEAVE: if (splice) { splices.push(splice); splice = undefined; } index++; oldIndex++; break; case EDIT_UPDATE: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; splice.removed.push(old[oldIndex]); oldIndex++; break; case EDIT_ADD: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; break; case EDIT_DELETE: if (!splice) splice = newSplice(index, [], 0); splice.removed.push(old[oldIndex]); oldIndex++; break; } } if (splice) { splices.push(splice); } return splices; }, sharedPrefix: function sharedPrefix(current, old, searchLength) { for (var i = 0; i < searchLength; ++i) if (!this.equals(current[i], old[i])) return i; return searchLength; }, sharedSuffix: function sharedSuffix(current, old, searchLength) { var index1 = current.length; var index2 = old.length; var count = 0; while (count < searchLength && this.equals(current[--index1], old[--index2])) count++; return count; }, calculateSplices: function calculateSplices(current, previous) { return this.calcSplices(current, 0, current.length, previous, 0, previous.length); }, equals: function equals(currentValue, previousValue) { return currentValue === previousValue; } }; var arraySplice = new ArraySplice(); function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { return arraySplice.calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd); } function intersect(start1, end1, start2, end2) { if (end1 < start2 || end2 < start1) return -1; if (end1 == start2 || end2 == start1) return 0; if (start1 < start2) { if (end1 < end2) return end1 - start2;else return end2 - start2; } else { if (end2 < end1) return end2 - start1;else return end1 - start1; } } function mergeSplice(splices, index, removed, addedCount) { var splice = newSplice(index, removed, addedCount); var inserted = false; var insertionOffset = 0; for (var i = 0; i < splices.length; i++) { var current = splices[i]; current.index += insertionOffset; if (inserted) continue; var intersectCount = intersect(splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount); if (intersectCount >= 0) { splices.splice(i, 1); i--; insertionOffset -= current.addedCount - current.removed.length; splice.addedCount += current.addedCount - intersectCount; var deleteCount = splice.removed.length + current.removed.length - intersectCount; if (!splice.addedCount && !deleteCount) { inserted = true; } else { var removed = current.removed; if (splice.index < current.index) { var prepend = splice.removed.slice(0, current.index - splice.index); Array.prototype.push.apply(prepend, removed); removed = prepend; } if (splice.index + splice.removed.length > current.index + current.addedCount) { var append = splice.removed.slice(current.index + current.addedCount - splice.index); Array.prototype.push.apply(removed, append); } splice.removed = removed; if (current.index < splice.index) { splice.index = current.index; } } } else if (splice.index < current.index) { inserted = true; splices.splice(i, 0, splice); i++; var offset = splice.addedCount - splice.removed.length; current.index += offset; insertionOffset += offset; } } if (!inserted) splices.push(splice); } function createInitialSplices(array, changeRecords) { var splices = []; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; switch (record.type) { case 'splice': mergeSplice(splices, record.index, record.removed.slice(), record.addedCount); break; case 'add': case 'update': case 'delete': if (!isIndex(record.name)) continue; var index = toNumber(record.name); if (index < 0) continue; mergeSplice(splices, index, [record.oldValue], record.type === 'delete' ? 0 : 1); break; default: console.error('Unexpected record type: ' + JSON.stringify(record)); break; } } return splices; } function projectArraySplices(array, changeRecords) { var splices = []; createInitialSplices(array, changeRecords).forEach(function (splice) { if (splice.addedCount == 1 && splice.removed.length == 1) { if (splice.removed[0] !== array[splice.index]) splices.push(splice); return; }; splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length)); }); return splices; } function newRecord(type, object, key, oldValue) { return { type: type, object: object, key: key, oldValue: oldValue }; } function getChangeRecords(map) { var entries = []; for (var _iterator = map.keys(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var key = _ref; entries.push(newRecord('added', map, key)); } return entries; } var ModifyCollectionObserver = (function () { function ModifyCollectionObserver(taskQueue, collection) { _classCallCheck(this, _ModifyCollectionObserver); this.taskQueue = taskQueue; this.queued = false; this.changeRecords = null; this.oldCollection = null; this.collection = collection; this.lengthPropertyName = collection instanceof Map ? 'size' : 'length'; } ModifyCollectionObserver.prototype.subscribe = function subscribe(context, callable) { this.addSubscriber(context, callable); }; ModifyCollectionObserver.prototype.unsubscribe = function unsubscribe(context, callable) { this.removeSubscriber(context, callable); }; ModifyCollectionObserver.prototype.addChangeRecord = function addChangeRecord(changeRecord) { if (!this.hasSubscribers() && !this.lengthObserver) { return; } if (changeRecord.type === 'splice') { var index = changeRecord.index; var arrayLength = changeRecord.object.length; if (index > arrayLength) { index = arrayLength - changeRecord.addedCount; } else if (index < 0) { index = arrayLength + changeRecord.removed.length + index - changeRecord.addedCount; } if (index < 0) { index = 0; } changeRecord.index = index; } if (this.changeRecords === null) { this.changeRecords = [changeRecord]; } else { this.changeRecords.push(changeRecord); } if (!this.queued) { this.queued = true; this.taskQueue.queueMicroTask(this); } }; ModifyCollectionObserver.prototype.reset = function reset(oldCollection) { this.oldCollection = oldCollection; if (this.hasSubscribers() && !this.queued) { this.queued = true; this.taskQueue.queueMicroTask(this); } }; ModifyCollectionObserver.prototype.getLengthObserver = function getLengthObserver() { return this.lengthObserver || (this.lengthObserver = new CollectionLengthObserver(this.collection)); }; ModifyCollectionObserver.prototype.call = function call() { var changeRecords = this.changeRecords; var oldCollection = this.oldCollection; var records = undefined; this.queued = false; this.changeRecords = []; this.oldCollection = null; if (this.hasSubscribers()) { if (oldCollection) { if (this.collection instanceof Map) { records = getChangeRecords(oldCollection); } else { records = calcSplices(this.collection, 0, this.collection.length, oldCollection, 0, oldCollection.length); } } else { if (this.collection instanceof Map) { records = changeRecords; } else { records = projectArraySplices(this.collection, changeRecords); } } this.callSubscribers(records); } if (this.lengthObserver) { this.lengthObserver.call(this.collection[this.lengthPropertyName]); } }; var _ModifyCollectionObserver = ModifyCollectionObserver; ModifyCollectionObserver = subscriberCollection()(ModifyCollectionObserver) || ModifyCollectionObserver; return ModifyCollectionObserver; })(); exports.ModifyCollectionObserver = ModifyCollectionObserver; var CollectionLengthObserver = (function () { function CollectionLengthObserver(collection) { _classCallCheck(this, _CollectionLengthObserver); this.collection = collection; this.lengthPropertyName = collection instanceof Map ? 'size' : 'length'; this.currentValue = collection[this.lengthPropertyName]; } CollectionLengthObserver.prototype.getValue = function getValue() { return this.collection[this.lengthPropertyName]; }; CollectionLengthObserver.prototype.setValue = function setValue(newValue) { this.collection[this.lengthPropertyName] = newValue; }; CollectionLengthObserver.prototype.subscribe = function subscribe(context, callable) { this.addSubscriber(context, callable); }; CollectionLengthObserver.prototype.unsubscribe = function unsubscribe(context, callable) { this.removeSubscriber(context, callable); }; CollectionLengthObserver.prototype.call = function call(newValue) { var oldValue = this.currentValue; this.callSubscribers(newValue, oldValue); this.currentValue = newValue; }; var _CollectionLengthObserver = CollectionLengthObserver; CollectionLengthObserver = subscriberCollection()(CollectionLengthObserver) || CollectionLengthObserver; return CollectionLengthObserver; })(); exports.CollectionLengthObserver = CollectionLengthObserver; var arrayProto = Array.prototype; function _getArrayObserver(taskQueue, array) { return ModifyArrayObserver.create(taskQueue, array); } var ModifyArrayObserver = (function (_ModifyCollectionObserver2) { _inherits(ModifyArrayObserver, _ModifyCollectionObserver2); function ModifyArrayObserver(taskQueue, array) { _classCallCheck(this, ModifyArrayObserver); _ModifyCollectionObserver2.call(this, taskQueue, array); } ModifyArrayObserver.create = function create(taskQueue, array) { var observer = new ModifyArrayObserver(taskQueue, array); array['pop'] = function () { var methodCallResult = arrayProto['pop'].apply(array, arguments); observer.addChangeRecord({ type: 'delete', object: array, name: array.length, oldValue: methodCallResult }); return methodCallResult; }; array['push'] = function () { var methodCallResult = arrayProto['push'].apply(array, arguments); observer.addChangeRecord({ type: 'splice', object: array, index: array.length - arguments.length, removed: [], addedCount: arguments.length }); return methodCallResult; }; array['reverse'] = function () { var oldArray = array.slice(); var methodCallResult = arrayProto['reverse'].apply(array, arguments); observer.reset(oldArray); return methodCallResult; }; array['shift'] = function () { var methodCallResult = arrayProto['shift'].apply(array, arguments); observer.addChangeRecord({ type: 'delete', object: array, name: 0, oldValue: methodCallResult }); return methodCallResult; }; array['sort'] = function () { var oldArray = array.slice(); var methodCallResult = arrayProto['sort'].apply(array, arguments); observer.reset(oldArray); return methodCallResult; }; array['splice'] = function () { var methodCallResult = arrayProto['splice'].apply(array, arguments); observer.addChangeRecord({ type: 'splice', object: array, index: arguments[0], removed: methodCallResult, addedCount: arguments.length > 2 ? arguments.length - 2 : 0 }); return methodCallResult; }; array['unshift'] = function () { var methodCallResult = arrayProto['unshift'].apply(array, arguments); observer.addChangeRecord({ type: 'splice', object: array, index: 0, removed: [], addedCount: arguments.length }); return methodCallResult; }; return observer; }; return ModifyArrayObserver; })(ModifyCollectionObserver); var Expression = (function () { function Expression() { _classCallCheck(this, Expression); this.isChain = false; this.isAssignable = false; } Expression.prototype.evaluate = function evaluate(scope, lookupFunctions, args) { throw new Error('Binding expression "' + this + '" cannot be evaluated.'); }; Expression.prototype.assign = function assign(scope, value, lookupFunctions) { throw new Error('Binding expression "' + this + '" cannot be assigned to.'); }; Expression.prototype.toString = function toString() { return Unparser.unparse(this); }; return Expression; })(); exports.Expression = Expression; var Chain = (function (_Expression) { _inherits(Chain, _Expression); function Chain(expressions) { _classCallCheck(this, Chain); _Expression.call(this); this.expressions = expressions; this.isChain = true; } Chain.prototype.evaluate = function evaluate(scope, lookupFunctions) { var result, expressions = this.expressions, length = expressions.length, i, last; for (i = 0; i < length; ++i) { last = expressions[i].evaluate(scope, lookupFunctions); if (last !== null) { result = last; } } return result; }; Chain.prototype.accept = function accept(visitor) { visitor.visitChain(this); }; return Chain; })(Expression); exports.Chain = Chain; var BindingBehavior = (function (_Expression2) { _inherits(BindingBehavior, _Expression2); function BindingBehavior(expression, name, args) { _classCallCheck(this, BindingBehavior); _Expression2.call(this); this.expression = expression; this.name = name; this.args = args; } BindingBehavior.prototype.evaluate = function evaluate(scope, lookupFunctions) { return this.expression.evaluate(scope, lookupFunctions); }; BindingBehavior.prototype.assign = function assign(scope, value, lookupFunctions) { return this.expression.assign(scope, value, lookupFunctions); }; BindingBehavior.prototype.accept = function accept(visitor) { visitor.visitBindingBehavior(this); }; BindingBehavior.prototype.connect = function connect(binding, scope) { this.expression.connect(binding, scope); }; BindingBehavior.prototype.bind = function bind(binding, scope, lookupFunctions) { if (this.expression.expression && this.expression.bind) { this.expression.bind(binding, scope, lookupFunctions); } var behavior = lookupFunctions.bindingBehaviors(this.name); if (!behavior) { throw new Error('No BindingBehavior named "' + this.name + '" was found!'); } var behaviorKey = 'behavior-' + this.name; if (binding[behaviorKey]) { throw new Error('A binding behavior named "' + this.name + '" has already been applied to "' + this.expression + '"'); } binding[behaviorKey] = behavior; behavior.bind.apply(behavior, [binding, scope].concat(evalList(scope, this.args, binding.lookupFunctions))); }; BindingBehavior.prototype.unbind = function unbind(binding, scope) { var behaviorKey = 'behavior-' + this.name; binding[behaviorKey].unbind(binding, scope); binding[behaviorKey] = null; if (this.expression.expression && this.expression.unbind) { this.expression.unbind(binding, scope); } }; return BindingBehavior; })(Expression); exports.BindingBehavior = BindingBehavior; var ValueConverter = (function (_Expression3) { _inherits(ValueConverter, _Expression3); function ValueConverter(expression, name, args, allArgs) { _classCallCheck(this, ValueConverter); _Expression3.call(this); this.expression = expression; this.name = name; this.args = args; this.allArgs = allArgs; } ValueConverter.prototype.evaluate = function evaluate(scope, lookupFunctions) { var converter = lookupFunctions.valueConverters(this.name); if (!converter) { throw new Error('No ValueConverter named "' + this.name + '" was found!'); } if ('toView' in converter) { return converter.toView.apply(converter, evalList(scope, this.allArgs, lookupFunctions)); } return this.allArgs[0].evaluate(scope, lookupFunctions); }; ValueConverter.prototype.assign = function assign(scope, value, lookupFunctions) { var converter = lookupFunctions.valueConverters(this.name); if (!converter) { throw new Error('No ValueConverter named "' + this.name + '" was found!'); } if ('fromView' in converter) { value = converter.fromView.apply(converter, [value].concat(evalList(scope, this.args, lookupFunctions))); } return this.allArgs[0].assign(scope, value, lookupFunctions); }; ValueConverter.prototype.accept = function accept(visitor) { visitor.visitValueConverter(this); }; ValueConverter.prototype.connect = function connect(binding, scope) { var expressions = this.allArgs; var i = expressions.length; while (i--) { expressions[i].connect(binding, scope); } }; return ValueConverter; })(Expression); exports.ValueConverter = ValueConverter; var Assign = (function (_Expression4) { _inherits(Assign, _Expression4); function Assign(target, value) { _classCallCheck(this, Assign); _Expression4.call(this); this.target = target; this.value = value; } Assign.prototype.evaluate = function evaluate(scope, lookupFunctions) { return this.target.assign(scope, this.value.evaluate(scope, lookupFunctions)); }; Assign.prototype.accept = function accept(vistor) { vistor.visitAssign(this); }; Assign.prototype.connect = function connect(binding, scope) {}; return Assign; })(Expression); exports.Assign = Assign; var Conditional = (function (_Expression5) { _inherits(Conditional, _Expression5); function Conditional(condition, yes, no) { _classCallCheck(this, Conditional); _Expression5.call(this); this.condition = condition; this.yes = yes; this.no = no; } Conditional.prototype.evaluate = function evaluate(scope, lookupFunctions) { return !!this.condition.evaluate(scope) ? this.yes.evaluate(scope) : this.no.evaluate(scope); }; Conditional.prototype.accept = function accept(visitor) { visitor.visitConditional(this); }; Conditional.prototype.connect = function connect(binding, scope) { this.condition.connect(binding, scope); if (this.condition.evaluate(scope)) { this.yes.connect(binding, scope); } else { this.no.connect(binding, scope); } }; return Conditional; })(Expression); exports.Conditional = Conditional; var AccessThis = (function (_Expression6) { _inherits(AccessThis, _Expression6); function AccessThis(ancestor) { _classCallCheck(this, AccessThis); _Expression6.call(this); this.ancestor = ancestor; } AccessThis.prototype.evaluate = function evaluate(scope, lookupFunctions) { var oc = scope.overrideContext; var i = this.ancestor; while (i-- && oc) { oc = oc.parentOverrideContext; } return i < 1 && oc ? oc.bindingContext : undefined; }; AccessThis.prototype.accept = function accept(visitor) { visitor.visitAccessThis(this); }; AccessThis.prototype.connect = function connect(binding, scope) {}; return AccessThis; })(Expression); exports.AccessThis = AccessThis; var AccessScope = (function (_Expression7) { _inherits(AccessScope, _Expression7); function AccessScope(name, ancestor) { _classCallCheck(this, AccessScope); _Expression7.call(this); this.name = name; this.ancestor = ancestor; this.isAssignable = true; } AccessScope.prototype.evaluate = function evaluate(scope, lookupFunctions) { var context = getContextFor(this.name, scope, this.ancestor); return context[this.name]; }; AccessScope.prototype.assign = function assign(scope, value) { var context = getContextFor(this.name, scope, this.ancestor); return context[this.name] = value; }; AccessScope.prototype.accept = function accept(visitor) { visitor.visitAccessScope(this); }; AccessScope.prototype.connect = function connect(binding, scope) { var context = getContextFor(this.name, scope, this.ancestor); binding.observeProperty(context, this.name); }; return AccessScope; })(Expression); exports.AccessScope = AccessScope; var AccessMember = (function (_Expression8) { _inherits(AccessMember, _Expression8); function AccessMember(object, name) { _classCallCheck(this, AccessMember); _Expression8.call(this); this.object = object; this.name = name; this.isAssignable = true; } AccessMember.prototype.evaluate = function evaluate(scope, lookupFunctions) { var instance = this.object.evaluate(scope, lookupFunctions); return instance === null || instance === undefined ? instance : instance[this.name]; }; AccessMember.prototype.assign = function assign(scope, value) { var instance = this.object.evaluate(scope); if (instance === null || instance === undefined) { instance = {}; this.object.assign(scope, instance); } return instance[this.name] = value; }; AccessMember.prototype.accept = function accept(visitor) { visitor.visitAccessMember(this); }; AccessMember.prototype.connect = function connect(binding, scope) { this.object.connect(binding, scope); var obj = this.object.evaluate(scope); if (obj) { binding.observeProperty(obj, this.name); } }; return AccessMember; })(Expression); exports.AccessMember = AccessMember; var AccessKeyed = (function (_Expression9) { _inherits(AccessKeyed, _Expression9); function AccessKeyed(object, key) { _classCallCheck(this, AccessKeyed); _Expression9.call(this); this.object = object; this.key = key; this.isAssignable = true; } AccessKeyed.prototype.evaluate = function evaluate(scope, lookupFunctions) { var instance = this.object.evaluate(scope, lookupFunctions); var lookup = this.key.evaluate(scope, lookupFunctions); return getKeyed(instance, lookup); }; AccessKeyed.prototype.assign = function assign(scope, value) { var instance = this.object.evaluate(scope); var lookup = this.key.evaluate(scope); return setKeyed(instance, lookup, value); }; AccessKeyed.prototype.accept = function accept(visitor) { visitor.visitAccessKeyed(this); }; AccessKeyed.prototype.connect = function connect(binding, scope) { this.object.connect(binding, scope); var obj = this.object.evaluate(scope); if (obj instanceof Object) { this.key.connect(binding, scope); var key = this.key.evaluate(scope); if (key !== null && key !== undefined) { binding.observeProperty(obj, key); } } }; return AccessKeyed; })(Expression); exports.AccessKeyed = AccessKeyed; var CallScope = (function (_Expression10) { _inherits(CallScope, _Expression10); function CallScope(name, args, ancestor) { _classCallCheck(this, CallScope); _Expression10.call(this); this.name = name; this.args = args; this.ancestor = ancestor; } CallScope.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) { var args = evalList(scope, this.args, lookupFunctions); var context = getContextFor(this.name, scope, this.ancestor); var func = getFunction(context, this.name, mustEvaluate); if (func) { return func.apply(context, args); } return undefined; }; CallScope.prototype.accept = function accept(visitor) { visitor.visitCallScope(this); }; CallScope.prototype.connect = function connect(binding, scope) { var args = this.args; var i = args.length; while (i--) { args[i].connect(binding, scope); } }; return CallScope; })(Expression); exports.CallScope = CallScope; var CallMember = (function (_Expression11) { _inherits(CallMember, _Expression11); function CallMember(object, name, args) { _classCallCheck(this, CallMember); _Expression11.call(this); this.object = object; this.name = name; this.args = args; } CallMember.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) { var instance = this.object.evaluate(scope, lookupFunctions); var args = evalList(scope, this.args, lookupFunctions); var func = getFunction(instance, this.name, mustEvaluate); if (func) { return func.apply(instance, args); } return undefined; }; CallMember.prototype.accept = function accept(visitor) { visitor.visitCallMember(this); }; CallMember.prototype.connect = function connect(binding, scope) { this.object.connect(binding, scope); var obj = this.object.evaluate(scope); if (getFunction(obj, this.name, false)) { var args = this.args; var i = args.length; while (i--) { args[i].connect(binding, scope); } } }; return CallMember; })(Expression); exports.CallMember = CallMember; var CallFunction = (function (_Expression12) { _inherits(CallFunction, _Expression12); function CallFunction(func, args) { _classCallCheck(this, CallFunction); _Expression12.call(this); this.func = func; this.args = args; } CallFunction.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) { var func = this.func.evaluate(scope, lookupFunctions); if (typeof func === 'function') { return func.apply(null, evalList(scope, this.args, lookupFunctions)); } if (!mustEvaluate && (func === null || func === undefined)) { return undefined; } throw new Error(this.func + ' is not a function'); }; CallFunction.prototype.accept = function accept(visitor) { visitor.visitCallFunction(this); }; CallFunction.prototype.connect = function connect(binding, scope) { this.func.connect(binding, scope); var func = this.func.evaluate(scope); if (typeof func === 'function') { var args = this.args; var i = args.length; while (i--) { args[i].connect(binding, scope); } } }; return CallFunction; })(Expression); exports.CallFunction = CallFunction; var Binary = (function (_Expression13) { _inherits(Binary, _Expression13); function Binary(operation, left, right) { _classCallCheck(this, Binary); _Expression13.call(this); this.operation = operation; this.left = left; this.right = right; } Binary.prototype.evaluate = function evaluate(scope, lookupFunctions) { var left = this.left.evaluate(scope); switch (this.operation) { case '&&': return left && this.right.evaluate(scope); case '||': return left || this.right.evaluate(scope); } var right = this.right.evaluate(scope); switch (this.operation) { case '==': return left == right; case '===': return left === right; case '!=': return left != right; case '!==': return left !== right; } if (left === null || right === null) { switch (this.operation) { case '+': if (left != null) return left; if (right != null) return right; return 0; case '-': if (left != null) return left; if (right != null) return 0 - right; return 0; } return null; } switch (this.operation) { case '+': return autoConvertAdd(left, right); case '-': return left - right; case '*': return left * right; case '/': return left / right; case '%': return left % right; case '<': return left < right; case '>': return left > right; case '<=': return left <= right; case '>=': return left >= right; case '^': return left ^ right; } throw new Error('Internal error [' + this.operation + '] not handled'); }; Binary.prototype.accept = function accept(visitor) { visitor.visitBinary(this); }; Binary.prototype.connect = function connect(binding, scope) { this.left.connect(binding, scope); var left = this.left.evaluate(scope); if (this.operation === '&&' && !left || this.operation === '||' && left) { return; } this.right.connect(binding, scope); }; return Binary; })(Expression); exports.Binary = Binary; var PrefixNot = (function (_Expression14) { _inherits(PrefixNot, _Expression14); function PrefixNot(operation, expression) { _classCallCheck(this, PrefixNot); _Expression14.call(this); this.operation = operation; this.expression = expression; } PrefixNot.prototype.evaluate = function evaluate(scope, lookupFunctions) { return !this.expression.evaluate(scope); }; PrefixNot.prototype.accept = function accept(visitor) { visitor.visitPrefix(this); }; PrefixNot.prototype.connect = function connect(binding, scope) { this.expression.connect(binding, scope); }; return PrefixNot; })(Expression); exports.PrefixNot = PrefixNot; var LiteralPrimitive = (function (_Expression15) { _inherits(LiteralPrimitive, _Expression15); function LiteralPrimitive(value) { _classCallCheck(this, LiteralPrimitive); _Expression15.call(this); this.value = value; } LiteralPrimitive.prototype.evaluate = function evaluate(scope, lookupFunctions) { return this.value; }; LiteralPrimitive.prototype.accept = function accept(visitor) { visitor.visitLiteralPrimitive(this); }; LiteralPrimitive.prototype.connect = function connect(binding, scope) {}; return LiteralPrimitive; })(Expression); exports.LiteralPrimitive = LiteralPrimitive; var LiteralString = (function (_Expression16) { _inherits(LiteralString, _Expression16); function LiteralString(value) { _classCallCheck(this, LiteralString); _Expression16.call(this); this.value = value; } LiteralString.prototype.evaluate = function evaluate(scope, lookupFunctions) { return this.value; }; LiteralString.prototype.accept = function accept(visitor) { visitor.visitLiteralString(this); }; LiteralString.prototype.connect = function connect(binding, scope) {}; return LiteralString; })(Expression); exports.LiteralString = LiteralString; var LiteralArray = (function (_Expression17) { _inherits(LiteralArray, _Expression17); function LiteralArray(elements) { _classCallCheck(this, LiteralArray); _Expression17.call(this); this.elements = elements; } LiteralArray.prototype.evaluate = function evaluate(scope, lookupFunctions) { var elements = this.elements, length = elements.length, result = [], i; for (i = 0; i < length; ++i) { result[i] = elements[i].evaluate(scope, lookupFunctions); } return result; }; LiteralArray.prototype.accept = function accept(visitor) { visitor.visitLiteralArray(this); }; LiteralArray.prototype.connect = function connect(binding, scope) { var length = this.elements.length; for (var i = 0; i < length; i++) { this.elements[i].connect(binding, scope); } }; return LiteralArray; })(Expression); exports.LiteralArray = LiteralArray; var LiteralObject = (function (_Expression18) { _inherits(LiteralObject, _Expression18); function LiteralObject(keys, values) { _classCallCheck(this, LiteralObject); _Expression18.call(this); this.keys = keys; this.values = values; } LiteralObject.prototype.evaluate = function evaluate(scope, lookupFunctions) { var instance = {}, keys = this.keys, values = this.values, length = keys.length, i; for (i = 0; i < length; ++i) { instance[keys[i]] = values[i].evaluate(scope, lookupFunctions); } return instance; }; LiteralObject.prototype.accept = function accept(visitor) { visitor.visitLiteralObject(this); }; LiteralObject.prototype.connect = function connect(binding, scope) { var length = this.keys.length; for (var i = 0; i < length; i++) { this.values[i].connect(binding, scope); } }; return LiteralObject; })(Expression); exports.LiteralObject = LiteralObject; var Unparser = (function () { function Unparser(buffer) { _classCallCheck(this, Unparser); this.buffer = buffer; } Unparser.unparse = function unparse(expression) { var buffer = [], visitor = new Unparser(buffer); expression.accept(visitor); return buffer.join(''); }; Unparser.prototype.write = function write(text) { this.buffer.push(text); }; Unparser.prototype.writeArgs = function writeArgs(args) { var i, length; this.write('('); for (i = 0, length = args.length; i < length; ++i) { if (i !== 0) { this.write(','); } args[i].accept(this); } this.write(')'); }; Unparser.prototype.visitChain = function visitChain(chain) { var expressions = chain.expressions, length = expressions.length, i; for (i = 0; i < length; ++i) { if (i !== 0) { this.write(';'); } expressions[i].accept(this); } }; Unparser.prototype.visitBindingBehavior = function visitBindingBehavior(behavior) { var args = behavior.args, length = args.length, i; this.write('('); behavior.expression.accept(this); this.write('&' + behavior.name); for (i = 0; i < length; ++i) { this.write(' :'); args[i].accept(this); } this.write(')'); }; Unparser.prototype.visitValueConverter = function visitValueConverter(converter) { var args = converter.args, length = args.length, i; this.write('('); converter.expression.accept(this); this.write('|' + converter.name); for (i = 0; i < length; ++i) { this.write(' :'); args[i].accept(this); } this.write(')'); }; Unparser.prototype.visitAssign = function visitAssign(assign) { assign.target.accept(this); this.write('='); assign.value.accept(this); }; Unparser.prototype.visitConditional = function visitConditional(conditional) { conditional.condition.accept(this); this.write('?'); conditional.yes.accept(this); this.write(':'); conditional.no.accept(this); }; Unparser.prototype.visitAccessThis = function visitAccessThis(access) { if (access.ancestor === 0) { this.write('$this'); return; } this.write('$parent'); var i = access.ancestor - 1; while (i--) { this.write('.$parent'); } }; Unparser.prototype.visitAccessScope = function visitAccessScope(access) { var i = access.ancestor; while (i--) { this.write('$parent.'); } this.write(access.name); }; Unparser.prototype.visitAccessMember = function visitAccessMember(access) { access.object.accept(this); this.write('.' + access.name); }; Unparser.prototype.visitAccessKeyed = function visitAccessKeyed(access) { access.object.accept(this); this.write('['); access.key.accept(this); this.write(']'); }; Unparser.prototype.visitCallScope = function visitCallScope(call) { var i = call.ancestor; while (i--) { this.write('$parent.'); } this.write(call.name); this.writeArgs(call.args); }; Unparser.prototype.visitCallFunction = function visitCallFunction(call) { call.func.accept(this); this.writeArgs(call.args); }; Unparser.prototype.visitCallMember = function visitCallMember(call) { call.object.accept(this); this.write('.' + call.name); this.writeArgs(call.args); }; Unparser.prototype.visitPrefix = function visitPrefix(prefix) { this.write('(' + prefix.operation); prefix.expression.accept(this); this.write(')'); }; Unparser.prototype.visitBinary = function visitBinary(binary) { this.write('('); binary.left.accept(this); this.write(binary.operation); binary.right.accept(this); this.write(')'); }; Unparser.prototype.visitLiteralPrimitive = function visitLiteralPrimitive(literal) { this.write('' + literal.value); }; Unparser.prototype.visitLiteralArray = function visitLiteralArray(literal) { var elements = literal.elements, length = elements.length, i; this.write('['); for (i = 0; i < length; ++i) { if (i !== 0) { this.write(','); } elements[i].accept(this); } this.write(']'); }; Unparser.prototype.visitLiteralObject = function visitLiteralObject(literal) { var keys = literal.keys, values = literal.values, length = keys.length, i; this.write('{'); for (i = 0; i < length; ++i) { if (i !== 0) { this.write(','); } this.write('\'' + keys[i] + '\':'); values[i].accept(this); } this.write('}'); }; Unparser.prototype.visitLiteralString = function visitLiteralString(literal) { var escaped = literal.value.replace(/'/g, "\'"); this.write('\'' + escaped + '\''); }; return Unparser; })(); exports.Unparser = Unparser; var evalListCache = [[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0]]; function evalList(scope, list, lookupFunctions) { var length = list.length, cacheLength, i; for (cacheLength = evalListCache.length; cacheLength <= length; ++cacheLength) { evalListCache.push([]); } var result = evalListCache[length]; for (i = 0; i < length; ++i) { result[i] = list[i].evaluate(scope, lookupFunctions); } return result; } function autoConvertAdd(a, b) { if (a != null && b != null) { if (typeof a == 'string' && typeof b != 'string') { return a + b.toString(); } if (typeof a != 'string' && typeof b == 'string') { return a.toString() + b; } return a + b; } if (a != null) { return a; } if (b != null) { return b; } return 0; } function getFunction(obj, name, mustExist) { var func = obj === null || obj === undefined ? null : obj[name]; if (typeof func === 'function') { return func; } if (!mustExist && (func === null || func === undefined)) { return null; } throw new Error(name + ' is not a function'); } function getKeyed(obj, key) { if (Array.isArray(obj)) { return obj[parseInt(key)]; } else if (obj) { return obj[key]; } else if (obj === null) { throw new Error('Accessing null object'); } else { return obj[key]; } } function setKeyed(obj, key, value) { if (Array.isArray(obj)) { var index = parseInt(key); if (obj.length <= index) { obj.length = index + 1; } obj[index] = value; } else { obj[key] = value; } return value; } var bindingMode = { oneTime: 0, oneWay: 1, twoWay: 2 }; exports.bindingMode = bindingMode; var Token = (function () { function Token(index, text) { _classCallCheck(this, Token); this.index = index; this.text = text; } Token.prototype.withOp = function withOp(op) { this.opKey = op; return this; }; Token.prototype.withGetterSetter = function withGetterSetter(key) { this.key = key; return this; }; Token.prototype.withValue = function withValue(value) { this.value = value; return this; }; Token.prototype.toString = function toString() { return 'Token(' + this.text + ')'; }; return Token; })(); exports.Token = Token; var Lexer = (function () { function Lexer() { _classCallCheck(this, Lexer); } Lexer.prototype.lex = function lex(text) { var scanner = new Scanner(text); var tokens = []; var token = scanner.scanToken(); while (token) { tokens.push(token); token = scanner.scanToken(); } return tokens; }; return Lexer; })(); exports.Lexer = Lexer; var Scanner = (function () { function Scanner(input) { _classCallCheck(this, Scanner); this.input = input; this.length = input.length; this.peek = 0; this.index = -1; this.advance(); } Scanner.prototype.scanToken = function scanToken() { while (this.peek <= $SPACE) { if (++this.index >= this.length) { this.peek = $EOF; return null; } else { this.peek = this.input.charCodeAt(this.index); } } if (isIdentifierStart(this.peek)) { return this.scanIdentifier(); } if (isDigit(this.peek)) { return this.scanNumber(this.index); } var start = this.index; switch (this.peek) { case $PERIOD: this.advance(); return isDigit(this.peek) ? this.scanNumber(start) : new Token(start, '.'); case $LPAREN: case $RPAREN: case $LBRACE: case $RBRACE: case $LBRACKET: case $RBRACKET: case $COMMA: case $COLON: case $SEMICOLON: return this.scanCharacter(start, String.fromCharCode(this.peek)); case $SQ: case $DQ: return this.scanString(); case $PLUS: case $MINUS: case $STAR: case $SLASH: case $PERCENT: case $CARET: case $QUESTION: return this.scanOperator(start, String.fromCharCode(this.peek)); case $LT: case $GT: case $BANG: case $EQ: return this.scanComplexOperator(start, $EQ, String.fromCharCode(this.peek), '='); case $AMPERSAND: return this.scanComplexOperator(start, $AMPERSAND, '&', '&'); case $BAR: return this.scanComplexOperator(start, $BAR, '|', '|'); case $NBSP: while (isWhitespace(this.peek)) { this.advance(); } return this.scanToken(); } var character = String.fromCharCode(this.peek); this.error('Unexpected character [' + character + ']'); return null; }; Scanner.prototype.scanCharacter = function scanCharacter(start, text) { assert(this.peek === text.charCodeAt(0)); this.advance(); return new Token(start, text); }; Scanner.prototype.scanOperator = function scanOperator(start, text) { assert(this.peek === text.charCodeAt(0)); assert(OPERATORS.indexOf(text) !== -1); this.advance(); return new Token(start, text).withOp(text); }; Scanner.prototype.scanComplexOperator = function scanComplexOperator(start, code, one, two) { assert(this.peek === one.charCodeAt(0)); this.advance(); var text = one; if (this.peek === code) { this.advance(); text += two; } if (this.peek === code) { this.advance(); text += two; } assert(OPERATORS.indexOf(text) != -1); return new Token(start, text).withOp(text); }; Scanner.prototype.scanIdentifier = function scanIdentifier() { assert(isIdentifierStart(this.peek)); var start = this.index; this.advance(); while (isIdentifierPart(this.peek)) { this.advance(); } var text = this.input.substring(start, this.index); var result = new Token(start, text); if (OPERATORS.indexOf(text) !== -1) { result.withOp(text); } else { result.withGetterSetter(text); } return result; }; Scanner.prototype.scanNumber = function scanNumber(start) { assert(isDigit(this.peek)); var simple = this.index === start; this.advance(); while (true) { if (isDigit(this.peek)) {} else if (this.peek === $PERIOD) { simple = false; } else if (isExponentStart(this.peek)) { this.advance(); if (isExponentSign(this.peek)) { this.advance(); } if (!isDigit(this.peek)) { this.error('Invalid exponent', -1); } simple = false; } else { break; } this.advance(); } var text = this.input.substring(start, this.index); var value = simple ? parseInt(text) : parseFloat(text); return new Token(start, text).withValue(value); }; Scanner.prototype.scanString = function scanString() { assert(this.peek === $SQ || this.peek === $DQ); var start = this.index; var quote = this.peek; this.advance(); var buffer = undefined; var marker = this.index; while (this.peek !== quote) { if (this.peek === $BACKSLASH) { if (!buffer) { buffer = []; } buffer.push(this.input.substring(marker, this.index)); this.advance(); var _unescaped = undefined; if (this.peek === $u) { var hex = this.input.substring(this.index + 1, this.index + 5); if (!/[A-Z0-9]{4}/.test(hex)) { this.error('Invalid unicode escape [\\u' + hex + ']'); } _unescaped = parseInt(hex, 16); for (var i = 0; i < 5; ++i) { this.advance(); } } else { _unescaped = unescape(this.peek); this.advance(); } buffer.push(String.fromCharCode(_unescaped)); marker = this.index; } else if (this.peek === $EOF) { this.error('Unterminated quote'); } else { this.advance(); } } var last = this.input.substring(marker, this.index); this.advance(); var text = this.input.substring(start, this.index); var unescaped = last; if (buffer != null) { buffer.push(last); unescaped = buffer.join(''); } return new Token(start, text).withValue(unescaped); }; Scanner.prototype.advance = function advance() { if (++this.index >= this.length) { this.peek = $EOF; } else { this.peek = this.input.charCodeAt(this.index); } }; Scanner.prototype.error = function error(message) { var offset = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; var position = this.index + offset; throw new Error('Lexer Error: ' + message + ' at column ' + position + ' in expression [' + this.input + ']'); }; return Scanner; })(); exports.Scanner = Scanner; var OPERATORS = ['undefined', 'null', 'true', 'false', '+', '-', '*', '/', '%', '^', '=', '==', '===', '!=', '!==', '<', '>', '<=', '>=', '&&', '||', '&', '|', '!', '?']; var $EOF = 0; var $TAB = 9; var $LF = 10; var $VTAB = 11; var $FF = 12; var $CR = 13; var $SPACE = 32; var $BANG = 33; var $DQ = 34; var $$ = 36; var $PERCENT = 37; var $AMPERSAND = 38; var $SQ = 39; var $LPAREN = 40; var $RPAREN = 41; var $STAR = 42; var $PLUS = 43; var $COMMA = 44; var $MINUS = 45; var $PERIOD = 46; var $SLASH = 47; var $COLON = 58; var $SEMICOLON = 59; var $LT = 60; var $EQ = 61; var $GT = 62; var $QUESTION = 63; var $0 = 48; var $9 = 57; var $A = 65; var $E = 69; var $Z = 90; var $LBRACKET = 91; var $BACKSLASH = 92; var $RBRACKET = 93; var $CARET = 94; var $_ = 95; var $a = 97; var $e = 101; var $f = 102; var $n = 110; var $r = 114; var $t = 116; var $u = 117; var $v = 118; var $z = 122; var $LBRACE = 123; var $BAR = 124; var $RBRACE = 125; var $NBSP = 160; function isWhitespace(code) { return code >= $TAB && code <= $SPACE || code === $NBSP; } function isIdentifierStart(code) { return $a <= code && code <= $z || $A <= code && code <= $Z || code === $_ || code === $$; } function isIdentifierPart(code) { return $a <= code && code <= $z || $A <= code && code <= $Z || $0 <= code && code <= $9 || code === $_ || code === $$; } function isDigit(code) { return $0 <= code && code <= $9; } function isExponentStart(code) { return code === $e || code === $E; } function isExponentSign(code) { return code === $MINUS || code === $PLUS; } function unescape(code) { switch (code) { case $n: return $LF; case $f: return $FF; case $r: return $CR; case $t: return $TAB; case $v: return $VTAB; default: return code; } } function assert(condition, message) { if (!condition) { throw message || "Assertion failed"; } } var EOF = new Token(-1, null); var Parser = (function () { function Parser() { _classCallCheck(this, Parser); this.cache = {}; this.lexer = new Lexer(); } Parser.prototype.parse = function parse(input) { input = input || ''; return this.cache[input] || (this.cache[input] = new ParserImplementation(this.lexer, input).parseChain()); }; return Parser; })(); exports.Parser = Parser; var ParserImplementation = (function () { function ParserImplementation(lexer, input) { _classCallCheck(this, ParserImplementation); this.index = 0; this.input = input; this.tokens = lexer.lex(input); } ParserImplementation.prototype.parseChain = function parseChain() { var isChain = false; var expressions = []; while (this.optional(';')) { isChain = true; } while (this.index < this.tokens.length) { if (this.peek.text === ')' || this.peek.text === '}' || this.peek.text === ']') { this.error('Unconsumed token ' + this.peek.text); } var expr = this.parseBindingBehavior(); expressions.push(expr); while (this.optional(';')) { isChain = true; } if (isChain) { this.error('Multiple expressions are not allowed.'); } } return expressions.length === 1 ? expressions[0] : new Chain(expressions); }; ParserImplementation.prototype.parseBindingBehavior = function parseBindingBehavior() { var result = this.parseValueConverter(); while (this.optional('&')) { var _name = this.peek.text; var args = []; this.advance(); while (this.optional(':')) { args.push(this.parseExpression()); } result = new BindingBehavior(result, _name, args); } return result; }; ParserImplementation.prototype.parseValueConverter = function parseValueConverter() { var result = this.parseExpression(); while (this.optional('|')) { var _name2 = this.peek.text; var args = []; this.advance(); while (this.optional(':')) { args.push(this.parseExpression()); } result = new ValueConverter(result, _name2, args, [result].concat(args)); } return result; }; ParserImplementation.prototype.parseExpression = function parseExpression() { var start = this.peek.index; var result = this.parseConditional(); while (this.peek.text === '=') { if (!result.isAssignable) { var end = this.index < this.tokens.length ? this.peek.index : this.input.length; var expression = this.input.substring(start, end); this.error('Expression ' + expression + ' is not assignable'); } this.expect('='); result = new Assign(result, this.parseConditional()); } return result; }; ParserImplementation.prototype.parseConditional = function parseConditional() { var start = this.peek.index; var result = this.parseLogicalOr(); if (this.optional('?')) { var yes = this.parseExpression(); if (!this.optional(':')) { var end = this.index < this.tokens.length ? this.peek.index : this.input.length; var expression = this.input.substring(start, end); this.error('Conditional expression ' + expression + ' requires all 3 expressions'); } var no = this.parseExpression(); result = new Conditional(result, yes, no); } return result; }; ParserImplementation.prototype.parseLogicalOr = function parseLogicalOr() { var result = this.parseLogicalAnd(); while (this.optional('||')) { result = new Binary('||', result, this.parseLogicalAnd()); } return result; }; ParserImplementation.prototype.parseLogicalAnd = function parseLogicalAnd() { var result = this.parseEquality(); while (this.optional('&&')) { result = new Binary('&&', result, this.parseEquality()); } return result; }; ParserImplementation.prototype.parseEquality = function parseEquality() { var result = this.parseRelational(); while (true) { if (this.optional('==')) { result = new Binary('==', result, this.parseRelational()); } else if (this.optional('!=')) { result = new Binary('!=', result, this.parseRelational()); } else if (this.optional('===')) { result = new Binary('===', result, this.parseRelational()); } else if (this.optional('!==')) { result = new Binary('!==', result, this.parseRelational()); } else { return result; } } }; ParserImplementation.prototype.parseRelational = function parseRelational() { var result = this.parseAdditive(); while (true) { if (this.optional('<')) { result = new Binary('<', result, this.parseAdditive()); } else if (this.optional('>')) { result = new Binary('>', result, this.parseAdditive()); } else if (this.optional('<=')) { result = new Binary('<=', result, this.parseAdditive()); } else if (this.optional('>=')) { result = new Binary('>=', result, this.parseAdditive()); } else { return result; } } }; ParserImplementation.prototype.parseAdditive = function parseAdditive() { var result = this.parseMultiplicative(); while (true) { if (this.optional('+')) { result = new Binary('+', result, this.parseMultiplicative()); } else if (this.optional('-')) { result = new Binary('-', result, this.parseMultiplicative()); } else { return result; } } }; ParserImplementation.prototype.parseMultiplicative = function parseMultiplicative() { var result = this.parsePrefix(); while (true) { if (this.optional('*')) { result = new Binary('*', result, this.parsePrefix()); } else if (this.optional('%')) { result = new Binary('%', result, this.parsePrefix()); } else if (this.optional('/')) { result = new Binary('/', result, this.parsePrefix()); } else { return result; } } }; ParserImplementation.prototype.parsePrefix = function parsePrefix() { if (this.optional('+')) { return this.parsePrefix(); } else if (this.optional('-')) { return new Binary('-', new LiteralPrimitive(0), this.parsePrefix()); } else if (this.optional('!')) { return new PrefixNot('!', this.parsePrefix()); } else { return this.parseAccessOrCallMember(); } }; ParserImplementation.prototype.parseAccessOrCallMember = function parseAccessOrCallMember() { var result = this.parsePrimary(); while (true) { if (this.optional('.')) { var _name3 = this.peek.text; this.advance(); if (this.optional('(')) { var args = this.parseExpressionList(')'); this.expect(')'); if (result instanceof AccessThis) { result = new CallScope(_name3, args, result.ancestor); } else { result = new CallMember(result, _name3, args); } } else { if (result instanceof AccessThis) { result = new AccessScope(_name3, result.ancestor); } else { result = new AccessMember(result, _name3); } } } else if (this.optional('[')) { var key = this.parseExpression(); this.expect(']'); result = new AccessKeyed(result, key); } else if (this.optional('(')) { var args = this.parseExpressionList(')'); this.expect(')'); result = new CallFunction(result, args); } else { return result; } } }; ParserImplementation.prototype.parsePrimary = function parsePrimary() { if (this.optional('(')) { var result = this.parseExpression(); this.expect(')'); return result; } else if (this.optional('null')) { return new LiteralPrimitive(null); } else if (this.optional('undefined')) { return new LiteralPrimitive(undefined); } else if (this.optional('true')) { return new LiteralPrimitive(true); } else if (this.optional('false')) { return new LiteralPrimitive(false); } else if (this.optional('[')) { var _elements = this.parseExpressionList(']'); this.expect(']'); return new LiteralArray(_elements); } else if (this.peek.text == '{') { return this.parseObject(); } else if (this.peek.key != null) { return this.parseAccessOrCallScope(); } else if (this.peek.value != null) { var value = this.peek.value; this.advance(); return value instanceof String || typeof value === 'string' ? new LiteralString(value) : new LiteralPrimitive(value); } else if (this.index >= this.tokens.length) { throw new Error('Unexpected end of expression: ' + this.input); } else { this.error('Unexpected token ' + this.peek.text); } }; ParserImplementation.prototype.parseAccessOrCallScope = function parseAccessOrCallScope() { var name = this.peek.key; this.advance(); if (name === '$this') { return new AccessThis(0); } var ancestor = 0; while (name === '$parent') { ancestor++; if (this.optional('.')) { name = this.peek.key; this.advance(); } else if (this.peek === EOF || this.peek.text === '(' || this.peek.text === '[' || this.peek.text === '}') { return new AccessThis(ancestor); } else { this.error('Unexpected token ' + this.peek.text); } } if (this.optional('(')) { var args = this.parseExpressionList(')'); this.expect(')'); return new CallScope(name, args, ancestor); } return new AccessScope(name, ancestor); }; ParserImplementation.prototype.parseObject = function parseObject() { var keys = []; var values = []; this.expect('{'); if (this.peek.text !== '}') { do { var value = this.peek.value; keys.push(typeof value === 'string' ? value : this.peek.text); this.advance(); this.expect(':'); values.push(this.parseExpression()); } while (this.optional(',')); } this.expect('}'); return new LiteralObject(keys, values); }; ParserImplementation.prototype.parseExpressionList = function parseExpressionList(terminator) { var result = []; if (this.peek.text != terminator) { do { result.push(this.parseExpression()); } while (this.optional(',')); } return result; }; ParserImplementation.prototype.optional = function optional(text) { if (this.peek.text === text) { this.advance(); return true; } return false; }; ParserImplementation.prototype.expect = function expect(text) { if (this.peek.text === text) { this.advance(); } else { this.error('Missing expected ' + text); } }; ParserImplementation.prototype.advance = function advance() { this.index++; }; ParserImplementation.prototype.error = function error(message) { var location = this.index < this.tokens.length ? 'at column ' + (this.tokens[this.index].index + 1) + ' in' : 'at the end of the expression'; throw new Error('Parser Error: ' + message + ' ' + location + ' [' + this.input + ']'); }; _createClass(ParserImplementation, [{ key: 'peek', get: function get() { return this.index < this.tokens.length ? this.tokens[this.index] : EOF; } }]); return ParserImplementation; })(); exports.ParserImplementation = ParserImplementation; var mapProto = Map.prototype; function _getMapObserver(taskQueue, map) { return ModifyMapObserver.create(taskQueue, map); } var ModifyMapObserver = (function (_ModifyCollectionObserver3) { _inherits(ModifyMapObserver, _ModifyCollectionObserver3); function ModifyMapObserver(taskQueue, map) { _classCallCheck(this, ModifyMapObserver); _ModifyCollectionObserver3.call(this, taskQueue, map); } ModifyMapObserver.create = function create(taskQueue, map) { var observer = new ModifyMapObserver(taskQueue, map); map['set'] = function () { var oldValue = map.get(arguments[0]); var type = typeof oldValue !== 'undefined' ? 'update' : 'add'; var methodCallResult = mapProto['set'].apply(map, arguments); observer.addChangeRecord({ type: type, object: map, key: arguments[0], oldValue: oldValue }); return methodCallResult; }; map['delete'] = function () { var oldValue = map.get(arguments[0]); var methodCallResult = mapProto['delete'].apply(map, arguments); observer.addChangeRecord({ type: 'delete', object: map, key: arguments[0], oldValue: oldValue }); return methodCallResult; }; map['clear'] = function () { var methodCallResult = mapProto['clear'].apply(map, arguments); observer.addChangeRecord({ type: 'clear', object: map }); return methodCallResult; }; return observer; }; return ModifyMapObserver; })(ModifyCollectionObserver); function findOriginalEventTarget(event) { return event.path && event.path[0] || event.deepPath && event.deepPath[0] || event.target; } function handleDelegatedEvent(event) { var target = findOriginalEventTarget(event); var callback = undefined; while (target && !callback) { if (target.delegatedCallbacks) { callback = target.delegatedCallbacks[event.type]; } if (!callback) { target = target.parentNode; } } if (callback) { callback(event); } } var DelegateHandlerEntry = (function () { function DelegateHandlerEntry(eventName) { _classCallCheck(this, DelegateHandlerEntry); this.eventName = eventName; this.count = 0; } DelegateHandlerEntry.prototype.increment = function increment() { this.count++; if (this.count === 1) { _aureliaPal.DOM.addEventListener(this.eventName, handleDelegatedEvent, false); } }; DelegateHandlerEntry.prototype.decrement = function decrement() { this.count--; if (this.count === 0) { _aureliaPal.DOM.removeEventListener(this.eventName, handleDelegatedEvent); } }; return DelegateHandlerEntry; })(); var DefaultEventStrategy = (function () { function DefaultEventStrategy() { _classCallCheck(this, DefaultEventStrategy); this.delegatedHandlers = []; } DefaultEventStrategy.prototype.subscribe = function subscribe(target, targetEvent, callback, delegate) { var _this = this; if (delegate) { var _ret = (function () { var delegatedHandlers = _this.delegatedHandlers; var handlerEntry = delegatedHandlers[targetEvent] || (delegatedHandlers[targetEvent] = new DelegateHandlerEntry(targetEvent)); var delegatedCallbacks = target.delegatedCallbacks || (target.delegatedCallbacks = {}); handlerEntry.increment(); delegatedCallbacks[targetEvent] = callback; return { v: function () { handlerEntry.decrement(); delegatedCallbacks[targetEvent] = null; } }; })(); if (typeof _ret === 'object') return _ret.v; } else { target.addEventListener(targetEvent, callback, false); return function () { target.removeEventListener(targetEvent, callback); }; } }; return DefaultEventStrategy; })(); var EventManager = (function () { function EventManager() { _classCallCheck(this, EventManager); this.elementHandlerLookup = {}; this.eventStrategyLookup = {}; this.registerElementConfig({ tagName: 'input', properties: { value: ['change', 'input'], checked: ['change', 'input'], files: ['change', 'input'] } }); this.registerElementConfig({ tagName: 'textarea', properties: { value: ['change', 'input'] } }); this.registerElementConfig({ tagName: 'select', properties: { value: ['change'] } }); this.registerElementConfig({ tagName: 'content editable', properties: { value: ['change', 'input', 'blur', 'keyup', 'paste'] } }); this.registerElementConfig({ tagName: 'scrollable element', properties: { scrollTop: ['scroll'], scrollLeft: ['scroll'] } }); this.defaultEventStrategy = new DefaultEventStrategy(); } EventManager.prototype.registerElementConfig = function registerElementConfig(config) { var tagName = config.tagName.toLowerCase(); var properties = config.properties; var propertyName = undefined; this.elementHandlerLookup[tagName] = {}; for (propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this.registerElementPropertyConfig(tagName, propertyName, properties[propertyName]); } } }; EventManager.prototype.registerElementPropertyConfig = function registerElementPropertyConfig(tagName, propertyName, events) { this.elementHandlerLookup[tagName][propertyName] = this.createElementHandler(events); }; EventManager.prototype.createElementHandler = function createElementHandler(events) { return { subscribe: function subscribe(target, callback) { events.forEach(function (changeEvent) { target.addEventListener(changeEvent, callback, false); }); return function () { events.forEach(function (changeEvent) { target.removeEventListener(changeEvent, callback); }); }; } }; }; EventManager.prototype.registerElementHandler = function registerElementHandler(tagName, handler) { this.elementHandlerLookup[tagName.toLowerCase()] = handler; }; EventManager.prototype.registerEventStrategy = function registerEventStrategy(eventName, strategy) { this.eventStrategyLookup[eventName] = strategy; }; EventManager.prototype.getElementHandler = function getElementHandler(target, propertyName) { var tagName = undefined; var lookup = this.elementHandlerLookup; if (target.tagName) { tagName = target.tagName.toLowerCase(); if (lookup[tagName] && lookup[tagName][propertyName]) { return lookup[tagName][propertyName]; } if (propertyName === 'textContent' || propertyName === 'innerHTML') { return lookup['content editable']['value']; } if (propertyName === 'scrollTop' || propertyName === 'scrollLeft') { return lookup['scrollable element'][propertyName]; } } return null; }; EventManager.prototype.addEventListener = function addEventListener(target, targetEvent, callback, delegate) { return (this.eventStrategyLookup[targetEvent] || this.defaultEventStrategy).subscribe(target, targetEvent, callback, delegate); }; return EventManager; })(); exports.EventManager = EventManager; var DirtyChecker = (function () { function DirtyChecker() { _classCallCheck(this, DirtyChecker); this.tracked = []; this.checkDelay = 120; } DirtyChecker.prototype.addProperty = function addProperty(property) { var tracked = this.tracked; tracked.push(property); if (tracked.length === 1) { this.scheduleDirtyCheck(); } }; DirtyChecker.prototype.removeProperty = function removeProperty(property) { var tracked = this.tracked; tracked.splice(tracked.indexOf(property), 1); }; DirtyChecker.prototype.scheduleDirtyCheck = function scheduleDirtyCheck() { var _this2 = this; setTimeout(function () { return _this2.check(); }, this.checkDelay); }; DirtyChecker.prototype.check = function check() { var tracked = this.tracked, i = tracked.length; while (i--) { var current = tracked[i]; if (current.isDirty()) { current.call(); } } if (tracked.length) { this.scheduleDirtyCheck(); } }; return DirtyChecker; })(); exports.DirtyChecker = DirtyChecker; var DirtyCheckProperty = (function () { function DirtyCheckProperty(dirtyChecker, obj, propertyName) { _classCallCheck(this, _DirtyCheckProperty); this.dirtyChecker = dirtyChecker; this.obj = obj; this.propertyName = propertyName; } DirtyCheckProperty.prototype.getValue = function getValue() { return this.obj[this.propertyName]; }; DirtyCheckProperty.prototype.setValue = function setValue(newValue) { this.obj[this.propertyName] = newValue; }; DirtyCheckProperty.prototype.call = function call() { var oldValue = this.oldValue; var newValue = this.getValue(); this.callSubscribers(newValue, oldValue); this.oldValue = newValue; }; DirtyCheckProperty.prototype.isDirty = function isDirty() { return this.oldValue !== this.obj[this.propertyName]; }; DirtyCheckProperty.prototype.subscribe = function subscribe(context, callable) { if (!this.hasSubscribers()) { this.oldValue = this.getValue(); this.dirtyChecker.addProperty(this); } this.addSubscriber(context, callable); }; DirtyCheckProperty.prototype.unsubscribe = function unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.dirtyChecker.removeProperty(this); } }; var _DirtyCheckProperty = DirtyCheckProperty; DirtyCheckProperty = subscriberCollection()(DirtyCheckProperty) || DirtyCheckProperty; return DirtyCheckProperty; })(); exports.DirtyCheckProperty = DirtyCheckProperty; var PrimitiveObserver = (function () { function PrimitiveObserver(primitive, propertyName) { _classCallCheck(this, PrimitiveObserver); this.doNotCache = true; this.primitive = primitive; this.propertyName = propertyName; } PrimitiveObserver.prototype.getValue = function getValue() { return this.primitive[this.propertyName]; }; PrimitiveObserver.prototype.setValue = function setValue() { var type = typeof this.primitive; throw new Error('The ' + this.propertyName + ' property of a ' + type + ' (' + this.primitive + ') cannot be assigned.'); }; PrimitiveObserver.prototype.subscribe = function subscribe() {}; PrimitiveObserver.prototype.unsubscribe = function unsubscribe() {}; return PrimitiveObserver; })(); exports.PrimitiveObserver = PrimitiveObserver; var SetterObserver = (function () { function SetterObserver(taskQueue, obj, propertyName) { _classCallCheck(this, _SetterObserver); this.taskQueue = taskQueue; this.obj = obj; this.propertyName = propertyName; this.queued = false; this.observing = false; } SetterObserver.prototype.getValue = function getValue() { return this.obj[this.propertyName]; }; SetterObserver.prototype.setValue = function setValue(newValue) { this.obj[this.propertyName] = newValue; }; SetterObserver.prototype.getterValue = function getterValue() { return this.currentValue; }; SetterObserver.prototype.setterValue = function setterValue(newValue) { var oldValue = this.currentValue; if (oldValue !== newValue) { if (!this.queued) { this.oldValue = oldValue; this.queued = true; this.taskQueue.queueMicroTask(this); } this.currentValue = newValue; } }; SetterObserver.prototype.call = function call() { var oldValue = this.oldValue; var newValue = this.currentValue; this.queued = false; this.callSubscribers(newValue, oldValue); }; SetterObserver.prototype.subscribe = function subscribe(context, callable) { if (!this.observing) { this.convertProperty(); } this.addSubscriber(context, callable); }; SetterObserver.prototype.unsubscribe = function unsubscribe(context, callable) { this.removeSubscriber(context, callable); }; SetterObserver.prototype.convertProperty = function convertProperty() { this.observing = true; this.currentValue = this.obj[this.propertyName]; this.setValue = this.setterValue; this.getValue = this.getterValue; try { Object.defineProperty(this.obj, this.propertyName, { configurable: true, enumerable: true, get: this.getValue.bind(this), set: this.setValue.bind(this) }); } catch (_) {} }; var _SetterObserver = SetterObserver; SetterObserver = subscriberCollection()(SetterObserver) || SetterObserver; return SetterObserver; })(); exports.SetterObserver = SetterObserver; var XLinkAttributeObserver = (function () { function XLinkAttributeObserver(element, propertyName, attributeName) { _classCallCheck(this, XLinkAttributeObserver); this.element = element; this.propertyName = propertyName; this.attributeName = attributeName; } XLinkAttributeObserver.prototype.getValue = function getValue() { return this.element.getAttributeNS('http://www.w3.org/1999/xlink', this.attributeName); }; XLinkAttributeObserver.prototype.setValue = function setValue(newValue) { return this.element.setAttributeNS('http://www.w3.org/1999/xlink', this.attributeName, newValue); }; XLinkAttributeObserver.prototype.subscribe = function subscribe() { throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.'); }; return XLinkAttributeObserver; })(); exports.XLinkAttributeObserver = XLinkAttributeObserver; var DataAttributeObserver = (function () { function DataAttributeObserver(element, propertyName) { _classCallCheck(this, DataAttributeObserver); this.element = element; this.propertyName = propertyName; } DataAttributeObserver.prototype.getValue = function getValue() { return this.element.getAttribute(this.propertyName); }; DataAttributeObserver.prototype.setValue = function setValue(newValue) { return this.element.setAttribute(this.propertyName, newValue); }; DataAttributeObserver.prototype.subscribe = function subscribe() { throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.'); }; return DataAttributeObserver; })(); exports.DataAttributeObserver = DataAttributeObserver; var StyleObserver = (function () { function StyleObserver(element, propertyName) { _classCallCheck(this, StyleObserver); this.element = element; this.propertyName = propertyName; } StyleObserver.prototype.getValue = function getValue() { return this.element.style.cssText; }; StyleObserver.prototype.setValue = function setValue(newValue) { if (newValue instanceof Object) { newValue = this.flattenCss(newValue); } this.element.style.cssText = newValue; }; StyleObserver.prototype.subscribe = function subscribe() { throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.'); }; StyleObserver.prototype.flattenCss = function flattenCss(object) { var s = ''; for (var propertyName in object) { if (object.hasOwnProperty(propertyName)) { s += propertyName + ': ' + object[propertyName] + '; '; } } return s; }; return StyleObserver; })(); exports.StyleObserver = StyleObserver; var ValueAttributeObserver = (function () { function ValueAttributeObserver(element, propertyName, handler) { _classCallCheck(this, _ValueAttributeObserver); this.element = element; this.propertyName = propertyName; this.handler = handler; } ValueAttributeObserver.prototype.getValue = function getValue() { return this.element[this.propertyName]; }; ValueAttributeObserver.prototype.setValue = function setValue(newValue) { this.element[this.propertyName] = newValue === undefined || newValue === null ? '' : newValue; this.notify(); }; ValueAttributeObserver.prototype.notify = function notify() { var oldValue = this.oldValue; var newValue = this.getValue(); this.callSubscribers(newValue, oldValue); this.oldValue = newValue; }; ValueAttributeObserver.prototype.subscribe = function subscribe(context, callable) { if (!this.hasSubscribers()) { this.oldValue = this.getValue(); this.disposeHandler = this.handler.subscribe(this.element, this.notify.bind(this)); } this.addSubscriber(context, callable); }; ValueAttributeObserver.prototype.unsubscribe = function unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.disposeHandler(); this.disposeHandler = null; } }; var _ValueAttributeObserver = ValueAttributeObserver; ValueAttributeObserver = subscriberCollection()(ValueAttributeObserver) || ValueAttributeObserver; return ValueAttributeObserver; })(); exports.ValueAttributeObserver = ValueAttributeObserver; var selectArrayContext = 'SelectValueObserver:array'; var SelectValueObserver = (function () { function SelectValueObserver(element, handler, observerLocator) { _classCallCheck(this, _SelectValueObserver); this.element = element; this.handler = handler; this.observerLocator = observerLocator; } SelectValueObserver.prototype.getValue = function getValue() { return this.value; }; SelectValueObserver.prototype.setValue = function setValue(newValue) { if (newValue !== null && newValue !== undefined && this.element.multiple && !Array.isArray(newValue)) { throw new Error('Only null or Array instances can be bound to a multi-select.'); } if (this.value === newValue) { return; } if (this.arrayObserver) { this.arrayObserver.unsubscribe(selectArrayContext, this); this.arrayObserver = null; } if (Array.isArray(newValue)) { this.arrayObserver = this.observerLocator.getArrayObserver(newValue); this.arrayObserver.subscribe(selectArrayContext, this); } this.value = newValue; this.synchronizeOptions(); if (this.element.options.length > 0 && !this.initialSync) { this.initialSync = true; this.observerLocator.taskQueue.queueMicroTask(this); } }; SelectValueObserver.prototype.call = function call(context, splices) { this.synchronizeOptions(); }; SelectValueObserver.prototype.synchronizeOptions = function synchronizeOptions() { var value = this.value, i, options, option, optionValue, clear, isArray; if (value === null || value === undefined) { clear = true; } else if (Array.isArray(value)) { isArray = true; } options = this.element.options; i = options.length; while (i--) { option = options.item(i); if (clear) { option.selected = false; continue; } optionValue = option.hasOwnProperty('model') ? option.model : option.value; if (isArray) { option.selected = value.indexOf(optionValue) !== -1; continue; } option.selected = value === optionValue; } }; SelectValueObserver.prototype.synchronizeValue = function synchronizeValue() { var options = this.element.options, option, i, ii, count = 0, value = []; for (i = 0, ii = options.length; i < ii; i++) { option = options.item(i); if (!option.selected) { continue; } value[count] = option.hasOwnProperty('model') ? option.model : option.value; count++; } if (!this.element.multiple) { if (count === 0) { value = null; } else { value = value[0]; } } this.oldValue = this.value; this.value = value; this.notify(); }; SelectValueObserver.prototype.notify = function notify() { var oldValue = this.oldValue; var newValue = this.value; this.callSubscribers(newValue, oldValue); }; SelectValueObserver.prototype.subscribe = function subscribe(context, callable) { if (!this.hasSubscribers()) { this.disposeHandler = this.handler.subscribe(this.element, this.synchronizeValue.bind(this, false)); } this.addSubscriber(context, callable); }; SelectValueObserver.prototype.unsubscribe = function unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.disposeHandler(); this.disposeHandler = null; } }; SelectValueObserver.prototype.bind = function bind() { var _this3 = this; this.domObserver = _aureliaPal.DOM.createMutationObserver(function () { _this3.synchronizeOptions(); _this3.synchronizeValue(); }); this.domObserver.observe(this.element, { childList: true, subtree: true }); }; SelectValueObserver.prototype.unbind = function unbind() { this.domObserver.disconnect(); this.domObserver = null; if (this.arrayObserver) { this.arrayObserver.unsubscribe(selectArrayContext, this); this.arrayObserver = null; } }; var _SelectValueObserver = SelectValueObserver; SelectValueObserver = subscriberCollection()(SelectValueObserver) || SelectValueObserver; return SelectValueObserver; })(); exports.SelectValueObserver = SelectValueObserver; var checkedArrayContext = 'CheckedObserver:array'; var CheckedObserver = (function () { function CheckedObserver(element, handler, observerLocator) { _classCallCheck(this, _CheckedObserver); this.element = element; this.handler = handler; this.observerLocator = observerLocator; } CheckedObserver.prototype.getValue = function getValue() { return this.value; }; CheckedObserver.prototype.setValue = function setValue(newValue) { if (this.value === newValue) { return; } if (this.arrayObserver) { this.arrayObserver.unsubscribe(checkedArrayContext, this); this.arrayObserver = null; } if (this.element.type === 'checkbox' && Array.isArray(newValue)) { this.arrayObserver = this.observerLocator.getArrayObserver(newValue); this.arrayObserver.subscribe(checkedArrayContext, this); } this.value = newValue; this.synchronizeElement(); if (!this.element.hasOwnProperty('model') && !this.initialSync) { this.initialSync = true; this.observerLocator.taskQueue.queueMicroTask(this); } }; CheckedObserver.prototype.call = function call(context, splices) { this.synchronizeElement(); }; CheckedObserver.prototype.synchronizeElement = function synchronizeElement() { var value = this.value, element = this.element, elementValue = element.hasOwnProperty('model') ? element.model : element.value, isRadio = element.type === 'radio'; element.checked = isRadio && value === elementValue || !isRadio && value === true || !isRadio && Array.isArray(value) && value.indexOf(elementValue) !== -1; }; CheckedObserver.prototype.synchronizeValue = function synchronizeValue() { var value = this.value, element = this.element, elementValue = element.hasOwnProperty('model') ? element.model : element.value, index; if (element.type === 'checkbox') { if (Array.isArray(value)) { index = value.indexOf(elementValue); if (element.checked && index === -1) { value.push(elementValue); } else if (!element.checked && index !== -1) { value.splice(index, 1); } return; } else { value = element.checked; } } else if (element.checked) { value = elementValue; } else { return; } this.oldValue = this.value; this.value = value; this.notify(); }; CheckedObserver.prototype.notify = function notify() { var oldValue = this.oldValue; var newValue = this.value; this.callSubscribers(newValue, oldValue); }; CheckedObserver.prototype.subscribe = function subscribe(context, callable) { if (!this.hasSubscribers()) { this.disposeHandler = this.handler.subscribe(this.element, this.synchronizeValue.bind(this, false)); } this.addSubscriber(context, callable); }; CheckedObserver.prototype.unsubscribe = function unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.disposeHandler(); this.disposeHandler = null; } }; CheckedObserver.prototype.unbind = function unbind() { if (this.arrayObserver) { this.arrayObserver.unsubscribe(checkedArrayContext, this); this.arrayObserver = null; } }; var _CheckedObserver = CheckedObserver; CheckedObserver = subscriberCollection()(CheckedObserver) || CheckedObserver; return CheckedObserver; })(); exports.CheckedObserver = CheckedObserver; var ClassObserver = (function () { function ClassObserver(element) { _classCallCheck(this, ClassObserver); this.element = element; this.doNotCache = true; this.value = ''; this.version = 0; } ClassObserver.prototype.getValue = function getValue() { return this.value; }; ClassObserver.prototype.setValue = function setValue(newValue) { var nameIndex = this.nameIndex || {}, version = this.version, names, name; if (newValue !== null && newValue !== undefined && newValue.length) { names = newValue.split(' '); for (var i = 0, _length = names.length; i < _length; i++) { name = names[i]; if (name === '') { continue; } nameIndex[name] = version; this.element.classList.add(name); } } this.value = newValue; this.nameIndex = nameIndex; this.version += 1; if (version === 0) { return; } version -= 1; for (name in nameIndex) { if (!nameIndex.hasOwnProperty(name) || nameIndex[name] !== version) { continue; } this.element.classList.remove(name); } }; ClassObserver.prototype.subscribe = function subscribe() { throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "class" property is not supported.'); }; return ClassObserver; })(); exports.ClassObserver = ClassObserver; var computedContext = 'ComputedPropertyObserver'; var ComputedPropertyObserver = (function () { function ComputedPropertyObserver(obj, propertyName, descriptor, observerLocator) { _classCallCheck(this, _ComputedPropertyObserver); this.obj = obj; this.propertyName = propertyName; this.descriptor = descriptor; this.observerLocator = observerLocator; } ComputedPropertyObserver.prototype.getValue = function getValue() { return this.obj[this.propertyName]; }; ComputedPropertyObserver.prototype.setValue = function setValue(newValue) { this.obj[this.propertyName] = newValue; }; ComputedPropertyObserver.prototype.call = function call(context) { var newValue = this.getValue(); if (this.oldValue === newValue) return; this.callSubscribers(newValue, this.oldValue); this.oldValue = newValue; return; }; ComputedPropertyObserver.prototype.subscribe = function subscribe(context, callable) { if (!this.hasSubscribers()) { this.oldValue = this.getValue(); var dependencies = this.descriptor.get.dependencies; this.observers = []; for (var i = 0, ii = dependencies.length; i < ii; i++) { var observer = this.observerLocator.getObserver(this.obj, dependencies[i]); this.observers.push(observer); observer.subscribe(computedContext, this); } } this.addSubscriber(context, callable); }; ComputedPropertyObserver.prototype.unsubscribe = function unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.oldValue = undefined; var i = this.observers.length; while (i--) { this.observers[i].unsubscribe(computedContext, this); } this.observers = null; } }; var _ComputedPropertyObserver = ComputedPropertyObserver; ComputedPropertyObserver = subscriberCollection()(ComputedPropertyObserver) || ComputedPropertyObserver; return ComputedPropertyObserver; })(); exports.ComputedPropertyObserver = ComputedPropertyObserver; function hasDeclaredDependencies(descriptor) { return descriptor && descriptor.get && descriptor.get.dependencies && descriptor.get.dependencies.length > 0; } function declarePropertyDependencies(ctor, propertyName, dependencies) { var descriptor = Object.getOwnPropertyDescriptor(ctor.prototype, propertyName); descriptor.get.dependencies = dependencies; } function computedFrom() { for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) { rest[_key] = arguments[_key]; } return function (target, key, descriptor) { descriptor.get.dependencies = rest; return descriptor; }; } var elements = { a: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'target', 'transform', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], altGlyph: ['class', 'dx', 'dy', 'externalResourcesRequired', 'format', 'glyphRef', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], altGlyphDef: ['id', 'xml:base', 'xml:lang', 'xml:space'], altGlyphItem: ['id', 'xml:base', 'xml:lang', 'xml:space'], animate: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], animateColor: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], animateMotion: ['accumulate', 'additive', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keyPoints', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'origin', 'path', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'rotate', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], animateTransform: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'type', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], circle: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'r', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], clipPath: ['class', 'clipPathUnits', 'externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], 'color-profile': ['id', 'local', 'name', 'rendering-intent', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], cursor: ['externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], defs: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], desc: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'], ellipse: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], feBlend: ['class', 'height', 'id', 'in', 'in2', 'mode', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feColorMatrix: ['class', 'height', 'id', 'in', 'result', 'style', 'type', 'values', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feComponentTransfer: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feComposite: ['class', 'height', 'id', 'in', 'in2', 'k1', 'k2', 'k3', 'k4', 'operator', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feConvolveMatrix: ['bias', 'class', 'divisor', 'edgeMode', 'height', 'id', 'in', 'kernelMatrix', 'kernelUnitLength', 'order', 'preserveAlpha', 'result', 'style', 'targetX', 'targetY', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feDiffuseLighting: ['class', 'diffuseConstant', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feDisplacementMap: ['class', 'height', 'id', 'in', 'in2', 'result', 'scale', 'style', 'width', 'x', 'xChannelSelector', 'xml:base', 'xml:lang', 'xml:space', 'y', 'yChannelSelector'], feDistantLight: ['azimuth', 'elevation', 'id', 'xml:base', 'xml:lang', 'xml:space'], feFlood: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feFuncA: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], feFuncB: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], feFuncG: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], feFuncR: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], feGaussianBlur: ['class', 'height', 'id', 'in', 'result', 'stdDeviation', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feImage: ['class', 'externalResourcesRequired', 'height', 'id', 'preserveAspectRatio', 'result', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], feMerge: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feMergeNode: ['id', 'xml:base', 'xml:lang', 'xml:space'], feMorphology: ['class', 'height', 'id', 'in', 'operator', 'radius', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feOffset: ['class', 'dx', 'dy', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], fePointLight: ['id', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'], feSpecularLighting: ['class', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'specularConstant', 'specularExponent', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feSpotLight: ['id', 'limitingConeAngle', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'specularExponent', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'], feTile: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feTurbulence: ['baseFrequency', 'class', 'height', 'id', 'numOctaves', 'result', 'seed', 'stitchTiles', 'style', 'type', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], filter: ['class', 'externalResourcesRequired', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], font: ['class', 'externalResourcesRequired', 'horiz-adv-x', 'horiz-origin-x', 'horiz-origin-y', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'], 'font-face': ['accent-height', 'alphabetic', 'ascent', 'bbox', 'cap-height', 'descent', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'hanging', 'id', 'ideographic', 'mathematical', 'overline-position', 'overline-thickness', 'panose-1', 'slope', 'stemh', 'stemv', 'strikethrough-position', 'strikethrough-thickness', 'underline-position', 'underline-thickness', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'widths', 'x-height', 'xml:base', 'xml:lang', 'xml:space'], 'font-face-format': ['id', 'string', 'xml:base', 'xml:lang', 'xml:space'], 'font-face-name': ['id', 'name', 'xml:base', 'xml:lang', 'xml:space'], 'font-face-src': ['id', 'xml:base', 'xml:lang', 'xml:space'], 'font-face-uri': ['id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], foreignObject: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], g: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], glyph: ['arabic-form', 'class', 'd', 'glyph-name', 'horiz-adv-x', 'id', 'lang', 'orientation', 'style', 'unicode', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'], glyphRef: ['class', 'dx', 'dy', 'format', 'glyphRef', 'id', 'style', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], hkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space'], image: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], line: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'], linearGradient: ['class', 'externalResourcesRequired', 'gradientTransform', 'gradientUnits', 'id', 'spreadMethod', 'style', 'x1', 'x2', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'], marker: ['class', 'externalResourcesRequired', 'id', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'], mask: ['class', 'externalResourcesRequired', 'height', 'id', 'maskContentUnits', 'maskUnits', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], metadata: ['id', 'xml:base', 'xml:lang', 'xml:space'], 'missing-glyph': ['class', 'd', 'horiz-adv-x', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'], mpath: ['externalResourcesRequired', 'id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], path: ['class', 'd', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'pathLength', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], pattern: ['class', 'externalResourcesRequired', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], polygon: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], polyline: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], radialGradient: ['class', 'cx', 'cy', 'externalResourcesRequired', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'spreadMethod', 'style', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], rect: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], script: ['externalResourcesRequired', 'id', 'type', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], set: ['attributeName', 'attributeType', 'begin', 'dur', 'end', 'externalResourcesRequired', 'fill', 'id', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], stop: ['class', 'id', 'offset', 'style', 'xml:base', 'xml:lang', 'xml:space'], style: ['id', 'media', 'title', 'type', 'xml:base', 'xml:lang', 'xml:space'], svg: ['baseProfile', 'class', 'contentScriptType', 'contentStyleType', 'externalResourcesRequired', 'height', 'id', 'onabort', 'onactivate', 'onclick', 'onerror', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onresize', 'onscroll', 'onunload', 'onzoom', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'version', 'viewBox', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'zoomAndPan'], 'switch': ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], symbol: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'], text: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'transform', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], textPath: ['class', 'externalResourcesRequired', 'id', 'lengthAdjust', 'method', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'textLength', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], title: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'], tref: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], tspan: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], use: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], view: ['externalResourcesRequired', 'id', 'preserveAspectRatio', 'viewBox', 'viewTarget', 'xml:base', 'xml:lang', 'xml:space', 'zoomAndPan'], vkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space'] }; exports.elements = elements; var presentationElements = { 'a': true, 'altGlyph': true, 'animate': true, 'animateColor': true, 'circle': true, 'clipPath': true, 'defs': true, 'ellipse': true, 'feBlend': true, 'feColorMatrix': true, 'feComponentTransfer': true, 'feComposite': true, 'feConvolveMatrix': true, 'feDiffuseLighting': true, 'feDisplacementMap': true, 'feFlood': true, 'feGaussianBlur': true, 'feImage': true, 'feMerge': true, 'feMorphology': true, 'feOffset': true, 'feSpecularLighting': true, 'feTile': true, 'feTurbulence': true, 'filter': true, 'font': true, 'foreignObject': true, 'g': true, 'glyph': true, 'glyphRef': true, 'image': true, 'line': true, 'linearGradient': true, 'marker': true, 'mask': true, 'missing-glyph': true, 'path': true, 'pattern': true, 'polygon': true, 'polyline': true, 'radialGradient': true, 'rect': true, 'stop': true, 'svg': true, 'switch': true, 'symbol': true, 'text': true, 'textPath': true, 'tref': true, 'tspan': true, 'use': true }; exports.presentationElements = presentationElements; var presentationAttributes = { 'alignment-baseline': true, 'baseline-shift': true, 'clip-path': true, 'clip-rule': true, 'clip': true, 'color-interpolation-filters': true, 'color-interpolation': true, 'color-profile': true, 'color-rendering': true, 'color': true, 'cursor': true, 'direction': true, 'display': true, 'dominant-baseline': true, 'enable-background': true, 'fill-opacity': true, 'fill-rule': true, 'fill': true, 'filter': true, 'flood-color': true, 'flood-opacity': true, 'font-family': true, 'font-size-adjust': true, 'font-size': true, 'font-stretch': true, 'font-style': true, 'font-variant': true, 'font-weight': true, 'glyph-orientation-horizontal': true, 'glyph-orientation-vertical': true, 'image-rendering': true, 'kerning': true, 'letter-spacing': true, 'lighting-color': true, 'marker-end': true, 'marker-mid': true, 'marker-start': true, 'mask': true, 'opacity': true, 'overflow': true, 'pointer-events': true, 'shape-rendering': true, 'stop-color': true, 'stop-opacity': true, 'stroke-dasharray': true, 'stroke-dashoffset': true, 'stroke-linecap': true, 'stroke-linejoin': true, 'stroke-miterlimit': true, 'stroke-opacity': true, 'stroke-width': true, 'stroke': true, 'text-anchor': true, 'text-decoration': true, 'text-rendering': true, 'unicode-bidi': true, 'visibility': true, 'word-spacing': true, 'writing-mode': true }; exports.presentationAttributes = presentationAttributes; function createElement(html) { var div = _aureliaPal.DOM.createElement('div'); div.innerHTML = html; return div.firstChild; } var SVGAnalyzer = (function () { function SVGAnalyzer() { _classCallCheck(this, SVGAnalyzer); if (createElement('<svg><altGlyph /></svg>').firstElementChild.nodeName === 'altglyph' && elements.altGlyph) { elements.altglyph = elements.altGlyph; delete elements.altGlyph; elements.altglyphdef = elements.altGlyphDef; delete elements.altGlyphDef; elements.altglyphitem = elements.altGlyphItem; delete elements.altGlyphItem; elements.glyphref = elements.glyphRef; delete elements.glyphRef; } } SVGAnalyzer.prototype.isStandardSvgAttribute = function isStandardSvgAttribute(nodeName, attributeName) { return presentationElements[nodeName] && presentationAttributes[attributeName] || elements[nodeName] && elements[nodeName].indexOf(attributeName) !== -1; }; return SVGAnalyzer; })(); exports.SVGAnalyzer = SVGAnalyzer; var ObserverLocator = (function () { _createClass(ObserverLocator, null, [{ key: 'inject', value: [_aureliaTaskQueue.TaskQueue, EventManager, DirtyChecker, SVGAnalyzer], enumerable: true }]); function ObserverLocator(taskQueue, eventManager, dirtyChecker, svgAnalyzer) { _classCallCheck(this, ObserverLocator); this.taskQueue = taskQueue; this.eventManager = eventManager; this.dirtyChecker = dirtyChecker; this.svgAnalyzer = svgAnalyzer; this.adapters = []; } ObserverLocator.prototype.getObserver = function getObserver(obj, propertyName) { var observersLookup = obj.__observers__; var observer = undefined; if (observersLookup && propertyName in observersLookup) { return observersLookup[propertyName]; } observer = this.createPropertyObserver(obj, propertyName); if (!observer.doNotCache) { if (observersLookup === undefined) { observersLookup = this.getOrCreateObserversLookup(obj); } observersLookup[propertyName] = observer; } return observer; }; ObserverLocator.prototype.getOrCreateObserversLookup = function getOrCreateObserversLookup(obj) { return obj.__observers__ || this.createObserversLookup(obj); }; ObserverLocator.prototype.createObserversLookup = function createObserversLookup(obj) { var value = {}; try { Object.defineProperty(obj, "__observers__", { enumerable: false, configurable: false, writable: false, value: value }); } catch (_) {} return value; }; ObserverLocator.prototype.addAdapter = function addAdapter(adapter) { this.adapters.push(adapter); }; ObserverLocator.prototype.getAdapterObserver = function getAdapterObserver(obj, propertyName, descriptor) { for (var i = 0, ii = this.adapters.length; i < ii; i++) { var adapter = this.adapters[i]; var observer = adapter.getObserver(obj, propertyName, descriptor); if (observer) { return observer; } } return null; }; ObserverLocator.prototype.createPropertyObserver = function createPropertyObserver(obj, propertyName) { var observerLookup = undefined; var descriptor = undefined; var handler = undefined; var xlinkResult = undefined; if (!(obj instanceof Object)) { return new PrimitiveObserver(obj, propertyName); } if (obj instanceof _aureliaPal.DOM.Element) { if (propertyName === 'class') { return new ClassObserver(obj); } if (propertyName === 'style' || propertyName === 'css') { return new StyleObserver(obj, propertyName); } handler = this.eventManager.getElementHandler(obj, propertyName); if (propertyName === 'value' && obj.tagName.toLowerCase() === 'select') { return new SelectValueObserver(obj, handler, this); } if (propertyName === 'checked' && obj.tagName.toLowerCase() === 'input') { return new CheckedObserver(obj, handler, this); } if (handler) { return new ValueAttributeObserver(obj, propertyName, handler); } xlinkResult = /^xlink:(.+)$/.exec(propertyName); if (xlinkResult) { return new XLinkAttributeObserver(obj, propertyName, xlinkResult[1]); } if (/^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof _aureliaPal.DOM.SVGElement && this.svgAnalyzer.isStandardSvgAttribute(obj.nodeName, propertyName)) { return new DataAttributeObserver(obj, propertyName); } } descriptor = Object.getPropertyDescriptor(obj, propertyName); if (hasDeclaredDependencies(descriptor)) { return new ComputedPropertyObserver(obj, propertyName, descriptor, this); } var existingGetterOrSetter = undefined; if (descriptor && (existingGetterOrSetter = descriptor.get || descriptor.set)) { if (existingGetterOrSetter.getObserver) { return existingGetterOrSetter.getObserver(obj); } var adapterObserver = this.getAdapterObserver(obj, propertyName, descriptor); if (adapterObserver) { return adapterObserver; } return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } if (obj instanceof Array) { if (propertyName === 'length') { return this.getArrayObserver(obj).getLengthObserver(); } else { return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } } else if (obj instanceof Map) { if (propertyName === 'size') { return this.getMapObserver(obj).getLengthObserver(); } else { return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } } return new SetterObserver(this.taskQueue, obj, propertyName); }; ObserverLocator.prototype.getArrayObserver = function getArrayObserver(array) { if ('__array_observer__' in array) { return array.__array_observer__; } return array.__array_observer__ = _getArrayObserver(this.taskQueue, array); }; ObserverLocator.prototype.getMapObserver = function getMapObserver(map) { if ('__map_observer__' in map) { return map.__map_observer__; } return map.__map_observer__ = _getMapObserver(this.taskQueue, map); }; return ObserverLocator; })(); exports.ObserverLocator = ObserverLocator; var ObjectObservationAdapter = (function () { function ObjectObservationAdapter() { _classCallCheck(this, ObjectObservationAdapter); } ObjectObservationAdapter.prototype.getObserver = function getObserver(object, propertyName, descriptor) { throw new Error('BindingAdapters must implement getObserver(object, propertyName).'); }; return ObjectObservationAdapter; })(); exports.ObjectObservationAdapter = ObjectObservationAdapter; var BindingExpression = (function () { function BindingExpression(observerLocator, targetProperty, sourceExpression, mode, lookupFunctions, attribute) { _classCallCheck(this, BindingExpression); this.observerLocator = observerLocator; this.targetProperty = targetProperty; this.sourceExpression = sourceExpression; this.mode = mode; this.lookupFunctions = lookupFunctions; this.attribute = attribute; this.discrete = false; } BindingExpression.prototype.createBinding = function createBinding(target) { return new Binding(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.mode, this.lookupFunctions); }; return BindingExpression; })(); exports.BindingExpression = BindingExpression; var targetContext = 'Binding:target'; var Binding = (function () { function Binding(observerLocator, sourceExpression, target, targetProperty, mode, lookupFunctions) { _classCallCheck(this, _Binding); this.observerLocator = observerLocator; this.sourceExpression = sourceExpression; this.targetProperty = observerLocator.getObserver(target, targetProperty); this.mode = mode; this.lookupFunctions = lookupFunctions; } Binding.prototype.updateTarget = function updateTarget(value) { this.targetProperty.setValue(value); }; Binding.prototype.updateSource = function updateSource(value) { this.sourceExpression.assign(this.source, value, this.lookupFunctions); }; Binding.prototype.call = function call(context, newValue, oldValue) { if (!this.isBound) { return; } if (context === sourceContext) { oldValue = this.targetProperty.getValue(); newValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions); if (newValue !== oldValue) { this.updateTarget(newValue); } if (this.mode !== bindingMode.oneTime) { this._version++; this.sourceExpression.connect(this, this.source); this.unobserve(false); } return; } if (context === targetContext) { this.updateSource(newValue); return; } throw new Error('Unexpected call context ' + context); }; Binding.prototype.bind = function bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; var sourceExpression = this.sourceExpression; if (sourceExpression.bind) { sourceExpression.bind(this, source, this.lookupFunctions); } var targetProperty = this.targetProperty; if ('bind' in targetProperty) { targetProperty.bind(); } var value = sourceExpression.evaluate(source, this.lookupFunctions); this.updateTarget(value); var mode = this.mode; if (mode === bindingMode.oneWay || mode === bindingMode.twoWay) { sourceExpression.connect(this, source); if (mode === bindingMode.twoWay) { targetProperty.subscribe(targetContext, this); } } }; Binding.prototype.unbind = function unbind() { if (!this.isBound) { return; } this.isBound = false; if (this.sourceExpression.unbind) { this.sourceExpression.unbind(this, this.source); } this.source = null; if ('unbind' in this.targetProperty) { this.targetProperty.unbind(); } if (this.mode === bindingMode.twoWay) { this.targetProperty.unsubscribe(targetContext, this); } this.unobserve(true); }; var _Binding = Binding; Binding = connectable()(Binding) || Binding; return Binding; })(); exports.Binding = Binding; var CallExpression = (function () { function CallExpression(observerLocator, targetProperty, sourceExpression, lookupFunctions) { _classCallCheck(this, CallExpression); this.observerLocator = observerLocator; this.targetProperty = targetProperty; this.sourceExpression = sourceExpression; this.lookupFunctions = lookupFunctions; } CallExpression.prototype.createBinding = function createBinding(target) { return new Call(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.lookupFunctions); }; return CallExpression; })(); exports.CallExpression = CallExpression; var Call = (function () { function Call(observerLocator, sourceExpression, target, targetProperty, lookupFunctions) { _classCallCheck(this, Call); this.sourceExpression = sourceExpression; this.target = target; this.targetProperty = observerLocator.getObserver(target, targetProperty); this.lookupFunctions = lookupFunctions; } Call.prototype.callSource = function callSource($event) { var overrideContext = this.source.overrideContext; Object.assign(overrideContext, $event); overrideContext.$event = $event; var mustEvaluate = true; var result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate); delete overrideContext.$event; for (var prop in $event) { delete overrideContext[prop]; } return result; }; Call.prototype.bind = function bind(source) { var _this4 = this; if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; var sourceExpression = this.sourceExpression; if (sourceExpression.bind) { sourceExpression.bind(this, source, this.lookupFunctions); } this.targetProperty.setValue(function ($event) { return _this4.callSource($event); }); }; Call.prototype.unbind = function unbind() { if (!this.isBound) { return; } this.isBound = false; if (this.sourceExpression.unbind) { this.sourceExpression.unbind(this, this.source); } this.source = null; this.targetProperty.setValue(null); }; return Call; })(); exports.Call = Call; var ValueConverterResource = (function () { function ValueConverterResource(name) { _classCallCheck(this, ValueConverterResource); this.name = name; } ValueConverterResource.convention = function convention(name) { if (name.endsWith('ValueConverter')) { return new ValueConverterResource(camelCase(name.substring(0, name.length - 14))); } }; ValueConverterResource.prototype.initialize = function initialize(container, target) { this.instance = container.get(target); }; ValueConverterResource.prototype.register = function register(registry, name) { registry.registerValueConverter(name || this.name, this.instance); }; ValueConverterResource.prototype.load = function load(container, target) {}; return ValueConverterResource; })(); exports.ValueConverterResource = ValueConverterResource; function valueConverter(nameOrTarget) { if (nameOrTarget === undefined || typeof nameOrTarget === 'string') { return function (target) { _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ValueConverterResource(nameOrTarget), target); }; } _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ValueConverterResource(), nameOrTarget); } var BindingBehaviorResource = (function () { function BindingBehaviorResource(name) { _classCallCheck(this, BindingBehaviorResource); this.name = name; } BindingBehaviorResource.convention = function convention(name) { if (name.endsWith('BindingBehavior')) { return new BindingBehaviorResource(camelCase(name.substring(0, name.length - 15))); } }; BindingBehaviorResource.prototype.initialize = function initialize(container, target) { this.instance = container.get(target); }; BindingBehaviorResource.prototype.register = function register(registry, name) { registry.registerBindingBehavior(name || this.name, this.instance); }; BindingBehaviorResource.prototype.load = function load(container, target) {}; return BindingBehaviorResource; })(); exports.BindingBehaviorResource = BindingBehaviorResource; function bindingBehavior(nameOrTarget) { if (nameOrTarget === undefined || typeof nameOrTarget === 'string') { return function (target) { _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new BindingBehaviorResource(nameOrTarget), target); }; } _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new BindingBehaviorResource(), nameOrTarget); } var ListenerExpression = (function () { function ListenerExpression(eventManager, targetEvent, sourceExpression, delegate, preventDefault, lookupFunctions) { _classCallCheck(this, ListenerExpression); this.eventManager = eventManager; this.targetEvent = targetEvent; this.sourceExpression = sourceExpression; this.delegate = delegate; this.discrete = true; this.preventDefault = preventDefault; this.lookupFunctions = lookupFunctions; } ListenerExpression.prototype.createBinding = function createBinding(target) { return new Listener(this.eventManager, this.targetEvent, this.delegate, this.sourceExpression, target, this.preventDefault, this.lookupFunctions); }; return ListenerExpression; })(); exports.ListenerExpression = ListenerExpression; var Listener = (function () { function Listener(eventManager, targetEvent, delegate, sourceExpression, target, preventDefault, lookupFunctions) { _classCallCheck(this, Listener); this.eventManager = eventManager; this.targetEvent = targetEvent; this.delegate = delegate; this.sourceExpression = sourceExpression; this.target = target; this.preventDefault = preventDefault; this.lookupFunctions = lookupFunctions; } Listener.prototype.callSource = function callSource(event) { var overrideContext = this.source.overrideContext; overrideContext.$event = event; var mustEvaluate = true; var result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate); delete overrideContext.$event; if (result !== true && this.preventDefault) { event.preventDefault(); } return result; }; Listener.prototype.bind = function bind(source) { var _this5 = this; if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; var sourceExpression = this.sourceExpression; if (sourceExpression.bind) { sourceExpression.bind(this, source, this.lookupFunctions); } this._disposeListener = this.eventManager.addEventListener(this.target, this.targetEvent, function (event) { return _this5.callSource(event); }, this.delegate); }; Listener.prototype.unbind = function unbind() { if (!this.isBound) { return; } this.isBound = false; if (this.sourceExpression.unbind) { this.sourceExpression.unbind(this, this.source); } this.source = null; this._disposeListener(); this._disposeListener = null; }; return Listener; })(); exports.Listener = Listener; function getAU(element) { var au = element.au; if (au === undefined) { throw new Error('No Aurelia APIs are defined for the referenced element.'); } return au; } var NameExpression = (function () { function NameExpression(property, apiName) { _classCallCheck(this, NameExpression); this.property = property; this.apiName = apiName; this.discrete = true; } NameExpression.prototype.createBinding = function createBinding(target) { return new NameBinder(this.property, NameExpression.locateAPI(target, this.apiName)); }; NameExpression.locateAPI = function locateAPI(element, apiName) { switch (apiName) { case 'element': return element; case 'controller': return getAU(element).controller; case 'view-model': return getAU(element).controller.viewModel; case 'view': return getAU(element).controller.view; default: var target = getAU(element)[apiName]; if (target === undefined) { throw new Error('Attempted to reference "' + apiName + '", but it was not found amongst the target\'s API.'); } return target.viewModel; } }; return NameExpression; })(); exports.NameExpression = NameExpression; var NameBinder = (function () { function NameBinder(property, target) { _classCallCheck(this, NameBinder); this.property = property; this.target = target; this.source = null; this.context = null; } NameBinder.prototype.bind = function bind(source) { if (this.source !== null) { if (this.source === source) { return; } this.unbind(); } this.source = source || null; this.context = source.bindingContext || source.overrideContext || null; if (this.context !== null) { this.context[this.property] = this.target; } }; NameBinder.prototype.unbind = function unbind() { if (this.source !== null) { this.source = null; } if (this.context !== null) { this.context[this.property] = null; } }; return NameBinder; })(); var lookupFunctions = { bindingBehaviors: function bindingBehaviors(name) { return null; }, valueConverters: function valueConverters(name) { return null; } }; var BindingEngine = (function () { _createClass(BindingEngine, null, [{ key: 'inject', value: [ObserverLocator, Parser], enumerable: true }]); function BindingEngine(observerLocator, parser) { _classCallCheck(this, BindingEngine); this.observerLocator = observerLocator; this.parser = parser; } BindingEngine.prototype.createBindingExpression = function createBindingExpression(targetProperty, sourceExpression) { var mode = arguments.length <= 2 || arguments[2] === undefined ? bindingMode.oneWay : arguments[2]; var lookupFunctions = arguments.length <= 3 || arguments[3] === undefined ? lookupFunctions : arguments[3]; return (function () { return new BindingExpression(this.observerLocator, targetProperty, this.parser.parse(sourceExpression), mode, lookupFunctions); }).apply(this, arguments); }; BindingEngine.prototype.propertyObserver = function propertyObserver(obj, propertyName) { var _this6 = this; return { subscribe: function subscribe(callback) { var observer = _this6.observerLocator.getObserver(obj, propertyName); observer.subscribe(callback); return { dispose: function dispose() { return observer.unsubscribe(callback); } }; } }; }; BindingEngine.prototype.collectionObserver = function collectionObserver(collection) { var _this7 = this; return { subscribe: function subscribe(callback) { var observer = undefined; if (collection instanceof Array) { observer = _this7.observerLocator.getArrayObserver(collection); } else if (collection instanceof Map) { observer = _this7.observerLocator.getMapObserver(collection); } else { throw new Error('collection must be an instance of Array or Map.'); } observer.subscribe(callback); return { dispose: function dispose() { return observer.unsubscribe(callback); } }; } }; }; BindingEngine.prototype.expressionObserver = function expressionObserver(bindingContext, expression) { var scope = { bindingContext: bindingContext, overrideContext: createOverrideContext(bindingContext) }; return new ExpressionObserver(scope, this.parser.parse(expression), this.observerLocator); }; BindingEngine.prototype.parseExpression = function parseExpression(expression) { return this.parser.parse(expression); }; BindingEngine.prototype.registerAdapter = function registerAdapter(adapter) { this.observerLocator.addAdapter(adapter); }; return BindingEngine; })(); exports.BindingEngine = BindingEngine; var ExpressionObserver = (function () { function ExpressionObserver(scope, expression, observerLocator) { _classCallCheck(this, _ExpressionObserver); this.scope = scope; this.expression = expression; this.observerLocator = observerLocator; } ExpressionObserver.prototype.subscribe = function subscribe(callback) { var _this8 = this; if (!this.hasSubscribers()) { this.oldValue = this.expression.evaluate(this.scope, lookupFunctions); this.expression.connect(this, this.scope); } this.addSubscriber(callback); return { dispose: function dispose() { if (_this8.removeSubscriber(callback) && !_this8.hasSubscribers()) { _this8.unobserve(true); } } }; }; ExpressionObserver.prototype.call = function call() { var newValue = this.expression.evaluate(this.scope, lookupFunctions); var oldValue = this.oldValue; if (newValue !== oldValue) { this.oldValue = newValue; this.callSubscribers(newValue, oldValue); } this._version++; this.expression.connect(this, this.scope); this.unobserve(false); }; var _ExpressionObserver = ExpressionObserver; ExpressionObserver = subscriberCollection()(ExpressionObserver) || ExpressionObserver; ExpressionObserver = connectable()(ExpressionObserver) || ExpressionObserver; return ExpressionObserver; })(); }); define('aurelia-dependency-injection',['exports', 'core-js', 'aurelia-metadata', 'aurelia-pal'], function (exports, _coreJs, _aureliaMetadata, _aureliaPal) { exports.__esModule = true; var _classInvokers; 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; }; })(); exports.invoker = invoker; exports.factory = factory; exports.registration = registration; exports.transient = transient; exports.singleton = singleton; exports.autoinject = autoinject; exports.inject = inject; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var resolver = _aureliaMetadata.protocol.create('aurelia:resolver', function (target) { if (!(typeof target.get === 'function')) { return 'Resolvers must implement: get(container: Container, key: any): any'; } return true; }); exports.resolver = resolver; var Lazy = (function () { function Lazy(key) { _classCallCheck(this, _Lazy); this._key = key; } Lazy.prototype.get = function get(container) { var _this = this; return function () { return container.get(_this._key); }; }; Lazy.of = function of(key) { return new Lazy(key); }; var _Lazy = Lazy; Lazy = resolver()(Lazy) || Lazy; return Lazy; })(); exports.Lazy = Lazy; var All = (function () { function All(key) { _classCallCheck(this, _All); this._key = key; } All.prototype.get = function get(container) { return container.getAll(this._key); }; All.of = function of(key) { return new All(key); }; var _All = All; All = resolver()(All) || All; return All; })(); exports.All = All; var Optional = (function () { function Optional(key) { var checkParent = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; _classCallCheck(this, _Optional); this._key = key; this._checkParent = checkParent; } Optional.prototype.get = function get(container) { if (container.hasResolver(this._key, this._checkParent)) { return container.get(this._key); } return null; }; Optional.of = function of(key) { var checkParent = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return new Optional(key, checkParent); }; var _Optional = Optional; Optional = resolver()(Optional) || Optional; return Optional; })(); exports.Optional = Optional; var Parent = (function () { function Parent(key) { _classCallCheck(this, _Parent); this._key = key; } Parent.prototype.get = function get(container) { return container.parent ? container.parent.get(this._key) : null; }; Parent.of = function of(key) { return new Parent(key); }; var _Parent = Parent; Parent = resolver()(Parent) || Parent; return Parent; })(); exports.Parent = Parent; var StrategyResolver = (function () { function StrategyResolver(strategy, state) { _classCallCheck(this, _StrategyResolver); this.strategy = strategy; this.state = state; } StrategyResolver.prototype.get = function get(container, key) { switch (this.strategy) { case 0: return this.state; case 1: var singleton = container.invoke(this.state); this.state = singleton; this.strategy = 0; return singleton; case 2: return container.invoke(this.state); case 3: return this.state(container, key, this); case 4: return this.state[0].get(container, key); case 5: return container.get(this.state); default: throw new Error('Invalid strategy: ' + this.strategy); } }; var _StrategyResolver = StrategyResolver; StrategyResolver = resolver()(StrategyResolver) || StrategyResolver; return StrategyResolver; })(); exports.StrategyResolver = StrategyResolver; function invoker(value) { return function (target) { _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.invoker, value, target); }; } function factory(potentialTarget) { var deco = function deco(target) { _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.invoker, FactoryInvoker.instance, target); }; return potentialTarget ? deco(potentialTarget) : deco; } var FactoryInvoker = (function () { function FactoryInvoker() { _classCallCheck(this, FactoryInvoker); } FactoryInvoker.prototype.invoke = function invoke(container, fn, dependencies) { var i = dependencies.length; var args = new Array(i); while (i--) { args[i] = container.get(dependencies[i]); } return fn.apply(undefined, args); }; FactoryInvoker.prototype.invokeWithDynamicDependencies = function invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) { var i = staticDependencies.length; var args = new Array(i); while (i--) { args[i] = container.get(staticDependencies[i]); } if (dynamicDependencies !== undefined) { args = args.concat(dynamicDependencies); } return fn.apply(undefined, args); }; _createClass(FactoryInvoker, null, [{ key: 'instance', value: new FactoryInvoker(), enumerable: true }]); return FactoryInvoker; })(); exports.FactoryInvoker = FactoryInvoker; function registration(value) { return function (target) { _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.registration, value, target); }; } function transient(key) { return registration(new TransientRegistration(key)); } function singleton(keyOrRegisterInChild) { var registerInChild = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return registration(new SingletonRegistration(keyOrRegisterInChild, registerInChild)); } var TransientRegistration = (function () { function TransientRegistration(key) { _classCallCheck(this, TransientRegistration); this._key = key; } TransientRegistration.prototype.registerResolver = function registerResolver(container, key, fn) { var resolver = new StrategyResolver(2, fn); container.registerResolver(this._key || key, resolver); return resolver; }; return TransientRegistration; })(); exports.TransientRegistration = TransientRegistration; var SingletonRegistration = (function () { function SingletonRegistration(keyOrRegisterInChild) { var registerInChild = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; _classCallCheck(this, SingletonRegistration); if (typeof keyOrRegisterInChild === 'boolean') { this._registerInChild = keyOrRegisterInChild; } else { this._key = keyOrRegisterInChild; this._registerInChild = registerInChild; } } SingletonRegistration.prototype.registerResolver = function registerResolver(container, key, fn) { var resolver = new StrategyResolver(1, fn); if (this._registerInChild) { container.registerResolver(this._key || key, resolver); } else { container.root.registerResolver(this._key || key, resolver); } return resolver; }; return SingletonRegistration; })(); exports.SingletonRegistration = SingletonRegistration; var badKeyError = 'key/value cannot be null or undefined. Are you trying to inject/register something that doesn\'t exist with DI?'; var _emptyParameters = Object.freeze([]); exports._emptyParameters = _emptyParameters; _aureliaMetadata.metadata.registration = 'aurelia:registration'; _aureliaMetadata.metadata.invoker = 'aurelia:invoker'; var resolverDecorates = resolver.decorates; var InvocationHandler = (function () { function InvocationHandler(fn, invoker, dependencies) { _classCallCheck(this, InvocationHandler); this.fn = fn; this.invoker = invoker; this.dependencies = dependencies; } InvocationHandler.prototype.invoke = function invoke(container, dynamicDependencies) { return dynamicDependencies !== undefined ? this.invoker.invokeWithDynamicDependencies(container, this.fn, this.dependencies, dynamicDependencies) : this.invoker.invoke(container, this.fn, this.dependencies); }; return InvocationHandler; })(); exports.InvocationHandler = InvocationHandler; function invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) { var i = staticDependencies.length; var args = new Array(i); while (i--) { args[i] = container.get(staticDependencies[i]); } if (dynamicDependencies !== undefined) { args = args.concat(dynamicDependencies); } return Reflect.construct(fn, args); } var classInvokers = (_classInvokers = {}, _classInvokers[0] = { invoke: function invoke(container, Type) { return new Type(); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, _classInvokers[1] = { invoke: function invoke(container, Type, deps) { return new Type(container.get(deps[0])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, _classInvokers[2] = { invoke: function invoke(container, Type, deps) { return new Type(container.get(deps[0]), container.get(deps[1])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, _classInvokers[3] = { invoke: function invoke(container, Type, deps) { return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, _classInvokers[4] = { invoke: function invoke(container, Type, deps) { return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, _classInvokers[5] = { invoke: function invoke(container, Type, deps) { return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3]), container.get(deps[4])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, _classInvokers.fallback = { invoke: invokeWithDynamicDependencies, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, _classInvokers); var Container = (function () { function Container(configuration) { _classCallCheck(this, Container); if (!configuration) { configuration = {}; } this._configuration = configuration; this._onHandlerCreated = configuration.onHandlerCreated; this._handlers = configuration.handlers || (configuration.handlers = new Map()); this._resolvers = new Map(); this.root = this; this.parent = null; } Container.prototype.makeGlobal = function makeGlobal() { Container.instance = this; return this; }; Container.prototype.setHandlerCreatedCallback = function setHandlerCreatedCallback(onHandlerCreated) { this._onHandlerCreated = onHandlerCreated; this._configuration.onHandlerCreated = onHandlerCreated; }; Container.prototype.registerInstance = function registerInstance(key, instance) { this.registerResolver(key, new StrategyResolver(0, instance === undefined ? key : instance)); }; Container.prototype.registerSingleton = function registerSingleton(key, fn) { this.registerResolver(key, new StrategyResolver(1, fn === undefined ? key : fn)); }; Container.prototype.registerTransient = function registerTransient(key, fn) { this.registerResolver(key, new StrategyResolver(2, fn === undefined ? key : fn)); }; Container.prototype.registerHandler = function registerHandler(key, handler) { this.registerResolver(key, new StrategyResolver(3, handler)); }; Container.prototype.registerAlias = function registerAlias(originalKey, aliasKey) { this.registerResolver(aliasKey, new StrategyResolver(5, originalKey)); }; Container.prototype.registerResolver = function registerResolver(key, resolver) { if (key === null || key === undefined) { throw new Error(badKeyError); } var allResolvers = this._resolvers; var result = allResolvers.get(key); if (result === undefined) { allResolvers.set(key, resolver); } else if (result.strategy === 4) { result.state.push(resolver); } else { allResolvers.set(key, new StrategyResolver(4, [result, resolver])); } }; Container.prototype.autoRegister = function autoRegister(fn, key) { var resolver = undefined; if (typeof fn === 'function') { var _registration = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.registration, fn); if (_registration === undefined) { resolver = new StrategyResolver(1, fn); this.registerResolver(key === undefined ? fn : key, resolver); } else { resolver = _registration.registerResolver(this, key === undefined ? fn : key, fn); } } else { resolver = new StrategyResolver(0, fn); this.registerResolver(key === undefined ? fn : key, resolver); } return resolver; }; Container.prototype.autoRegisterAll = function autoRegisterAll(fns) { var i = fns.length; while (i--) { this.autoRegister(fns[i]); } }; Container.prototype.unregister = function unregister(key) { this._resolvers['delete'](key); }; Container.prototype.hasResolver = function hasResolver(key) { var checkParent = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (key === null || key === undefined) { throw new Error(badKeyError); } return this._resolvers.has(key) || checkParent && this.parent !== null && this.parent.hasResolver(key, checkParent); }; Container.prototype.get = function get(key) { if (key === null || key === undefined) { throw new Error(badKeyError); } if (key === Container) { return this; } if (resolverDecorates(key)) { return key.get(this, key); } var resolver = this._resolvers.get(key); if (resolver === undefined) { if (this.parent === null) { return this.autoRegister(key).get(this, key); } return this.parent._get(key); } return resolver.get(this, key); }; Container.prototype._get = function _get(key) { var resolver = this._resolvers.get(key); if (resolver === undefined) { if (this.parent === null) { return this.autoRegister(key).get(this, key); } return this.parent._get(key); } return resolver.get(this, key); }; Container.prototype.getAll = function getAll(key) { if (key === null || key === undefined) { throw new Error(badKeyError); } var resolver = this._resolvers.get(key); if (resolver === undefined) { if (this.parent === null) { return _emptyParameters; } return this.parent.getAll(key); } if (resolver.strategy === 4) { var state = resolver.state; var i = state.length; var results = new Array(i); while (i--) { results[i] = state[i].get(this, key); } return results; } return resolver.get(this, key); }; Container.prototype.createChild = function createChild() { var child = new Container(this._configuration); child.root = this.root; child.parent = this; return child; }; Container.prototype.invoke = function invoke(fn, dynamicDependencies) { try { var _handler = this._handlers.get(fn); if (_handler === undefined) { _handler = this._createInvocationHandler(fn); this._handlers.set(fn, _handler); } return _handler.invoke(this, dynamicDependencies); } catch (e) { throw new _aureliaPal.AggregateError('Error invoking ' + fn.name + '. Check the inner error for details.', e, true); } }; Container.prototype._createInvocationHandler = function _createInvocationHandler(fn) { var dependencies = undefined; if (typeof fn.inject === 'function') { dependencies = fn.inject(); } else if (fn.inject === undefined) { dependencies = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, fn) || _emptyParameters; } else { dependencies = fn.inject; } var invoker = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.invoker, fn) || classInvokers[dependencies.length] || classInvokers.fallback; var handler = new InvocationHandler(fn, invoker, dependencies); return this._onHandlerCreated !== undefined ? this._onHandlerCreated(handler) : handler; }; return Container; })(); exports.Container = Container; function autoinject(potentialTarget) { var deco = function deco(target) { target.inject = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, target) || _emptyParameters; }; return potentialTarget ? deco(potentialTarget) : deco; } function inject() { for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) { rest[_key] = arguments[_key]; } return function (target, key, descriptor) { if (descriptor) { var _fn = descriptor.value; _fn.inject = rest; } else { target.inject = rest; } }; } }); define('aurelia-templating',['exports', 'core-js', 'aurelia-logging', 'aurelia-metadata', 'aurelia-path', 'aurelia-loader', 'aurelia-pal', 'aurelia-binding', 'aurelia-dependency-injection', 'aurelia-task-queue'], function (exports, _coreJs, _aureliaLogging, _aureliaMetadata, _aureliaPath, _aureliaLoader, _aureliaPal, _aureliaBinding, _aureliaDependencyInjection, _aureliaTaskQueue) { exports.__esModule = true; 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; }; })(); exports._hyphenate = _hyphenate; exports.children = children; exports.child = child; exports.resource = resource; exports.behavior = behavior; exports.customElement = customElement; exports.customAttribute = customAttribute; exports.templateController = templateController; exports.bindable = bindable; exports.dynamicOptions = dynamicOptions; exports.useShadowDOM = useShadowDOM; exports.processContent = processContent; exports.containerless = containerless; exports.useViewStrategy = useViewStrategy; exports.useView = useView; exports.inlineView = inlineView; exports.noView = noView; exports.elementConfig = elementConfig; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var animationEvent = { enterBegin: 'animation:enter:begin', enterActive: 'animation:enter:active', enterDone: 'animation:enter:done', enterTimeout: 'animation:enter:timeout', leaveBegin: 'animation:leave:begin', leaveActive: 'animation:leave:active', leaveDone: 'animation:leave:done', leaveTimeout: 'animation:leave:timeout', staggerNext: 'animation:stagger:next', removeClassBegin: 'animation:remove-class:begin', removeClassActive: 'animation:remove-class:active', removeClassDone: 'animation:remove-class:done', removeClassTimeout: 'animation:remove-class:timeout', addClassBegin: 'animation:add-class:begin', addClassActive: 'animation:add-class:active', addClassDone: 'animation:add-class:done', addClassTimeout: 'animation:add-class:timeout', animateBegin: 'animation:animate:begin', animateActive: 'animation:animate:active', animateDone: 'animation:animate:done', animateTimeout: 'animation:animate:timeout', sequenceBegin: 'animation:sequence:begin', sequenceDone: 'animation:sequence:done' }; exports.animationEvent = animationEvent; var Animator = (function () { function Animator() { _classCallCheck(this, Animator); } Animator.prototype.enter = function enter(element) { return Promise.resolve(false); }; Animator.prototype.leave = function leave(element) { return Promise.resolve(false); }; Animator.prototype.removeClass = function removeClass(element, className) { element.classList.remove(className); return Promise.resolve(false); }; Animator.prototype.addClass = function addClass(element, className) { element.classList.add(className); return Promise.resolve(false); }; Animator.prototype.animate = function animate(element, className) { return Promise.resolve(false); }; Animator.prototype.runSequence = function runSequence(animations) {}; Animator.prototype.registerEffect = function registerEffect(effectName, properties) {}; Animator.prototype.unregisterEffect = function unregisterEffect(effectName) {}; return Animator; })(); exports.Animator = Animator; var capitalMatcher = /([A-Z])/g; function addHyphenAndLower(char) { return '-' + char.toLowerCase(); } function _hyphenate(name) { return (name.charAt(0).toLowerCase() + name.slice(1)).replace(capitalMatcher, addHyphenAndLower); } var ResourceLoadContext = (function () { function ResourceLoadContext() { _classCallCheck(this, ResourceLoadContext); this.dependencies = {}; } ResourceLoadContext.prototype.addDependency = function addDependency(url) { this.dependencies[url] = true; }; ResourceLoadContext.prototype.hasDependency = function hasDependency(url) { return url in this.dependencies; }; return ResourceLoadContext; })(); exports.ResourceLoadContext = ResourceLoadContext; var ViewCompileInstruction = (function () { _createClass(ViewCompileInstruction, null, [{ key: 'normal', value: new ViewCompileInstruction(), enumerable: true }]); function ViewCompileInstruction() { var targetShadowDOM = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; var compileSurrogate = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; _classCallCheck(this, ViewCompileInstruction); this.targetShadowDOM = targetShadowDOM; this.compileSurrogate = compileSurrogate; this.associatedModuleId = null; } return ViewCompileInstruction; })(); exports.ViewCompileInstruction = ViewCompileInstruction; var BehaviorInstruction = (function () { BehaviorInstruction.enhance = function enhance() { var instruction = new BehaviorInstruction(); instruction.enhance = true; return instruction; }; BehaviorInstruction.unitTest = function unitTest(type, attributes) { var instruction = new BehaviorInstruction(); instruction.type = type; instruction.attributes = attributes || {}; return instruction; }; BehaviorInstruction.element = function element(node, type) { var instruction = new BehaviorInstruction(); instruction.type = type; instruction.attributes = {}; instruction.anchorIsContainer = !(node.hasAttribute('containerless') || type.containerless); instruction.initiatedByBehavior = true; return instruction; }; BehaviorInstruction.attribute = function attribute(attrName, type) { var instruction = new BehaviorInstruction(); instruction.attrName = attrName; instruction.type = type || null; instruction.attributes = {}; return instruction; }; BehaviorInstruction.dynamic = function dynamic(host, viewModel, viewFactory) { var instruction = new BehaviorInstruction(); instruction.host = host; instruction.viewModel = viewModel; instruction.viewFactory = viewFactory; return instruction; }; _createClass(BehaviorInstruction, null, [{ key: 'normal', value: new BehaviorInstruction(), enumerable: true }]); function BehaviorInstruction() { _classCallCheck(this, BehaviorInstruction); this.initiatedByBehavior = false; this.enhance = false; this.partReplacements = null; this.viewFactory = null; this.originalAttrName = null; this.skipContentProcessing = false; this.contentFactory = null; this.viewModel = null; this.anchorIsContainer = false; this.host = null; this.attributes = null; this.type = null; this.attrName = null; } return BehaviorInstruction; })(); exports.BehaviorInstruction = BehaviorInstruction; var TargetInstruction = (function () { TargetInstruction.contentSelector = function contentSelector(node, parentInjectorId) { var instruction = new TargetInstruction(); instruction.parentInjectorId = parentInjectorId; instruction.contentSelector = true; instruction.selector = node.getAttribute('select'); return instruction; }; TargetInstruction.contentExpression = function contentExpression(expression) { var instruction = new TargetInstruction(); instruction.contentExpression = expression; return instruction; }; TargetInstruction.lifting = function lifting(parentInjectorId, liftingInstruction) { var instruction = new TargetInstruction(); instruction.parentInjectorId = parentInjectorId; instruction.expressions = TargetInstruction.noExpressions; instruction.behaviorInstructions = [liftingInstruction]; instruction.viewFactory = liftingInstruction.viewFactory; instruction.providers = [liftingInstruction.type.target]; return instruction; }; TargetInstruction.normal = function normal(injectorId, parentInjectorId, providers, behaviorInstructions, expressions, elementInstruction) { var instruction = new TargetInstruction(); instruction.injectorId = injectorId; instruction.parentInjectorId = parentInjectorId; instruction.providers = providers; instruction.behaviorInstructions = behaviorInstructions; instruction.expressions = expressions; instruction.anchorIsContainer = elementInstruction ? elementInstruction.anchorIsContainer : true; instruction.elementInstruction = elementInstruction; return instruction; }; TargetInstruction.surrogate = function surrogate(providers, behaviorInstructions, expressions, values) { var instruction = new TargetInstruction(); instruction.expressions = expressions; instruction.behaviorInstructions = behaviorInstructions; instruction.providers = providers; instruction.values = values; return instruction; }; _createClass(TargetInstruction, null, [{ key: 'noExpressions', value: Object.freeze([]), enumerable: true }]); function TargetInstruction() { _classCallCheck(this, TargetInstruction); this.injectorId = null; this.parentInjectorId = null; this.contentSelector = false; this.selector = null; this.contentExpression = null; this.expressions = null; this.behaviorInstructions = null; this.providers = null; this.viewFactory = null; this.anchorIsContainer = false; this.elementInstruction = null; this.values = null; } return TargetInstruction; })(); exports.TargetInstruction = TargetInstruction; var viewStrategy = _aureliaMetadata.protocol.create('aurelia:view-strategy', { validate: function validate(target) { if (!(typeof target.loadViewFactory === 'function')) { return 'View strategies must implement: loadViewFactory(viewEngine: ViewEngine, compileInstruction: ViewCompileInstruction, loadContext?: ResourceLoadContext): Promise<ViewFactory>'; } return true; }, compose: function compose(target) { if (!(typeof target.makeRelativeTo === 'function')) { target.makeRelativeTo = _aureliaPal.PLATFORM.noop; } } }); exports.viewStrategy = viewStrategy; var RelativeViewStrategy = (function () { function RelativeViewStrategy(path) { _classCallCheck(this, _RelativeViewStrategy); this.path = path; this.absolutePath = null; } RelativeViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext) { if (this.absolutePath === null && this.moduleId) { this.absolutePath = _aureliaPath.relativeToFile(this.path, this.moduleId); } compileInstruction.associatedModuleId = this.moduleId; return viewEngine.loadViewFactory(this.absolutePath || this.path, compileInstruction, loadContext); }; RelativeViewStrategy.prototype.makeRelativeTo = function makeRelativeTo(file) { if (this.absolutePath === null) { this.absolutePath = _aureliaPath.relativeToFile(this.path, file); } }; var _RelativeViewStrategy = RelativeViewStrategy; RelativeViewStrategy = viewStrategy()(RelativeViewStrategy) || RelativeViewStrategy; return RelativeViewStrategy; })(); exports.RelativeViewStrategy = RelativeViewStrategy; var ConventionalViewStrategy = (function () { function ConventionalViewStrategy(viewLocator, origin) { _classCallCheck(this, _ConventionalViewStrategy); this.moduleId = origin.moduleId; this.viewUrl = viewLocator.convertOriginToViewUrl(origin); } ConventionalViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext) { compileInstruction.associatedModuleId = this.moduleId; return viewEngine.loadViewFactory(this.viewUrl, compileInstruction, loadContext); }; var _ConventionalViewStrategy = ConventionalViewStrategy; ConventionalViewStrategy = viewStrategy()(ConventionalViewStrategy) || ConventionalViewStrategy; return ConventionalViewStrategy; })(); exports.ConventionalViewStrategy = ConventionalViewStrategy; var NoViewStrategy = (function () { function NoViewStrategy() { _classCallCheck(this, _NoViewStrategy); } NoViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext) { return Promise.resolve(null); }; var _NoViewStrategy = NoViewStrategy; NoViewStrategy = viewStrategy()(NoViewStrategy) || NoViewStrategy; return NoViewStrategy; })(); exports.NoViewStrategy = NoViewStrategy; var TemplateRegistryViewStrategy = (function () { function TemplateRegistryViewStrategy(moduleId, entry) { _classCallCheck(this, _TemplateRegistryViewStrategy); this.moduleId = moduleId; this.entry = entry; } TemplateRegistryViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext) { var entry = this.entry; if (entry.factoryIsReady) { return Promise.resolve(entry.factory); } compileInstruction.associatedModuleId = this.moduleId; return viewEngine.loadViewFactory(entry, compileInstruction, loadContext); }; var _TemplateRegistryViewStrategy = TemplateRegistryViewStrategy; TemplateRegistryViewStrategy = viewStrategy()(TemplateRegistryViewStrategy) || TemplateRegistryViewStrategy; return TemplateRegistryViewStrategy; })(); exports.TemplateRegistryViewStrategy = TemplateRegistryViewStrategy; var InlineViewStrategy = (function () { function InlineViewStrategy(markup, dependencies, dependencyBaseUrl) { _classCallCheck(this, _InlineViewStrategy); this.markup = markup; this.dependencies = dependencies || null; this.dependencyBaseUrl = dependencyBaseUrl || ''; } InlineViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext) { var entry = this.entry; var dependencies = this.dependencies; if (entry && entry.factoryIsReady) { return Promise.resolve(entry.factory); } this.entry = entry = new _aureliaLoader.TemplateRegistryEntry(this.moduleId || this.dependencyBaseUrl); entry.template = _aureliaPal.DOM.createTemplateFromMarkup(this.markup); if (dependencies !== null) { for (var i = 0, ii = dependencies.length; i < ii; ++i) { var current = dependencies[i]; if (typeof current === 'string' || typeof current === 'function') { entry.addDependency(current); } else { entry.addDependency(current.from, current.as); } } } compileInstruction.associatedModuleId = this.moduleId; return viewEngine.loadViewFactory(entry, compileInstruction, loadContext); }; var _InlineViewStrategy = InlineViewStrategy; InlineViewStrategy = viewStrategy()(InlineViewStrategy) || InlineViewStrategy; return InlineViewStrategy; })(); exports.InlineViewStrategy = InlineViewStrategy; var ViewLocator = (function () { function ViewLocator() { _classCallCheck(this, ViewLocator); } ViewLocator.prototype.getViewStrategy = function getViewStrategy(value) { if (!value) { return null; } if (typeof value === 'object' && 'getViewStrategy' in value) { var _origin = _aureliaMetadata.Origin.get(value.constructor); value = value.getViewStrategy(); if (typeof value === 'string') { value = new RelativeViewStrategy(value); } viewStrategy.assert(value); if (_origin) { value.makeRelativeTo(_origin.moduleId); } return value; } if (typeof value === 'string') { value = new RelativeViewStrategy(value); } if (viewStrategy.validate(value)) { return value; } if (typeof value !== 'function') { value = value.constructor; } var origin = _aureliaMetadata.Origin.get(value); var strategy = _aureliaMetadata.metadata.get(ViewLocator.viewStrategyMetadataKey, value); if (!strategy) { if (!origin) { throw new Error('Cannot determinte default view strategy for object.', value); } strategy = this.createFallbackViewStrategy(origin); } else if (origin) { strategy.moduleId = origin.moduleId; } return strategy; }; ViewLocator.prototype.createFallbackViewStrategy = function createFallbackViewStrategy(origin) { return new ConventionalViewStrategy(this, origin); }; ViewLocator.prototype.convertOriginToViewUrl = function convertOriginToViewUrl(origin) { var moduleId = origin.moduleId; var id = moduleId.endsWith('.js') || moduleId.endsWith('.ts') ? moduleId.substring(0, moduleId.length - 3) : moduleId; return id + '.html'; }; _createClass(ViewLocator, null, [{ key: 'viewStrategyMetadataKey', value: 'aurelia:view-strategy', enumerable: true }]); return ViewLocator; })(); exports.ViewLocator = ViewLocator; var BindingLanguage = (function () { function BindingLanguage() { _classCallCheck(this, BindingLanguage); } BindingLanguage.prototype.inspectAttribute = function inspectAttribute(resources, attrName, attrValue) { throw new Error('A BindingLanguage must implement inspectAttribute(...)'); }; BindingLanguage.prototype.createAttributeInstruction = function createAttributeInstruction(resources, element, info, existingInstruction) { throw new Error('A BindingLanguage must implement createAttributeInstruction(...)'); }; BindingLanguage.prototype.parseText = function parseText(resources, value) { throw new Error('A BindingLanguage must implement parseText(...)'); }; return BindingLanguage; })(); exports.BindingLanguage = BindingLanguage; function register(lookup, name, resource, type) { if (!name) { return; } var existing = lookup[name]; if (existing) { if (existing !== resource) { throw new Error('Attempted to register ' + type + ' when one with the same name already exists. Name: ' + name + '.'); } return; } lookup[name] = resource; } var ViewResources = (function () { function ViewResources(parent, viewUrl) { _classCallCheck(this, ViewResources); this.bindingLanguage = null; this.parent = parent || null; this.hasParent = this.parent !== null; this.viewUrl = viewUrl || ''; this.lookupFunctions = { valueConverters: this.getValueConverter.bind(this), bindingBehaviors: this.getBindingBehavior.bind(this) }; this.attributes = {}; this.elements = {}; this.valueConverters = {}; this.bindingBehaviors = {}; this.attributeMap = {}; this.hook1 = null; this.hook2 = null; this.hook3 = null; this.additionalHooks = null; } ViewResources.prototype._onBeforeCompile = function _onBeforeCompile(content, resources, instruction) { if (this.hasParent) { this.parent._onBeforeCompile(content, resources, instruction); } if (this.hook1 !== null) { this.hook1.beforeCompile(content, resources, instruction); if (this.hook2 !== null) { this.hook2.beforeCompile(content, resources, instruction); if (this.hook3 !== null) { this.hook3.beforeCompile(content, resources, instruction); if (this.additionalHooks !== null) { var hooks = this.additionalHooks; for (var i = 0, _length = hooks.length; i < _length; ++i) { hooks[i].beforeCompile(content, resources, instruction); } } } } } }; ViewResources.prototype._onAfterCompile = function _onAfterCompile(viewFactory) { if (this.hasParent) { this.parent._onAfterCompile(viewFactory); } if (this.hook1 !== null) { this.hook1.afterCompile(viewFactory); if (this.hook2 !== null) { this.hook2.afterCompile(viewFactory); if (this.hook3 !== null) { this.hook3.afterCompile(viewFactory); if (this.additionalHooks !== null) { var hooks = this.additionalHooks; for (var i = 0, _length2 = hooks.length; i < _length2; ++i) { hooks[i].afterCompile(viewFactory); } } } } } }; ViewResources.prototype._onBeforeCreate = function _onBeforeCreate(viewFactory, container, content, instruction, bindingContext) { if (this.hasParent) { this.parent._onBeforeCreate(viewFactory, container, content, instruction, bindingContext); } if (this.hook1 !== null) { this.hook1.beforeCreate(viewFactory, container, content, instruction, bindingContext); if (this.hook2 !== null) { this.hook2.beforeCreate(viewFactory, container, content, instruction, bindingContext); if (this.hook3 !== null) { this.hook3.beforeCreate(viewFactory, container, content, instruction, bindingContext); if (this.additionalHooks !== null) { var hooks = this.additionalHooks; for (var i = 0, _length3 = hooks.length; i < _length3; ++i) { hooks[i].beforeCreate(viewFactory, container, content, instruction, bindingContext); } } } } } }; ViewResources.prototype._onAfterCreate = function _onAfterCreate(view) { if (this.hasParent) { this.parent._onAfterCreate(view); } if (this.hook1 !== null) { this.hook1.afterCreate(view); if (this.hook2 !== null) { this.hook2.afterCreate(view); if (this.hook3 !== null) { this.hook3.afterCreate(view); if (this.additionalHooks !== null) { var hooks = this.additionalHooks; for (var i = 0, _length4 = hooks.length; i < _length4; ++i) { hooks[i].afterCreate(view); } } } } } }; ViewResources.prototype.registerViewEngineHooks = function registerViewEngineHooks(hooks) { if (hooks.beforeCompile === undefined) hooks.beforeCompile = _aureliaPal.PLATFORM.noop; if (hooks.afterCompile === undefined) hooks.afterCompile = _aureliaPal.PLATFORM.noop; if (hooks.beforeCreate === undefined) hooks.beforeCreate = _aureliaPal.PLATFORM.noop; if (hooks.afterCreate === undefined) hooks.afterCreate = _aureliaPal.PLATFORM.noop; if (this.hook1 === null) this.hook1 = hooks;else if (this.hook2 === null) this.hook2 = hooks;else if (this.hook3 === null) this.hook3 = hooks;else { if (this.additionalHooks === null) { this.additionalHooks = []; } this.additionalHooks.push(hooks); } }; ViewResources.prototype.getBindingLanguage = function getBindingLanguage(bindingLanguageFallback) { return this.bindingLanguage || (this.bindingLanguage = bindingLanguageFallback); }; ViewResources.prototype.patchInParent = function patchInParent(newParent) { var originalParent = this.parent; this.parent = newParent || null; this.hasParent = this.parent !== null; if (newParent.parent === null) { newParent.parent = originalParent; newParent.hasParent = originalParent !== null; } }; ViewResources.prototype.relativeToView = function relativeToView(path) { return _aureliaPath.relativeToFile(path, this.viewUrl); }; ViewResources.prototype.registerElement = function registerElement(tagName, behavior) { register(this.elements, tagName, behavior, 'an Element'); }; ViewResources.prototype.getElement = function getElement(tagName) { return this.elements[tagName] || (this.hasParent ? this.parent.getElement(tagName) : null); }; ViewResources.prototype.mapAttribute = function mapAttribute(attribute) { return this.attributeMap[attribute] || (this.hasParent ? this.parent.mapAttribute(attribute) : null); }; ViewResources.prototype.registerAttribute = function registerAttribute(attribute, behavior, knownAttribute) { this.attributeMap[attribute] = knownAttribute; register(this.attributes, attribute, behavior, 'an Attribute'); }; ViewResources.prototype.getAttribute = function getAttribute(attribute) { return this.attributes[attribute] || (this.hasParent ? this.parent.getAttribute(attribute) : null); }; ViewResources.prototype.registerValueConverter = function registerValueConverter(name, valueConverter) { register(this.valueConverters, name, valueConverter, 'a ValueConverter'); }; ViewResources.prototype.getValueConverter = function getValueConverter(name) { return this.valueConverters[name] || (this.hasParent ? this.parent.getValueConverter(name) : null); }; ViewResources.prototype.registerBindingBehavior = function registerBindingBehavior(name, bindingBehavior) { register(this.bindingBehaviors, name, bindingBehavior, 'a BindingBehavior'); }; ViewResources.prototype.getBindingBehavior = function getBindingBehavior(name) { return this.bindingBehaviors[name] || (this.hasParent ? this.parent.getBindingBehavior(name) : null); }; return ViewResources; })(); exports.ViewResources = ViewResources; var View = (function () { function View(viewFactory, fragment, controllers, bindings, children, contentSelectors) { _classCallCheck(this, View); this.viewFactory = viewFactory; this.fragment = fragment; this.controllers = controllers; this.bindings = bindings; this.children = children; this.contentSelectors = contentSelectors; this.firstChild = fragment.firstChild; this.lastChild = fragment.lastChild; this.fromCache = false; this.isBound = false; this.isAttached = false; this.fromCache = false; this.bindingContext = null; this.overrideContext = null; this.controller = null; this.viewModelScope = null; this._isUserControlled = false; } View.prototype.returnToCache = function returnToCache() { this.viewFactory.returnViewToCache(this); }; View.prototype.created = function created() { var i = undefined; var ii = undefined; var controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].created(this); } }; View.prototype.bind = function bind(bindingContext, overrideContext, _systemUpdate) { var controllers = undefined; var bindings = undefined; var children = undefined; var i = undefined; var ii = undefined; if (_systemUpdate && this._isUserControlled) { return; } if (this.isBound) { if (this.bindingContext === bindingContext) { return; } this.unbind(); } this.isBound = true; this.bindingContext = bindingContext; this.overrideContext = overrideContext || _aureliaBinding.createOverrideContext(bindingContext); bindings = this.bindings; for (i = 0, ii = bindings.length; i < ii; ++i) { bindings[i].bind(this); } if (this.viewModelScope !== null) { bindingContext.bind(this.viewModelScope.bindingContext, this.viewModelScope.overrideContext); this.viewModelScope = null; } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].bind(this); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].bind(bindingContext, overrideContext, true); } }; View.prototype.addBinding = function addBinding(binding) { this.bindings.push(binding); if (this.isBound) { binding.bind(this.bindingContext); } }; View.prototype.unbind = function unbind() { var controllers = undefined; var bindings = undefined; var children = undefined; var i = undefined; var ii = undefined; if (this.isBound) { this.isBound = false; this.bindingContext = null; this.overrideContext = null; if (this.controller !== null) { this.controller.unbind(); } bindings = this.bindings; for (i = 0, ii = bindings.length; i < ii; ++i) { bindings[i].unbind(); } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].unbind(); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].unbind(); } } }; View.prototype.insertNodesBefore = function insertNodesBefore(refNode) { var parent = refNode.parentNode; parent.insertBefore(this.fragment, refNode); }; View.prototype.appendNodesTo = function appendNodesTo(parent) { parent.appendChild(this.fragment); }; View.prototype.removeNodes = function removeNodes() { var start = this.firstChild; var end = this.lastChild; var fragment = this.fragment; var next = undefined; var current = start; var loop = true; while (loop) { if (current === end) { loop = false; } next = current.nextSibling; fragment.appendChild(current); current = next; } }; View.prototype.attached = function attached() { var controllers = undefined; var children = undefined; var i = undefined; var ii = undefined; if (this.isAttached) { return; } this.isAttached = true; if (this.controller !== null) { this.controller.attached(); } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].attached(); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].attached(); } }; View.prototype.detached = function detached() { var controllers = undefined; var children = undefined; var i = undefined; var ii = undefined; if (this.isAttached) { this.isAttached = false; if (this.controller !== null) { this.controller.detached(); } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].detached(); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].detached(); } } }; return View; })(); exports.View = View; var placeholder = []; function findInsertionPoint(groups, index) { var insertionPoint = undefined; while (!insertionPoint && index >= 0) { insertionPoint = groups[index][0]; index--; } return insertionPoint; } var _ContentSelector = (function () { _ContentSelector.applySelectors = function applySelectors(view, contentSelectors, callback) { var currentChild = view.fragment.firstChild; var contentMap = new Map(); var nextSibling = undefined; var i = undefined; var ii = undefined; var contentSelector = undefined; while (currentChild) { nextSibling = currentChild.nextSibling; if (currentChild.viewSlot) { var viewSlotSelectors = contentSelectors.map(function (x) { return x.copyForViewSlot(); }); currentChild.viewSlot._installContentSelectors(viewSlotSelectors); } else { for (i = 0, ii = contentSelectors.length; i < ii; i++) { contentSelector = contentSelectors[i]; if (contentSelector.matches(currentChild)) { var elements = contentMap.get(contentSelector); if (!elements) { elements = []; contentMap.set(contentSelector, elements); } elements.push(currentChild); break; } } } currentChild = nextSibling; } for (i = 0, ii = contentSelectors.length; i < ii; ++i) { contentSelector = contentSelectors[i]; callback(contentSelector, contentMap.get(contentSelector) || placeholder); } }; function _ContentSelector(anchor, selector) { _classCallCheck(this, _ContentSelector); this.anchor = anchor; this.selector = selector; this.all = !this.selector; this.groups = []; } _ContentSelector.prototype.copyForViewSlot = function copyForViewSlot() { return new _ContentSelector(this.anchor, this.selector); }; _ContentSelector.prototype.matches = function matches(node) { return this.all || node.nodeType === 1 && node.matches(this.selector); }; _ContentSelector.prototype.add = function add(group) { var anchor = this.anchor; var parent = anchor.parentNode; var i = undefined; var ii = undefined; for (i = 0, ii = group.length; i < ii; ++i) { parent.insertBefore(group[i], anchor); } this.groups.push(group); }; _ContentSelector.prototype.insert = function insert(index, group) { if (group.length) { var anchor = findInsertionPoint(this.groups, index) || this.anchor; var _parent = anchor.parentNode; var i = undefined; var ii = undefined; for (i = 0, ii = group.length; i < ii; ++i) { _parent.insertBefore(group[i], anchor); } } this.groups.splice(index, 0, group); }; _ContentSelector.prototype.removeAt = function removeAt(index, fragment) { var group = this.groups[index]; var i = undefined; var ii = undefined; for (i = 0, ii = group.length; i < ii; ++i) { fragment.appendChild(group[i]); } this.groups.splice(index, 1); }; return _ContentSelector; })(); exports._ContentSelector = _ContentSelector; function getAnimatableElement(view) { var firstChild = view.firstChild; if (firstChild !== null && firstChild !== undefined && firstChild.nodeType === 8) { var _element = _aureliaPal.DOM.nextElementSibling(firstChild); if (_element !== null && _element !== undefined && _element.nodeType === 1 && _element.classList.contains('au-animate')) { return _element; } } return null; } var ViewSlot = (function () { function ViewSlot(anchor, anchorIsContainer) { var animator = arguments.length <= 2 || arguments[2] === undefined ? Animator.instance : arguments[2]; _classCallCheck(this, ViewSlot); this.anchor = anchor; this.viewAddMethod = anchorIsContainer ? 'appendNodesTo' : 'insertNodesBefore'; this.bindingContext = null; this.animator = animator; this.children = []; this.isBound = false; this.isAttached = false; this.contentSelectors = null; anchor.viewSlot = this; } ViewSlot.prototype.transformChildNodesIntoView = function transformChildNodesIntoView() { var parent = this.anchor; this.children.push({ fragment: parent, firstChild: parent.firstChild, lastChild: parent.lastChild, returnToCache: function returnToCache() {}, removeNodes: function removeNodes() { var last = undefined; while (last = parent.lastChild) { parent.removeChild(last); } }, created: function created() {}, bind: function bind() {}, unbind: function unbind() {}, attached: function attached() {}, detached: function detached() {} }); }; ViewSlot.prototype.bind = function bind(bindingContext, overrideContext) { var i = undefined; var ii = undefined; var children = undefined; if (this.isBound) { if (this.bindingContext === bindingContext) { return; } this.unbind(); } this.isBound = true; this.bindingContext = bindingContext = bindingContext || this.bindingContext; children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].bind(bindingContext, overrideContext, true); } }; ViewSlot.prototype.unbind = function unbind() { if (this.isBound) { var i = undefined; var ii = undefined; var _children = this.children; this.isBound = false; this.bindingContext = null; for (i = 0, ii = _children.length; i < ii; ++i) { _children[i].unbind(); } } }; ViewSlot.prototype.add = function add(view) { view[this.viewAddMethod](this.anchor); this.children.push(view); if (this.isAttached) { view.attached(); var animatableElement = getAnimatableElement(view); if (animatableElement !== null) { return this.animator.enter(animatableElement); } } }; ViewSlot.prototype.insert = function insert(index, view) { var children = this.children; var length = children.length; if (index === 0 && length === 0 || index >= length) { return this.add(view); } view.insertNodesBefore(children[index].firstChild); children.splice(index, 0, view); if (this.isAttached) { view.attached(); var animatableElement = getAnimatableElement(view); if (animatableElement !== null) { return this.animator.enter(animatableElement); } } }; ViewSlot.prototype.remove = function remove(view, returnToCache, skipAnimation) { return this.removeAt(this.children.indexOf(view), returnToCache, skipAnimation); }; ViewSlot.prototype.removeAt = function removeAt(index, returnToCache, skipAnimation) { var _this = this; var view = this.children[index]; var removeAction = function removeAction() { index = _this.children.indexOf(view); view.removeNodes(); _this.children.splice(index, 1); if (_this.isAttached) { view.detached(); } if (returnToCache) { view.returnToCache(); } return view; }; if (!skipAnimation) { var animatableElement = getAnimatableElement(view); if (animatableElement !== null) { return this.animator.leave(animatableElement).then(function () { return removeAction(); }); } } return removeAction(); }; ViewSlot.prototype.removeAll = function removeAll(returnToCache, skipAnimation) { var _this2 = this; var children = this.children; var ii = children.length; var i = undefined; var rmPromises = []; children.forEach(function (child) { if (skipAnimation) { child.removeNodes(); return; } var animatableElement = getAnimatableElement(child); if (animatableElement !== null) { rmPromises.push(_this2.animator.leave(animatableElement).then(function () { return child.removeNodes(); })); } else { child.removeNodes(); } }); var removeAction = function removeAction() { if (_this2.isAttached) { for (i = 0; i < ii; ++i) { children[i].detached(); } } if (returnToCache) { for (i = 0; i < ii; ++i) { children[i].returnToCache(); } } _this2.children = []; }; if (rmPromises.length > 0) { return Promise.all(rmPromises).then(function () { return removeAction(); }); } removeAction(); }; ViewSlot.prototype.attached = function attached() { var i = undefined; var ii = undefined; var children = undefined; var child = undefined; if (this.isAttached) { return; } this.isAttached = true; children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { child = children[i]; child.attached(); var _element2 = child.firstChild ? _aureliaPal.DOM.nextElementSibling(child.firstChild) : null; if (child.firstChild && child.firstChild.nodeType === 8 && _element2 && _element2.nodeType === 1 && _element2.classList.contains('au-animate')) { this.animator.enter(_element2); } } }; ViewSlot.prototype.detached = function detached() { var i = undefined; var ii = undefined; var children = undefined; if (this.isAttached) { this.isAttached = false; children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].detached(); } } }; ViewSlot.prototype._installContentSelectors = function _installContentSelectors(contentSelectors) { this.contentSelectors = contentSelectors; this.add = this._contentSelectorAdd; this.insert = this._contentSelectorInsert; this.remove = this._contentSelectorRemove; this.removeAt = this._contentSelectorRemoveAt; this.removeAll = this._contentSelectorRemoveAll; }; ViewSlot.prototype._contentSelectorAdd = function _contentSelectorAdd(view) { _ContentSelector.applySelectors(view, this.contentSelectors, function (contentSelector, group) { return contentSelector.add(group); }); this.children.push(view); if (this.isAttached) { view.attached(); } }; ViewSlot.prototype._contentSelectorInsert = function _contentSelectorInsert(index, view) { if (index === 0 && !this.children.length || index >= this.children.length) { this.add(view); } else { _ContentSelector.applySelectors(view, this.contentSelectors, function (contentSelector, group) { return contentSelector.insert(index, group); }); this.children.splice(index, 0, view); if (this.isAttached) { view.attached(); } } }; ViewSlot.prototype._contentSelectorRemove = function _contentSelectorRemove(view) { var index = this.children.indexOf(view); var contentSelectors = this.contentSelectors; var i = undefined; var ii = undefined; for (i = 0, ii = contentSelectors.length; i < ii; ++i) { contentSelectors[i].removeAt(index, view.fragment); } this.children.splice(index, 1); if (this.isAttached) { view.detached(); } }; ViewSlot.prototype._contentSelectorRemoveAt = function _contentSelectorRemoveAt(index) { var view = this.children[index]; var contentSelectors = this.contentSelectors; var i = undefined; var ii = undefined; for (i = 0, ii = contentSelectors.length; i < ii; ++i) { contentSelectors[i].removeAt(index, view.fragment); } this.children.splice(index, 1); if (this.isAttached) { view.detached(); } return view; }; ViewSlot.prototype._contentSelectorRemoveAll = function _contentSelectorRemoveAll() { var children = this.children; var contentSelectors = this.contentSelectors; var ii = children.length; var jj = contentSelectors.length; var i = undefined; var j = undefined; var view = undefined; for (i = 0; i < ii; ++i) { view = children[i]; for (j = 0; j < jj; ++j) { contentSelectors[j].removeAt(0, view.fragment); } } if (this.isAttached) { for (i = 0; i < ii; ++i) { children[i].detached(); } } this.children = []; }; return ViewSlot; })(); exports.ViewSlot = ViewSlot; var ProviderResolver = (function () { function ProviderResolver() { _classCallCheck(this, _ProviderResolver); } ProviderResolver.prototype.get = function get(container, key) { var id = key.__providerId__; return id in container ? container[id] : container[id] = container.invoke(key); }; var _ProviderResolver = ProviderResolver; ProviderResolver = _aureliaDependencyInjection.resolver(ProviderResolver) || ProviderResolver; return ProviderResolver; })(); var providerResolverInstance = new ProviderResolver(); function elementContainerGet(key) { if (key === _aureliaPal.DOM.Element) { return this.element; } if (key === BoundViewFactory) { if (this.boundViewFactory) { return this.boundViewFactory; } var factory = this.instruction.viewFactory; var _partReplacements = this.partReplacements; if (_partReplacements) { factory = _partReplacements[factory.part] || factory; } this.boundViewFactory = new BoundViewFactory(this, factory, _partReplacements); return this.boundViewFactory; } if (key === ViewSlot) { if (this.viewSlot === undefined) { this.viewSlot = new ViewSlot(this.element, this.instruction.anchorIsContainer); this.children.push(this.viewSlot); } return this.viewSlot; } if (key === ViewResources) { return this.viewResources; } if (key === TargetInstruction) { return this.instruction; } return this.superGet(key); } function createElementContainer(parent, element, instruction, children, partReplacements, resources) { var container = parent.createChild(); var providers = undefined; var i = undefined; container.element = element; container.instruction = instruction; container.children = children; container.viewResources = resources; container.partReplacements = partReplacements; providers = instruction.providers; i = providers.length; while (i--) { container._resolvers.set(providers[i], providerResolverInstance); } container.superGet = container.get; container.get = elementContainerGet; return container; } function makeElementIntoAnchor(element, elementInstruction) { var anchor = _aureliaPal.DOM.createComment('anchor'); if (elementInstruction) { anchor.hasAttribute = function (name) { return element.hasAttribute(name); }; anchor.getAttribute = function (name) { return element.getAttribute(name); }; anchor.setAttribute = function (name, value) { element.setAttribute(name, value); }; } _aureliaPal.DOM.replaceNode(anchor, element); return anchor; } function applyInstructions(containers, element, instruction, controllers, bindings, children, contentSelectors, partReplacements, resources) { var behaviorInstructions = instruction.behaviorInstructions; var expressions = instruction.expressions; var elementContainer = undefined; var i = undefined; var ii = undefined; var current = undefined; var instance = undefined; if (instruction.contentExpression) { bindings.push(instruction.contentExpression.createBinding(element.nextSibling)); element.parentNode.removeChild(element); return; } if (instruction.contentSelector) { var commentAnchor = _aureliaPal.DOM.createComment('anchor'); _aureliaPal.DOM.replaceNode(commentAnchor, element); contentSelectors.push(new _ContentSelector(commentAnchor, instruction.selector)); return; } if (behaviorInstructions.length) { if (!instruction.anchorIsContainer) { element = makeElementIntoAnchor(element, instruction.elementInstruction); } containers[instruction.injectorId] = elementContainer = createElementContainer(containers[instruction.parentInjectorId], element, instruction, children, partReplacements, resources); for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { current = behaviorInstructions[i]; instance = current.type.create(elementContainer, current, element, bindings); if (instance.contentView) { children.push(instance.contentView); } controllers.push(instance); } } for (i = 0, ii = expressions.length; i < ii; ++i) { bindings.push(expressions[i].createBinding(element)); } } function styleStringToObject(style, target) { var attributes = style.split(';'); var firstIndexOfColon = undefined; var i = undefined; var current = undefined; var key = undefined; var value = undefined; target = target || {}; for (i = 0; i < attributes.length; i++) { current = attributes[i]; firstIndexOfColon = current.indexOf(':'); key = current.substring(0, firstIndexOfColon).trim(); value = current.substring(firstIndexOfColon + 1).trim(); target[key] = value; } return target; } function styleObjectToString(obj) { var result = ''; for (var key in obj) { result += key + ':' + obj[key] + ';'; } return result; } function applySurrogateInstruction(container, element, instruction, controllers, bindings, children) { var behaviorInstructions = instruction.behaviorInstructions; var expressions = instruction.expressions; var providers = instruction.providers; var values = instruction.values; var i = undefined; var ii = undefined; var current = undefined; var instance = undefined; var currentAttributeValue = undefined; i = providers.length; while (i--) { container._resolvers.set(providers[i], providerResolverInstance); } for (var key in values) { currentAttributeValue = element.getAttribute(key); if (currentAttributeValue) { if (key === 'class') { element.setAttribute('class', currentAttributeValue + ' ' + values[key]); } else if (key === 'style') { var styleObject = styleStringToObject(values[key]); styleStringToObject(currentAttributeValue, styleObject); element.setAttribute('style', styleObjectToString(styleObject)); } } else { element.setAttribute(key, values[key]); } } if (behaviorInstructions.length) { for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { current = behaviorInstructions[i]; instance = current.type.create(container, current, element, bindings); if (instance.contentView) { children.push(instance.contentView); } controllers.push(instance); } } for (i = 0, ii = expressions.length; i < ii; ++i) { bindings.push(expressions[i].createBinding(element)); } } var BoundViewFactory = (function () { function BoundViewFactory(parentContainer, viewFactory, partReplacements) { _classCallCheck(this, BoundViewFactory); this.parentContainer = parentContainer; this.viewFactory = viewFactory; this.factoryCreateInstruction = { partReplacements: partReplacements }; } BoundViewFactory.prototype.create = function create() { var view = this.viewFactory.create(this.parentContainer.createChild(), this.factoryCreateInstruction); view._isUserControlled = true; return view; }; BoundViewFactory.prototype.setCacheSize = function setCacheSize(size, doNotOverrideIfAlreadySet) { this.viewFactory.setCacheSize(size, doNotOverrideIfAlreadySet); }; BoundViewFactory.prototype.getCachedView = function getCachedView() { return this.viewFactory.getCachedView(); }; BoundViewFactory.prototype.returnViewToCache = function returnViewToCache(view) { this.viewFactory.returnViewToCache(view); }; _createClass(BoundViewFactory, [{ key: 'isCaching', get: function get() { return this.viewFactory.isCaching; } }]); return BoundViewFactory; })(); exports.BoundViewFactory = BoundViewFactory; var ViewFactory = (function () { function ViewFactory(template, instructions, resources) { _classCallCheck(this, ViewFactory); this.isCaching = false; this.template = template; this.instructions = instructions; this.resources = resources; this.cacheSize = -1; this.cache = null; } ViewFactory.prototype.setCacheSize = function setCacheSize(size, doNotOverrideIfAlreadySet) { if (size) { if (size === '*') { size = Number.MAX_VALUE; } else if (typeof size === 'string') { size = parseInt(size, 10); } } if (this.cacheSize === -1 || !doNotOverrideIfAlreadySet) { this.cacheSize = size; } if (this.cacheSize > 0) { this.cache = []; } else { this.cache = null; } this.isCaching = this.cacheSize > 0; }; ViewFactory.prototype.getCachedView = function getCachedView() { return this.cache !== null ? this.cache.pop() || null : null; }; ViewFactory.prototype.returnViewToCache = function returnViewToCache(view) { if (view.isAttached) { view.detached(); } if (view.isBound) { view.unbind(); } if (this.cache !== null && this.cache.length < this.cacheSize) { view.fromCache = true; this.cache.push(view); } }; ViewFactory.prototype.create = function create(container, createInstruction, element) { createInstruction = createInstruction || BehaviorInstruction.normal; element = element || null; var cachedView = this.getCachedView(); if (cachedView !== null) { return cachedView; } var fragment = createInstruction.enhance ? this.template : this.template.cloneNode(true); var instructables = fragment.querySelectorAll('.au-target'); var instructions = this.instructions; var resources = this.resources; var controllers = []; var bindings = []; var children = []; var contentSelectors = []; var containers = { root: container }; var partReplacements = createInstruction.partReplacements; var i = undefined; var ii = undefined; var view = undefined; var instructable = undefined; var instruction = undefined; this.resources._onBeforeCreate(this, container, fragment, createInstruction); if (element !== null && this.surrogateInstruction !== null) { applySurrogateInstruction(container, element, this.surrogateInstruction, controllers, bindings, children); } for (i = 0, ii = instructables.length; i < ii; ++i) { instructable = instructables[i]; instruction = instructions[instructable.getAttribute('au-target-id')]; applyInstructions(containers, instructable, instruction, controllers, bindings, children, contentSelectors, partReplacements, resources); } view = new View(this, fragment, controllers, bindings, children, contentSelectors); if (!createInstruction.initiatedByBehavior) { view.created(); } this.resources._onAfterCreate(view); return view; }; return ViewFactory; })(); exports.ViewFactory = ViewFactory; var nextInjectorId = 0; function getNextInjectorId() { return ++nextInjectorId; } function configureProperties(instruction, resources) { var type = instruction.type; var attrName = instruction.attrName; var attributes = instruction.attributes; var property = undefined; var key = undefined; var value = undefined; var knownAttribute = resources.mapAttribute(attrName); if (knownAttribute && attrName in attributes && knownAttribute !== attrName) { attributes[knownAttribute] = attributes[attrName]; delete attributes[attrName]; } for (key in attributes) { value = attributes[key]; if (value !== null && typeof value === 'object') { property = type.attributes[key]; if (property !== undefined) { value.targetProperty = property.name; } else { value.targetProperty = key; } } } } var lastAUTargetID = 0; function getNextAUTargetID() { return (++lastAUTargetID).toString(); } function makeIntoInstructionTarget(element) { var value = element.getAttribute('class'); var auTargetID = getNextAUTargetID(); element.setAttribute('class', value ? value += ' au-target' : 'au-target'); element.setAttribute('au-target-id', auTargetID); return auTargetID; } var ViewCompiler = (function () { function ViewCompiler(bindingLanguage, resources) { _classCallCheck(this, _ViewCompiler); this.bindingLanguage = bindingLanguage; this.resources = resources; } ViewCompiler.prototype.compile = function compile(source, resources, compileInstruction) { resources = resources || this.resources; compileInstruction = compileInstruction || ViewCompileInstruction.normal; source = typeof source === 'string' ? _aureliaPal.DOM.createTemplateFromMarkup(source) : source; var content = undefined; var part = undefined; var cacheSize = undefined; if (source.content) { part = source.getAttribute('part'); cacheSize = source.getAttribute('view-cache'); content = _aureliaPal.DOM.adoptNode(source.content); } else { content = source; } compileInstruction.targetShadowDOM = compileInstruction.targetShadowDOM && _aureliaPal.FEATURE.shadowDOM; resources._onBeforeCompile(content, resources, compileInstruction); var instructions = {}; this._compileNode(content, resources, instructions, source, 'root', !compileInstruction.targetShadowDOM); content.insertBefore(_aureliaPal.DOM.createComment('<view>'), content.firstChild); content.appendChild(_aureliaPal.DOM.createComment('</view>')); var factory = new ViewFactory(content, instructions, resources); factory.surrogateInstruction = compileInstruction.compileSurrogate ? this._compileSurrogate(source, resources) : null; factory.part = part; if (cacheSize) { factory.setCacheSize(cacheSize); } resources._onAfterCompile(factory); return factory; }; ViewCompiler.prototype._compileNode = function _compileNode(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) { switch (node.nodeType) { case 1: return this._compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM); case 3: var expression = resources.getBindingLanguage(this.bindingLanguage).parseText(resources, node.wholeText); if (expression) { var marker = _aureliaPal.DOM.createElement('au-marker'); var auTargetID = makeIntoInstructionTarget(marker); (node.parentNode || parentNode).insertBefore(marker, node); node.textContent = ' '; instructions[auTargetID] = TargetInstruction.contentExpression(expression); while (node.nextSibling && node.nextSibling.nodeType === 3) { (node.parentNode || parentNode).removeChild(node.nextSibling); } } else { while (node.nextSibling && node.nextSibling.nodeType === 3) { node = node.nextSibling; } } return node.nextSibling; case 11: var currentChild = node.firstChild; while (currentChild) { currentChild = this._compileNode(currentChild, resources, instructions, node, parentInjectorId, targetLightDOM); } break; default: break; } return node.nextSibling; }; ViewCompiler.prototype._compileSurrogate = function _compileSurrogate(node, resources) { var attributes = node.attributes; var bindingLanguage = resources.getBindingLanguage(this.bindingLanguage); var knownAttribute = undefined; var property = undefined; var instruction = undefined; var i = undefined; var ii = undefined; var attr = undefined; var attrName = undefined; var attrValue = undefined; var info = undefined; var type = undefined; var expressions = []; var expression = undefined; var behaviorInstructions = []; var values = {}; var hasValues = false; var providers = []; for (i = 0, ii = attributes.length; i < ii; ++i) { attr = attributes[i]; attrName = attr.name; attrValue = attr.value; info = bindingLanguage.inspectAttribute(resources, attrName, attrValue); type = resources.getAttribute(info.attrName); if (type) { knownAttribute = resources.mapAttribute(info.attrName); if (knownAttribute) { property = type.attributes[knownAttribute]; if (property) { info.defaultBindingMode = property.defaultBindingMode; if (!info.command && !info.expression) { info.command = property.hasOptions ? 'options' : null; } } } } instruction = bindingLanguage.createAttributeInstruction(resources, node, info); if (instruction) { if (instruction.alteredAttr) { type = resources.getAttribute(instruction.attrName); } if (instruction.discrete) { expressions.push(instruction); } else { if (type) { instruction.type = type; configureProperties(instruction, resources); if (type.liftsContent) { throw new Error('You cannot place a template controller on a surrogate element.'); } else { behaviorInstructions.push(instruction); } } else { expressions.push(instruction.attributes[instruction.attrName]); } } } else { if (type) { instruction = BehaviorInstruction.attribute(attrName, type); instruction.attributes[resources.mapAttribute(attrName)] = attrValue; if (type.liftsContent) { throw new Error('You cannot place a template controller on a surrogate element.'); } else { behaviorInstructions.push(instruction); } } else if (attrName !== 'id' && attrName !== 'part' && attrName !== 'replace-part') { hasValues = true; values[attrName] = attrValue; } } } if (expressions.length || behaviorInstructions.length || hasValues) { for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { instruction = behaviorInstructions[i]; instruction.type.compile(this, resources, node, instruction); providers.push(instruction.type.target); } for (i = 0, ii = expressions.length; i < ii; ++i) { expression = expressions[i]; if (expression.attrToRemove !== undefined) { node.removeAttribute(expression.attrToRemove); } } return TargetInstruction.surrogate(providers, behaviorInstructions, expressions, values); } return null; }; ViewCompiler.prototype._compileElement = function _compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) { var tagName = node.tagName.toLowerCase(); var attributes = node.attributes; var expressions = []; var expression = undefined; var behaviorInstructions = []; var providers = []; var bindingLanguage = resources.getBindingLanguage(this.bindingLanguage); var liftingInstruction = undefined; var viewFactory = undefined; var type = undefined; var elementInstruction = undefined; var elementProperty = undefined; var i = undefined; var ii = undefined; var attr = undefined; var attrName = undefined; var attrValue = undefined; var instruction = undefined; var info = undefined; var property = undefined; var knownAttribute = undefined; var auTargetID = undefined; var injectorId = undefined; if (tagName === 'content') { if (targetLightDOM) { auTargetID = makeIntoInstructionTarget(node); instructions[auTargetID] = TargetInstruction.contentSelector(node, parentInjectorId); } return node.nextSibling; } else if (tagName === 'template') { viewFactory = this.compile(node, resources); viewFactory.part = node.getAttribute('part'); } else { type = resources.getElement(tagName); if (type) { elementInstruction = BehaviorInstruction.element(node, type); behaviorInstructions.push(elementInstruction); } } for (i = 0, ii = attributes.length; i < ii; ++i) { attr = attributes[i]; attrName = attr.name; attrValue = attr.value; info = bindingLanguage.inspectAttribute(resources, attrName, attrValue); type = resources.getAttribute(info.attrName); elementProperty = null; if (type) { knownAttribute = resources.mapAttribute(info.attrName); if (knownAttribute) { property = type.attributes[knownAttribute]; if (property) { info.defaultBindingMode = property.defaultBindingMode; if (!info.command && !info.expression) { info.command = property.hasOptions ? 'options' : null; } } } } else if (elementInstruction) { elementProperty = elementInstruction.type.attributes[info.attrName]; if (elementProperty) { info.defaultBindingMode = elementProperty.defaultBindingMode; } } if (elementProperty) { instruction = bindingLanguage.createAttributeInstruction(resources, node, info, elementInstruction); } else { instruction = bindingLanguage.createAttributeInstruction(resources, node, info); } if (instruction) { if (instruction.alteredAttr) { type = resources.getAttribute(instruction.attrName); } if (instruction.discrete) { expressions.push(instruction); } else { if (type) { instruction.type = type; configureProperties(instruction, resources); if (type.liftsContent) { instruction.originalAttrName = attrName; liftingInstruction = instruction; break; } else { behaviorInstructions.push(instruction); } } else if (elementProperty) { elementInstruction.attributes[info.attrName].targetProperty = elementProperty.name; } else { expressions.push(instruction.attributes[instruction.attrName]); } } } else { if (type) { instruction = BehaviorInstruction.attribute(attrName, type); instruction.attributes[resources.mapAttribute(attrName)] = attrValue; if (type.liftsContent) { instruction.originalAttrName = attrName; liftingInstruction = instruction; break; } else { behaviorInstructions.push(instruction); } } else if (elementProperty) { elementInstruction.attributes[attrName] = attrValue; } } } if (liftingInstruction) { liftingInstruction.viewFactory = viewFactory; node = liftingInstruction.type.compile(this, resources, node, liftingInstruction, parentNode); auTargetID = makeIntoInstructionTarget(node); instructions[auTargetID] = TargetInstruction.lifting(parentInjectorId, liftingInstruction); } else { if (expressions.length || behaviorInstructions.length) { injectorId = behaviorInstructions.length ? getNextInjectorId() : false; for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { instruction = behaviorInstructions[i]; instruction.type.compile(this, resources, node, instruction, parentNode); providers.push(instruction.type.target); } for (i = 0, ii = expressions.length; i < ii; ++i) { expression = expressions[i]; if (expression.attrToRemove !== undefined) { node.removeAttribute(expression.attrToRemove); } } auTargetID = makeIntoInstructionTarget(node); instructions[auTargetID] = TargetInstruction.normal(injectorId, parentInjectorId, providers, behaviorInstructions, expressions, elementInstruction); } if (elementInstruction && elementInstruction.skipContentProcessing) { return node.nextSibling; } var currentChild = node.firstChild; while (currentChild) { currentChild = this._compileNode(currentChild, resources, instructions, node, injectorId || parentInjectorId, targetLightDOM); } } return node.nextSibling; }; var _ViewCompiler = ViewCompiler; ViewCompiler = _aureliaDependencyInjection.inject(BindingLanguage, ViewResources)(ViewCompiler) || ViewCompiler; return ViewCompiler; })(); exports.ViewCompiler = ViewCompiler; var ResourceModule = (function () { function ResourceModule(moduleId) { _classCallCheck(this, ResourceModule); this.id = moduleId; this.moduleInstance = null; this.mainResource = null; this.resources = null; this.viewStrategy = null; this.isInitialized = false; this.onLoaded = null; } ResourceModule.prototype.initialize = function initialize(container) { var current = this.mainResource; var resources = this.resources; var vs = this.viewStrategy; if (this.isInitialized) { return; } this.isInitialized = true; if (current !== undefined) { current.metadata.viewStrategy = vs; current.initialize(container); } for (var i = 0, ii = resources.length; i < ii; ++i) { current = resources[i]; current.metadata.viewStrategy = vs; current.initialize(container); } }; ResourceModule.prototype.register = function register(registry, name) { var main = this.mainResource; var resources = this.resources; if (main !== undefined) { main.register(registry, name); name = null; } for (var i = 0, ii = resources.length; i < ii; ++i) { resources[i].register(registry, name); name = null; } }; ResourceModule.prototype.load = function load(container, loadContext) { if (this.onLoaded !== null) { return this.onLoaded; } var main = this.mainResource; var resources = this.resources; var loads = undefined; if (main !== undefined) { loads = new Array(resources.length + 1); loads[0] = main.load(container, loadContext); for (var i = 0, ii = resources.length; i < ii; ++i) { loads[i + 1] = resources[i].load(container, loadContext); } } else { loads = new Array(resources.length); for (var i = 0, ii = resources.length; i < ii; ++i) { loads[i] = resources[i].load(container, loadContext); } } this.onLoaded = Promise.all(loads); return this.onLoaded; }; return ResourceModule; })(); exports.ResourceModule = ResourceModule; var ResourceDescription = (function () { function ResourceDescription(key, exportedValue, resourceTypeMeta) { _classCallCheck(this, ResourceDescription); if (!resourceTypeMeta) { resourceTypeMeta = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.resource, exportedValue); if (!resourceTypeMeta) { resourceTypeMeta = new HtmlBehaviorResource(); resourceTypeMeta.elementName = _hyphenate(key); _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, resourceTypeMeta, exportedValue); } } if (resourceTypeMeta instanceof HtmlBehaviorResource) { if (resourceTypeMeta.elementName === undefined) { resourceTypeMeta.elementName = _hyphenate(key); } else if (resourceTypeMeta.attributeName === undefined) { resourceTypeMeta.attributeName = _hyphenate(key); } else if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { HtmlBehaviorResource.convention(key, resourceTypeMeta); } } else if (!resourceTypeMeta.name) { resourceTypeMeta.name = _hyphenate(key); } this.metadata = resourceTypeMeta; this.value = exportedValue; } ResourceDescription.prototype.initialize = function initialize(container) { this.metadata.initialize(container, this.value); }; ResourceDescription.prototype.register = function register(registry, name) { this.metadata.register(registry, name); }; ResourceDescription.prototype.load = function load(container, loadContext) { return this.metadata.load(container, this.value, loadContext); }; return ResourceDescription; })(); exports.ResourceDescription = ResourceDescription; var ModuleAnalyzer = (function () { function ModuleAnalyzer() { _classCallCheck(this, ModuleAnalyzer); this.cache = {}; } ModuleAnalyzer.prototype.getAnalysis = function getAnalysis(moduleId) { return this.cache[moduleId]; }; ModuleAnalyzer.prototype.analyze = function analyze(moduleId, moduleInstance, mainResourceKey) { var mainResource = undefined; var fallbackValue = undefined; var fallbackKey = undefined; var resourceTypeMeta = undefined; var key = undefined; var exportedValue = undefined; var resources = []; var conventional = undefined; var vs = undefined; var resourceModule = undefined; resourceModule = this.cache[moduleId]; if (resourceModule) { return resourceModule; } resourceModule = new ResourceModule(moduleId); this.cache[moduleId] = resourceModule; if (typeof moduleInstance === 'function') { moduleInstance = { 'default': moduleInstance }; } if (mainResourceKey) { mainResource = new ResourceDescription(mainResourceKey, moduleInstance[mainResourceKey]); } for (key in moduleInstance) { exportedValue = moduleInstance[key]; if (key === mainResourceKey || typeof exportedValue !== 'function') { continue; } resourceTypeMeta = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.resource, exportedValue); if (resourceTypeMeta) { if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { HtmlBehaviorResource.convention(key, resourceTypeMeta); } if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { resourceTypeMeta.elementName = _hyphenate(key); } if (!mainResource && resourceTypeMeta instanceof HtmlBehaviorResource && resourceTypeMeta.elementName !== null) { mainResource = new ResourceDescription(key, exportedValue, resourceTypeMeta); } else { resources.push(new ResourceDescription(key, exportedValue, resourceTypeMeta)); } } else if (viewStrategy.decorates(exportedValue)) { vs = exportedValue; } else if (exportedValue instanceof _aureliaLoader.TemplateRegistryEntry) { vs = new TemplateRegistryViewStrategy(moduleId, exportedValue); } else { if (conventional = HtmlBehaviorResource.convention(key)) { if (conventional.elementName !== null && !mainResource) { mainResource = new ResourceDescription(key, exportedValue, conventional); } else { resources.push(new ResourceDescription(key, exportedValue, conventional)); } _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, conventional, exportedValue); } else if (conventional = _aureliaBinding.ValueConverterResource.convention(key)) { resources.push(new ResourceDescription(key, exportedValue, conventional)); _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, conventional, exportedValue); } else if (conventional = _aureliaBinding.BindingBehaviorResource.convention(key)) { resources.push(new ResourceDescription(key, exportedValue, conventional)); _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, conventional, exportedValue); } else if (!fallbackValue) { fallbackValue = exportedValue; fallbackKey = key; } } } if (!mainResource && fallbackValue) { mainResource = new ResourceDescription(fallbackKey, fallbackValue); } resourceModule.moduleInstance = moduleInstance; resourceModule.mainResource = mainResource; resourceModule.resources = resources; resourceModule.viewStrategy = vs; return resourceModule; }; return ModuleAnalyzer; })(); exports.ModuleAnalyzer = ModuleAnalyzer; var logger = _aureliaLogging.getLogger('templating'); function ensureRegistryEntry(loader, urlOrRegistryEntry) { if (urlOrRegistryEntry instanceof _aureliaLoader.TemplateRegistryEntry) { return Promise.resolve(urlOrRegistryEntry); } return loader.loadTemplate(urlOrRegistryEntry); } var ProxyViewFactory = (function () { function ProxyViewFactory(promise) { var _this3 = this; _classCallCheck(this, ProxyViewFactory); promise.then(function (x) { return _this3.viewFactory = x; }); } ProxyViewFactory.prototype.create = function create(container, bindingContext, createInstruction, element) { return this.viewFactory.create(container, bindingContext, createInstruction, element); }; ProxyViewFactory.prototype.setCacheSize = function setCacheSize(size, doNotOverrideIfAlreadySet) { this.viewFactory.setCacheSize(size, doNotOverrideIfAlreadySet); }; ProxyViewFactory.prototype.getCachedView = function getCachedView() { return this.viewFactory.getCachedView(); }; ProxyViewFactory.prototype.returnViewToCache = function returnViewToCache(view) { this.viewFactory.returnViewToCache(view); }; _createClass(ProxyViewFactory, [{ key: 'isCaching', get: function get() { return this.viewFactory.isCaching; } }]); return ProxyViewFactory; })(); var ViewEngine = (function () { function ViewEngine(loader, container, viewCompiler, moduleAnalyzer, appResources) { _classCallCheck(this, _ViewEngine); this.loader = loader; this.container = container; this.viewCompiler = viewCompiler; this.moduleAnalyzer = moduleAnalyzer; this.appResources = appResources; this._pluginMap = {}; } ViewEngine.prototype.addResourcePlugin = function addResourcePlugin(extension, implementation) { var name = extension.replace('.', '') + '-resource-plugin'; this._pluginMap[extension] = name; this.loader.addPlugin(name, implementation); }; ViewEngine.prototype.loadViewFactory = function loadViewFactory(urlOrRegistryEntry, compileInstruction, loadContext) { var _this4 = this; loadContext = loadContext || new ResourceLoadContext(); return ensureRegistryEntry(this.loader, urlOrRegistryEntry).then(function (registryEntry) { if (registryEntry.onReady) { if (!loadContext.hasDependency(urlOrRegistryEntry)) { loadContext.addDependency(urlOrRegistryEntry); return registryEntry.onReady; } return Promise.resolve(new ProxyViewFactory(registryEntry.onReady)); } loadContext.addDependency(urlOrRegistryEntry); registryEntry.onReady = _this4.loadTemplateResources(registryEntry, compileInstruction, loadContext).then(function (resources) { registryEntry.resources = resources; var viewFactory = _this4.viewCompiler.compile(registryEntry.template, resources, compileInstruction); registryEntry.factory = viewFactory; return viewFactory; }); return registryEntry.onReady; }); }; ViewEngine.prototype.loadTemplateResources = function loadTemplateResources(registryEntry, compileInstruction, loadContext) { var resources = new ViewResources(this.appResources, registryEntry.address); var dependencies = registryEntry.dependencies; var importIds = undefined; var names = undefined; compileInstruction = compileInstruction || ViewCompileInstruction.normal; if (dependencies.length === 0 && !compileInstruction.associatedModuleId) { return Promise.resolve(resources); } importIds = dependencies.map(function (x) { return x.src; }); names = dependencies.map(function (x) { return x.name; }); logger.debug('importing resources for ' + registryEntry.address, importIds); return this.importViewResources(importIds, names, resources, compileInstruction, loadContext); }; ViewEngine.prototype.importViewModelResource = function importViewModelResource(moduleImport, moduleMember) { var _this5 = this; return this.loader.loadModule(moduleImport).then(function (viewModelModule) { var normalizedId = _aureliaMetadata.Origin.get(viewModelModule).moduleId; var resourceModule = _this5.moduleAnalyzer.analyze(normalizedId, viewModelModule, moduleMember); if (!resourceModule.mainResource) { throw new Error('No view model found in module "' + moduleImport + '".'); } resourceModule.initialize(_this5.container); return resourceModule.mainResource; }); }; ViewEngine.prototype.importViewResources = function importViewResources(moduleIds, names, resources, compileInstruction, loadContext) { var _this6 = this; loadContext = loadContext || new ResourceLoadContext(); compileInstruction = compileInstruction || ViewCompileInstruction.normal; moduleIds = moduleIds.map(function (x) { return _this6._applyLoaderPlugin(x); }); return this.loader.loadAllModules(moduleIds).then(function (imports) { var i = undefined; var ii = undefined; var analysis = undefined; var normalizedId = undefined; var current = undefined; var associatedModule = undefined; var container = _this6.container; var moduleAnalyzer = _this6.moduleAnalyzer; var allAnalysis = new Array(imports.length); for (i = 0, ii = imports.length; i < ii; ++i) { current = imports[i]; normalizedId = _aureliaMetadata.Origin.get(current).moduleId; analysis = moduleAnalyzer.analyze(normalizedId, current); analysis.initialize(container); analysis.register(resources, names[i]); allAnalysis[i] = analysis; } if (compileInstruction.associatedModuleId) { associatedModule = moduleAnalyzer.getAnalysis(compileInstruction.associatedModuleId); if (associatedModule) { associatedModule.register(resources); } } for (i = 0, ii = allAnalysis.length; i < ii; ++i) { allAnalysis[i] = allAnalysis[i].load(container, loadContext); } return Promise.all(allAnalysis).then(function () { return resources; }); }); }; ViewEngine.prototype._applyLoaderPlugin = function _applyLoaderPlugin(id) { var index = id.lastIndexOf('.'); if (index !== -1) { var ext = id.substring(index); var pluginName = this._pluginMap[ext]; if (pluginName === undefined) { return id; } return this.loader.applyPluginToUrl(id, pluginName); } return id; }; var _ViewEngine = ViewEngine; ViewEngine = _aureliaDependencyInjection.inject(_aureliaLoader.Loader, _aureliaDependencyInjection.Container, ViewCompiler, ModuleAnalyzer, ViewResources)(ViewEngine) || ViewEngine; return ViewEngine; })(); exports.ViewEngine = ViewEngine; var Controller = (function () { function Controller(behavior, instruction, viewModel) { _classCallCheck(this, Controller); this.behavior = behavior; this.instruction = instruction; this.viewModel = viewModel; this.isAttached = false; this.view = null; this.isBound = false; this.bindingContext = null; var observerLookup = behavior.observerLocator.getOrCreateObserversLookup(viewModel); var handlesBind = behavior.handlesBind; var attributes = instruction.attributes; var boundProperties = this.boundProperties = []; var properties = behavior.properties; var i = undefined; var ii = undefined; behavior._ensurePropertiesDefined(viewModel, observerLookup); for (i = 0, ii = properties.length; i < ii; ++i) { properties[i]._initialize(viewModel, observerLookup, attributes, handlesBind, boundProperties); } } Controller.prototype.created = function created(owningView) { if (this.behavior.handlesCreated) { this.viewModel.created(owningView, this.view); } }; Controller.prototype.automate = function automate(overrideContext) { this.view.bindingContext = this.viewModel; this.view.overrideContext = overrideContext || _aureliaBinding.createOverrideContext(this.viewModel); this.view._isUserControlled = true; this.bind(this.view); }; Controller.prototype.bind = function bind(scope) { var skipSelfSubscriber = this.behavior.handlesBind; var boundProperties = this.boundProperties; var i = undefined; var ii = undefined; var x = undefined; var observer = undefined; var selfSubscriber = undefined; var context = scope.bindingContext; if (this.isBound) { if (this.bindingContext === context) { return; } this.unbind(); } this.isBound = true; this.bindingContext = context; for (i = 0, ii = boundProperties.length; i < ii; ++i) { x = boundProperties[i]; observer = x.observer; selfSubscriber = observer.selfSubscriber; observer.publishing = false; if (skipSelfSubscriber) { observer.selfSubscriber = null; } x.binding.bind(scope); observer.call(); observer.publishing = true; observer.selfSubscriber = selfSubscriber; } if (this.view !== null) { if (skipSelfSubscriber) { this.view.viewModelScope = scope; } this.view.bind(this.viewModel, _aureliaBinding.createOverrideContext(this.viewModel, scope.overrideContext)); } else if (skipSelfSubscriber) { this.viewModel.bind(context, scope.overrideContext); } }; Controller.prototype.unbind = function unbind() { if (this.isBound) { var boundProperties = this.boundProperties; var i = undefined; var ii = undefined; this.isBound = false; this.scope = null; if (this.view !== null) { this.view.unbind(); } if (this.behavior.handlesUnbind) { this.viewModel.unbind(); } for (i = 0, ii = boundProperties.length; i < ii; ++i) { boundProperties[i].binding.unbind(); } } }; Controller.prototype.attached = function attached() { if (this.isAttached) { return; } this.isAttached = true; if (this.behavior.handlesAttached) { this.viewModel.attached(); } if (this.view !== null) { this.view.attached(); } }; Controller.prototype.detached = function detached() { if (this.isAttached) { this.isAttached = false; if (this.view !== null) { this.view.detached(); } if (this.behavior.handlesDetached) { this.viewModel.detached(); } } }; return Controller; })(); exports.Controller = Controller; var BehaviorPropertyObserver = (function () { function BehaviorPropertyObserver(taskQueue, obj, propertyName, selfSubscriber, initialValue) { _classCallCheck(this, _BehaviorPropertyObserver); this.taskQueue = taskQueue; this.obj = obj; this.propertyName = propertyName; this.notqueued = true; this.publishing = false; this.selfSubscriber = selfSubscriber; this.currentValue = this.oldValue = initialValue; } BehaviorPropertyObserver.prototype.getValue = function getValue() { return this.currentValue; }; BehaviorPropertyObserver.prototype.setValue = function setValue(newValue) { var oldValue = this.currentValue; if (oldValue !== newValue) { if (this.publishing && this.notqueued) { this.notqueued = false; this.taskQueue.queueMicroTask(this); } this.oldValue = oldValue; this.currentValue = newValue; } }; BehaviorPropertyObserver.prototype.call = function call() { var oldValue = this.oldValue; var newValue = this.currentValue; this.notqueued = true; if (newValue === oldValue) { return; } if (this.selfSubscriber) { this.selfSubscriber(newValue, oldValue); } this.callSubscribers(newValue, oldValue); this.oldValue = newValue; }; BehaviorPropertyObserver.prototype.subscribe = function subscribe(context, callable) { this.addSubscriber(context, callable); }; BehaviorPropertyObserver.prototype.unsubscribe = function unsubscribe(context, callable) { this.removeSubscriber(context, callable); }; var _BehaviorPropertyObserver = BehaviorPropertyObserver; BehaviorPropertyObserver = _aureliaBinding.subscriberCollection()(BehaviorPropertyObserver) || BehaviorPropertyObserver; return BehaviorPropertyObserver; })(); exports.BehaviorPropertyObserver = BehaviorPropertyObserver; function getObserver(behavior, instance, name) { var lookup = instance.__observers__; if (lookup === undefined) { lookup = behavior.observerLocator.getOrCreateObserversLookup(instance); behavior._ensurePropertiesDefined(instance, lookup); } return lookup[name]; } var BindableProperty = (function () { function BindableProperty(nameOrConfig) { _classCallCheck(this, BindableProperty); if (typeof nameOrConfig === 'string') { this.name = nameOrConfig; } else { Object.assign(this, nameOrConfig); } this.attribute = this.attribute || _hyphenate(this.name); this.defaultBindingMode = this.defaultBindingMode || _aureliaBinding.bindingMode.oneWay; this.changeHandler = this.changeHandler || null; this.owner = null; this.descriptor = null; } BindableProperty.prototype.registerWith = function registerWith(target, behavior, descriptor) { behavior.properties.push(this); behavior.attributes[this.attribute] = this; this.owner = behavior; if (descriptor) { this.descriptor = descriptor; return this._configureDescriptor(behavior, descriptor); } }; BindableProperty.prototype._configureDescriptor = function _configureDescriptor(behavior, descriptor) { var name = this.name; descriptor.configurable = true; descriptor.enumerable = true; if ('initializer' in descriptor) { this.defaultValue = descriptor.initializer; delete descriptor.initializer; delete descriptor.writable; } if ('value' in descriptor) { this.defaultValue = descriptor.value; delete descriptor.value; delete descriptor.writable; } descriptor.get = function () { return getObserver(behavior, this, name).getValue(); }; descriptor.set = function (value) { getObserver(behavior, this, name).setValue(value); }; descriptor.get.getObserver = function (obj) { return getObserver(behavior, obj, name); }; return descriptor; }; BindableProperty.prototype.defineOn = function defineOn(target, behavior) { var name = this.name; var handlerName = undefined; if (this.changeHandler === null) { handlerName = name + 'Changed'; if (handlerName in target.prototype) { this.changeHandler = handlerName; } } if (this.descriptor === null) { Object.defineProperty(target.prototype, name, this._configureDescriptor(behavior, {})); } }; BindableProperty.prototype.createObserver = function createObserver(viewModel) { var selfSubscriber = null; var defaultValue = this.defaultValue; var changeHandlerName = this.changeHandler; var name = this.name; var initialValue = undefined; if (this.hasOptions) { return undefined; } if (changeHandlerName in viewModel) { if ('propertyChanged' in viewModel) { selfSubscriber = function (newValue, oldValue) { viewModel[changeHandlerName](newValue, oldValue); viewModel.propertyChanged(name, newValue, oldValue); }; } else { selfSubscriber = function (newValue, oldValue) { return viewModel[changeHandlerName](newValue, oldValue); }; } } else if ('propertyChanged' in viewModel) { selfSubscriber = function (newValue, oldValue) { return viewModel.propertyChanged(name, newValue, oldValue); }; } else if (changeHandlerName !== null) { throw new Error('Change handler ' + changeHandlerName + ' was specified but not delcared on the class.'); } if (defaultValue !== undefined) { initialValue = typeof defaultValue === 'function' ? defaultValue.call(viewModel) : defaultValue; } return new BehaviorPropertyObserver(this.owner.taskQueue, viewModel, this.name, selfSubscriber, initialValue); }; BindableProperty.prototype._initialize = function _initialize(viewModel, observerLookup, attributes, behaviorHandlesBind, boundProperties) { var selfSubscriber = undefined; var observer = undefined; var attribute = undefined; var defaultValue = this.defaultValue; if (this.isDynamic) { for (var key in attributes) { this._createDynamicProperty(viewModel, observerLookup, behaviorHandlesBind, key, attributes[key], boundProperties); } } else if (!this.hasOptions) { observer = observerLookup[this.name]; if (attributes !== null) { selfSubscriber = observer.selfSubscriber; attribute = attributes[this.attribute]; if (behaviorHandlesBind) { observer.selfSubscriber = null; } if (typeof attribute === 'string') { viewModel[this.name] = attribute; observer.call(); } else if (attribute) { boundProperties.push({ observer: observer, binding: attribute.createBinding(viewModel) }); } else if (defaultValue !== undefined) { observer.call(); } observer.selfSubscriber = selfSubscriber; } observer.publishing = true; } }; BindableProperty.prototype._createDynamicProperty = function _createDynamicProperty(viewModel, observerLookup, behaviorHandlesBind, name, attribute, boundProperties) { var changeHandlerName = name + 'Changed'; var selfSubscriber = null; var observer = undefined; var info = undefined; if (changeHandlerName in viewModel) { if ('propertyChanged' in viewModel) { selfSubscriber = function (newValue, oldValue) { viewModel[changeHandlerName](newValue, oldValue); viewModel.propertyChanged(name, newValue, oldValue); }; } else { selfSubscriber = function (newValue, oldValue) { return viewModel[changeHandlerName](newValue, oldValue); }; } } else if ('propertyChanged' in viewModel) { selfSubscriber = function (newValue, oldValue) { return viewModel.propertyChanged(name, newValue, oldValue); }; } observer = observerLookup[name] = new BehaviorPropertyObserver(this.owner.taskQueue, viewModel, name, selfSubscriber); Object.defineProperty(viewModel, name, { configurable: true, enumerable: true, get: observer.getValue.bind(observer), set: observer.setValue.bind(observer) }); if (behaviorHandlesBind) { observer.selfSubscriber = null; } if (typeof attribute === 'string') { viewModel[name] = attribute; observer.call(); } else if (attribute) { info = { observer: observer, binding: attribute.createBinding(viewModel) }; boundProperties.push(info); } observer.publishing = true; observer.selfSubscriber = selfSubscriber; }; return BindableProperty; })(); exports.BindableProperty = BindableProperty; var contentSelectorViewCreateInstruction = { enhance: false }; var lastProviderId = 0; function nextProviderId() { return ++lastProviderId; } function doProcessContent() { return true; } var HtmlBehaviorResource = (function () { function HtmlBehaviorResource() { _classCallCheck(this, HtmlBehaviorResource); this.elementName = null; this.attributeName = null; this.attributeDefaultBindingMode = undefined; this.liftsContent = false; this.targetShadowDOM = false; this.processContent = doProcessContent; this.usesShadowDOM = false; this.childBindings = null; this.hasDynamicOptions = false; this.containerless = false; this.properties = []; this.attributes = {}; } HtmlBehaviorResource.convention = function convention(name, existing) { var behavior = undefined; if (name.endsWith('CustomAttribute')) { behavior = existing || new HtmlBehaviorResource(); behavior.attributeName = _hyphenate(name.substring(0, name.length - 15)); } if (name.endsWith('CustomElement')) { behavior = existing || new HtmlBehaviorResource(); behavior.elementName = _hyphenate(name.substring(0, name.length - 13)); } return behavior; }; HtmlBehaviorResource.prototype.addChildBinding = function addChildBinding(behavior) { if (this.childBindings === null) { this.childBindings = []; } this.childBindings.push(behavior); }; HtmlBehaviorResource.prototype.initialize = function initialize(container, target) { var proto = target.prototype; var properties = this.properties; var attributeName = this.attributeName; var attributeDefaultBindingMode = this.attributeDefaultBindingMode; var i = undefined; var ii = undefined; var current = undefined; target.__providerId__ = nextProviderId(); this.observerLocator = container.get(_aureliaBinding.ObserverLocator); this.taskQueue = container.get(_aureliaTaskQueue.TaskQueue); this.target = target; this.usesShadowDOM = this.targetShadowDOM && _aureliaPal.FEATURE.shadowDOM; this.handlesCreated = 'created' in proto; this.handlesBind = 'bind' in proto; this.handlesUnbind = 'unbind' in proto; this.handlesAttached = 'attached' in proto; this.handlesDetached = 'detached' in proto; this.htmlName = this.elementName || this.attributeName; if (attributeName !== null) { if (properties.length === 0) { new BindableProperty({ name: 'value', changeHandler: 'valueChanged' in proto ? 'valueChanged' : null, attribute: attributeName, defaultBindingMode: attributeDefaultBindingMode }).registerWith(target, this); } current = properties[0]; if (properties.length === 1 && current.name === 'value') { current.isDynamic = current.hasOptions = this.hasDynamicOptions; current.defineOn(target, this); } else { for (i = 0, ii = properties.length; i < ii; ++i) { properties[i].defineOn(target, this); } current = new BindableProperty({ name: 'value', changeHandler: 'valueChanged' in proto ? 'valueChanged' : null, attribute: attributeName, defaultBindingMode: attributeDefaultBindingMode }); current.hasOptions = true; current.registerWith(target, this); } } else { for (i = 0, ii = properties.length; i < ii; ++i) { properties[i].defineOn(target, this); } } }; HtmlBehaviorResource.prototype.register = function register(registry, name) { if (this.attributeName !== null) { registry.registerAttribute(name || this.attributeName, this, this.attributeName); } if (this.elementName !== null) { registry.registerElement(name || this.elementName, this); } }; HtmlBehaviorResource.prototype.load = function load(container, target, loadContext, viewStrategy, transientView) { var _this7 = this; var options = undefined; if (this.elementName !== null) { viewStrategy = container.get(ViewLocator).getViewStrategy(viewStrategy || this.viewStrategy || target); options = new ViewCompileInstruction(this.targetShadowDOM, true); if (!viewStrategy.moduleId) { viewStrategy.moduleId = _aureliaMetadata.Origin.get(target).moduleId; } return viewStrategy.loadViewFactory(container.get(ViewEngine), options, loadContext).then(function (viewFactory) { if (!transientView || !_this7.viewFactory) { _this7.viewFactory = viewFactory; } return viewFactory; }); } return Promise.resolve(this); }; HtmlBehaviorResource.prototype.compile = function compile(compiler, resources, node, instruction, parentNode) { if (this.liftsContent) { if (!instruction.viewFactory) { var template = _aureliaPal.DOM.createElement('template'); var fragment = _aureliaPal.DOM.createDocumentFragment(); var cacheSize = node.getAttribute('view-cache'); var part = node.getAttribute('part'); node.removeAttribute(instruction.originalAttrName); _aureliaPal.DOM.replaceNode(template, node, parentNode); fragment.appendChild(node); instruction.viewFactory = compiler.compile(fragment, resources); if (part) { instruction.viewFactory.part = part; node.removeAttribute('part'); } if (cacheSize) { instruction.viewFactory.setCacheSize(cacheSize); node.removeAttribute('view-cache'); } node = template; } } else if (this.elementName !== null) { var _partReplacements2 = instruction.partReplacements = {}; if (this.processContent(compiler, resources, node, instruction) && node.hasChildNodes()) { if (this.usesShadowDOM) { var currentChild = node.firstChild; var nextSibling = undefined; var toReplace = undefined; while (currentChild) { nextSibling = currentChild.nextSibling; if (currentChild.tagName === 'TEMPLATE' && (toReplace = currentChild.getAttribute('replace-part'))) { _partReplacements2[toReplace] = compiler.compile(currentChild, resources); _aureliaPal.DOM.removeNode(currentChild, parentNode); } currentChild = nextSibling; } instruction.skipContentProcessing = false; } else { var fragment = _aureliaPal.DOM.createDocumentFragment(); var currentChild = node.firstChild; var nextSibling = undefined; var toReplace = undefined; while (currentChild) { nextSibling = currentChild.nextSibling; if (currentChild.tagName === 'TEMPLATE' && (toReplace = currentChild.getAttribute('replace-part'))) { _partReplacements2[toReplace] = compiler.compile(currentChild, resources); _aureliaPal.DOM.removeNode(currentChild, parentNode); } else { fragment.appendChild(currentChild); } currentChild = nextSibling; } instruction.contentFactory = compiler.compile(fragment, resources); instruction.skipContentProcessing = true; } } else { instruction.skipContentProcessing = true; } } return node; }; HtmlBehaviorResource.prototype.create = function create(container, instruction, element, bindings) { var host = undefined; var au = null; instruction = instruction || BehaviorInstruction.normal; element = element || null; bindings = bindings || null; if (this.elementName !== null && element) { if (this.usesShadowDOM) { host = element.createShadowRoot(); container.registerInstance(_aureliaPal.DOM.boundary, host); } else { host = element; if (this.targetShadowDOM) { container.registerInstance(_aureliaPal.DOM.boundary, host); } } } if (element !== null) { element.au = au = element.au || {}; } var viewModel = instruction.viewModel || container.get(this.target); var controller = new Controller(this, instruction, viewModel); var childBindings = this.childBindings; var viewFactory = undefined; if (this.liftsContent) { au.controller = controller; } else if (this.elementName !== null) { viewFactory = instruction.viewFactory || this.viewFactory; container.viewModel = viewModel; if (viewFactory) { controller.view = viewFactory.create(container, instruction, element); } if (element !== null) { au.controller = controller; if (controller.view) { if (!this.usesShadowDOM) { if (instruction.contentFactory) { var contentView = instruction.contentFactory.create(container, contentSelectorViewCreateInstruction); _ContentSelector.applySelectors(contentView, controller.view.contentSelectors, function (contentSelector, group) { return contentSelector.add(group); }); controller.contentView = contentView; } } if (instruction.anchorIsContainer) { if (childBindings !== null) { for (var i = 0, ii = childBindings.length; i < ii; ++i) { controller.view.addBinding(childBindings[i].create(element, viewModel)); } } controller.view.appendNodesTo(host); } else { controller.view.insertNodesBefore(host); } } else if (childBindings !== null) { for (var i = 0, ii = childBindings.length; i < ii; ++i) { bindings.push(childBindings[i].create(element, viewModel)); } } } else if (controller.view) { controller.view.controller = controller; if (childBindings !== null) { for (var i = 0, ii = childBindings.length; i < ii; ++i) { controller.view.addBinding(childBindings[i].create(instruction.host, viewModel)); } } } else if (childBindings !== null) { for (var i = 0, ii = childBindings.length; i < ii; ++i) { bindings.push(childBindings[i].create(instruction.host, viewModel)); } } } else if (childBindings !== null) { for (var i = 0, ii = childBindings.length; i < ii; ++i) { bindings.push(childBindings[i].create(element, viewModel)); } } if (au !== null) { au[this.htmlName] = controller; } if (instruction.initiatedByBehavior && viewFactory) { controller.view.created(); } return controller; }; HtmlBehaviorResource.prototype._ensurePropertiesDefined = function _ensurePropertiesDefined(instance, lookup) { var properties = undefined; var i = undefined; var ii = undefined; var observer = undefined; if ('__propertiesDefined__' in lookup) { return; } lookup.__propertiesDefined__ = true; properties = this.properties; for (i = 0, ii = properties.length; i < ii; ++i) { observer = properties[i].createObserver(instance); if (observer !== undefined) { lookup[observer.propertyName] = observer; } } }; return HtmlBehaviorResource; })(); exports.HtmlBehaviorResource = HtmlBehaviorResource; function createChildObserverDecorator(selectorOrConfig, all) { return function (target, key, descriptor) { var actualTarget = descriptor ? target.constructor : target; var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, actualTarget); if (typeof selectorOrConfig === 'string') { selectorOrConfig = { selector: selectorOrConfig, name: key }; } if (descriptor) { descriptor.writable = true; } selectorOrConfig.all = all; r.addChildBinding(new ChildObserver(selectorOrConfig)); }; } function children(selectorOrConfig) { return createChildObserverDecorator(selectorOrConfig, true); } function child(selectorOrConfig) { return createChildObserverDecorator(selectorOrConfig, false); } var ChildObserver = (function () { function ChildObserver(config) { _classCallCheck(this, ChildObserver); this.name = config.name; this.changeHandler = config.changeHandler || this.name + 'Changed'; this.selector = config.selector; this.all = config.all; } ChildObserver.prototype.create = function create(target, viewModel) { return new ChildObserverBinder(this.selector, target, this.name, viewModel, this.changeHandler, this.all); }; return ChildObserver; })(); var noMutations = []; function trackMutation(groupedMutations, binder, record) { var mutations = groupedMutations.get(binder); if (!mutations) { mutations = []; groupedMutations.set(binder, mutations); } mutations.push(record); } function onChildChange(mutations, observer) { var binders = observer.binders; var bindersLength = binders.length; var groupedMutations = new Map(); for (var i = 0, ii = mutations.length; i < ii; ++i) { var record = mutations[i]; var added = record.addedNodes; var removed = record.removedNodes; for (var j = 0, jj = removed.length; j < jj; ++j) { var node = removed[j]; if (node.nodeType === 1) { for (var k = 0; k < bindersLength; ++k) { var binder = binders[k]; if (binder.onRemove(node)) { trackMutation(groupedMutations, binder, record); } } } } for (var j = 0, jj = added.length; j < jj; ++j) { var node = added[j]; if (node.nodeType === 1) { for (var k = 0; k < bindersLength; ++k) { var binder = binders[k]; if (binder.onAdd(node)) { trackMutation(groupedMutations, binder, record); } } } } } groupedMutations.forEach(function (value, key) { if (key.changeHandler !== null) { key.viewModel[key.changeHandler](value); } }); } var ChildObserverBinder = (function () { function ChildObserverBinder(selector, target, property, viewModel, changeHandler, all) { _classCallCheck(this, ChildObserverBinder); this.selector = selector; this.target = target; this.property = property; this.viewModel = viewModel; this.changeHandler = changeHandler in viewModel ? changeHandler : null; this.all = all; } ChildObserverBinder.prototype.bind = function bind(source) { var target = this.target; var viewModel = this.viewModel; var selector = this.selector; var current = target.firstElementChild; var observer = target.__childObserver__; if (!observer) { observer = target.__childObserver__ = _aureliaPal.DOM.createMutationObserver(onChildChange); observer.observe(target, { childList: true }); observer.binders = []; } observer.binders.push(this); if (this.all) { var items = viewModel[this.property]; if (!items) { items = viewModel[this.property] = []; } else { items.length = 0; } while (current) { if (current.matches(selector)) { items.push(current.au && current.au.controller ? current.au.controller.viewModel : current); } current = current.nextElementSibling; } if (this.changeHandler !== null) { this.viewModel[this.changeHandler](noMutations); } } else { while (current) { if (current.matches(selector)) { var value = current.au && current.au.controller ? current.au.controller.viewModel : current; this.viewModel[this.property] = value; if (this.changeHandler !== null) { this.viewModel[this.changeHandler](value); } break; } current = current.nextElementSibling; } } }; ChildObserverBinder.prototype.onRemove = function onRemove(element) { if (element.matches(this.selector)) { var value = element.au && element.au.controller ? element.au.controller.viewModel : element; if (this.all) { var items = this.viewModel[this.property]; var index = items.indexOf(value); if (index !== -1) { items.splice(index, 1); } return true; } return false; } }; ChildObserverBinder.prototype.onAdd = function onAdd(element) { var selector = this.selector; if (element.matches(selector)) { var value = element.au && element.au.controller ? element.au.controller.viewModel : element; if (this.all) { var items = this.viewModel[this.property]; var index = 0; var prev = element.previousElementSibling; while (prev) { if (prev.matches(selector)) { index++; } prev = prev.previousElementSibling; } items.splice(index, 0, value); return true; } this.viewModel[this.property] = value; if (this.changeHandler !== null) { this.viewModel[this.changeHandler](value); } } return false; }; ChildObserverBinder.prototype.unbind = function unbind() { if (this.target.__childObserver__) { this.target.__childObserver__.disconnect(); this.target.__childObserver__ = null; } }; return ChildObserverBinder; })(); function tryActivateViewModel(context) { if (context.skipActivation || typeof context.viewModel.activate !== 'function') { return Promise.resolve(); } return context.viewModel.activate(context.model) || Promise.resolve(); } var CompositionEngine = (function () { function CompositionEngine(viewEngine, viewLocator) { _classCallCheck(this, _CompositionEngine); this.viewEngine = viewEngine; this.viewLocator = viewLocator; } CompositionEngine.prototype._createControllerAndSwap = function _createControllerAndSwap(context) { var _this8 = this; var removeResponse = context.viewSlot.removeAll(true); var afterRemove = function afterRemove() { return _this8.createController(context).then(function (controller) { if (context.currentController) { context.currentController.unbind(); } controller.automate(); context.viewSlot.add(controller.view); return controller; }); }; if (removeResponse instanceof Promise) { return removeResponse.then(afterRemove); } return afterRemove(); }; CompositionEngine.prototype.createController = function createController(context) { var _this9 = this; var childContainer = undefined; var viewModel = undefined; var viewModelResource = undefined; var metadata = undefined; return this.ensureViewModel(context).then(tryActivateViewModel).then(function () { childContainer = context.childContainer; viewModel = context.viewModel; viewModelResource = context.viewModelResource; metadata = viewModelResource.metadata; var viewStrategy = _this9.viewLocator.getViewStrategy(context.view || viewModel); if (context.viewResources) { viewStrategy.makeRelativeTo(context.viewResources.viewUrl); } return metadata.load(childContainer, viewModelResource.value, null, viewStrategy, true); }).then(function (viewFactory) { return metadata.create(childContainer, BehaviorInstruction.dynamic(context.host, viewModel, viewFactory)); }); }; CompositionEngine.prototype.ensureViewModel = function ensureViewModel(context) { var childContainer = context.childContainer = context.childContainer || context.container.createChild(); if (typeof context.viewModel === 'string') { context.viewModel = context.viewResources ? context.viewResources.relativeToView(context.viewModel) : context.viewModel; return this.viewEngine.importViewModelResource(context.viewModel).then(function (viewModelResource) { childContainer.autoRegister(viewModelResource.value); if (context.host) { childContainer.registerInstance(_aureliaPal.DOM.Element, context.host); } context.viewModel = childContainer.viewModel = childContainer.get(viewModelResource.value); context.viewModelResource = viewModelResource; return context; }); } var metadata = new HtmlBehaviorResource(); metadata.elementName = 'dynamic-element'; metadata.initialize(context.container || childContainer, context.viewModel.constructor); context.viewModelResource = { metadata: metadata, value: context.viewModel.constructor }; childContainer.viewModel = context.viewModel; return Promise.resolve(context); }; CompositionEngine.prototype.compose = function compose(context) { context.childContainer = context.childContainer || context.container.createChild(); context.view = this.viewLocator.getViewStrategy(context.view); if (context.viewModel) { return this._createControllerAndSwap(context); } else if (context.view) { if (context.viewResources) { context.view.makeRelativeTo(context.viewResources.viewUrl); } return context.view.loadViewFactory(this.viewEngine, new ViewCompileInstruction()).then(function (viewFactory) { var removeResponse = context.viewSlot.removeAll(true); if (removeResponse instanceof Promise) { return removeResponse.then(function () { var result = viewFactory.create(context.childContainer); result.bind(context.bindingContext, context.overrideContext); context.viewSlot.add(result); return result; }); } var result = viewFactory.create(context.childContainer); result.bind(context.bindingContext, context.overrideContext); context.viewSlot.add(result); return result; }); } else if (context.viewSlot) { context.viewSlot.removeAll(); return Promise.resolve(null); } }; var _CompositionEngine = CompositionEngine; CompositionEngine = _aureliaDependencyInjection.inject(ViewEngine, ViewLocator)(CompositionEngine) || CompositionEngine; return CompositionEngine; })(); exports.CompositionEngine = CompositionEngine; var ElementConfigResource = (function () { function ElementConfigResource() { _classCallCheck(this, ElementConfigResource); } ElementConfigResource.prototype.initialize = function initialize(container, target) {}; ElementConfigResource.prototype.register = function register(registry, name) {}; ElementConfigResource.prototype.load = function load(container, target) { var config = new Target(); var eventManager = container.get(_aureliaBinding.EventManager); eventManager.registerElementConfig(config); }; return ElementConfigResource; })(); exports.ElementConfigResource = ElementConfigResource; function validateBehaviorName(name, type) { if (/[A-Z]/.test(name)) { throw new Error('\'' + name + '\' is not a valid ' + type + ' name. Upper-case letters are not allowed because the DOM is not case-sensitive.'); } } function resource(instance) { return function (target) { _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, instance, target); }; } function behavior(override) { return function (target) { if (override instanceof HtmlBehaviorResource) { _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, override, target); } else { var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, target); Object.assign(r, override); } }; } function customElement(name) { validateBehaviorName(name, 'custom element'); return function (target) { var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, target); r.elementName = name; }; } function customAttribute(name, defaultBindingMode) { validateBehaviorName(name, 'custom attribute'); return function (target) { var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, target); r.attributeName = name; r.attributeDefaultBindingMode = defaultBindingMode; }; } function templateController(target) { var deco = function deco(t) { var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); r.liftsContent = true; }; return target ? deco(target) : deco; } function bindable(nameOrConfigOrTarget, key, descriptor) { var deco = function deco(target, key2, descriptor2) { var actualTarget = key2 ? target.constructor : target; var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, actualTarget); var prop = undefined; if (key2) { nameOrConfigOrTarget = nameOrConfigOrTarget || {}; nameOrConfigOrTarget.name = key2; } prop = new BindableProperty(nameOrConfigOrTarget); return prop.registerWith(actualTarget, r, descriptor2); }; if (!nameOrConfigOrTarget) { return deco; } if (key) { var target = nameOrConfigOrTarget; nameOrConfigOrTarget = null; return deco(target, key, descriptor); } return deco; } function dynamicOptions(target) { var deco = function deco(t) { var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); r.hasDynamicOptions = true; }; return target ? deco(target) : deco; } function useShadowDOM(target) { var deco = function deco(t) { var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); r.targetShadowDOM = true; }; return target ? deco(target) : deco; } function doNotProcessContent() { return false; } function processContent(processor) { return function (t) { var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); r.processContent = processor || doNotProcessContent; }; } function containerless(target) { var deco = function deco(t) { var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t); r.containerless = true; }; return target ? deco(target) : deco; } function useViewStrategy(strategy) { return function (target) { _aureliaMetadata.metadata.define(ViewLocator.viewStrategyMetadataKey, strategy, target); }; } function useView(path) { return useViewStrategy(new RelativeViewStrategy(path)); } function inlineView(markup, dependencies, dependencyBaseUrl) { return useViewStrategy(new InlineViewStrategy(markup, dependencies, dependencyBaseUrl)); } function noView(target) { var deco = function deco(t) { _aureliaMetadata.metadata.define(ViewLocator.viewStrategyMetadataKey, new NoViewStrategy(), t); }; return target ? deco(target) : deco; } function elementConfig(target) { var deco = function deco(t) { _aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ElementConfigResource(), t); }; return target ? deco(target) : deco; } var TemplatingEngine = (function () { function TemplatingEngine(container, moduleAnalyzer, viewCompiler, compositionEngine) { _classCallCheck(this, _TemplatingEngine); this._container = container; this._moduleAnalyzer = moduleAnalyzer; this._viewCompiler = viewCompiler; this._compositionEngine = compositionEngine; container.registerInstance(Animator, Animator.instance = new Animator()); } TemplatingEngine.prototype.configureAnimator = function configureAnimator(animator) { this._container.unregister(Animator); this._container.registerInstance(Animator, Animator.instance = animator); }; TemplatingEngine.prototype.compose = function compose(context) { return this._compositionEngine.compose(context); }; TemplatingEngine.prototype.enhance = function enhance(instruction) { if (instruction instanceof _aureliaPal.DOM.Element) { instruction = { element: instruction }; } var compilerInstructions = {}; var resources = instruction.resources || this._container.get(ViewResources); this._viewCompiler._compileNode(instruction.element, resources, compilerInstructions, instruction.element.parentNode, 'root', true); var factory = new ViewFactory(instruction.element, compilerInstructions, resources); var container = instruction.container || this._container.createChild(); var view = factory.create(container, BehaviorInstruction.enhance()); view.bind(instruction.bindingContext || {}); return view; }; TemplatingEngine.prototype.createControllerForUnitTest = function createControllerForUnitTest(viewModelType, attributesFromHTML) { var _moduleAnalyzer$analyze; var exportName = viewModelType.name; var resourceModule = this._moduleAnalyzer.analyze('test-module', (_moduleAnalyzer$analyze = {}, _moduleAnalyzer$analyze[exportName] = viewModelType, _moduleAnalyzer$analyze), exportName); var description = resourceModule.mainResource; description.initialize(this._container); var viewModel = this._container.get(viewModelType); var instruction = BehaviorInstruction.unitTest(description, attributesFromHTML); return new Controller(description.metadata, instruction, viewModel); }; TemplatingEngine.prototype.createViewModelForUnitTest = function createViewModelForUnitTest(viewModelType, attributesFromHTML, bindingContext) { var controller = this.createControllerForUnitTest(viewModelType, attributesFromHTML); controller.bind(_aureliaBinding.createScopeForTest(bindingContext)); return controller.viewModel; }; var _TemplatingEngine = TemplatingEngine; TemplatingEngine = _aureliaDependencyInjection.inject(_aureliaDependencyInjection.Container, ModuleAnalyzer, ViewCompiler, CompositionEngine)(TemplatingEngine) || TemplatingEngine; return TemplatingEngine; })(); exports.TemplatingEngine = TemplatingEngine; }); define('aurelia-framework',['exports', 'core-js', 'aurelia-logging', 'aurelia-templating', 'aurelia-path', 'aurelia-dependency-injection', 'aurelia-loader', 'aurelia-pal', 'aurelia-binding', 'aurelia-metadata', 'aurelia-task-queue'], function (exports, _coreJs, _aureliaLogging, _aureliaTemplating, _aureliaPath, _aureliaDependencyInjection, _aureliaLoader, _aureliaPal, _aureliaBinding, _aureliaMetadata, _aureliaTaskQueue) { exports.__esModule = true; function _interopExportWildcard(obj, defaults) { var newObj = defaults({}, obj); delete newObj['default']; return newObj; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var logger = _aureliaLogging.getLogger('aurelia'); function runTasks(config, tasks) { var current = undefined; var next = function next() { if (current = tasks.shift()) { return Promise.resolve(current(config)).then(next); } return Promise.resolve(); }; return next(); } function loadPlugin(config, loader, info) { logger.debug('Loading plugin ' + info.moduleId + '.'); config.resourcesRelativeTo = info.resourcesRelativeTo; return loader.loadModule(info.moduleId).then(function (m) { if ('configure' in m) { return Promise.resolve(m.configure(config, info.config || {})).then(function () { config.resourcesRelativeTo = null; logger.debug('Configured plugin ' + info.moduleId + '.'); }); } config.resourcesRelativeTo = null; logger.debug('Loaded plugin ' + info.moduleId + '.'); }); } function loadResources(container, resourcesToLoad, appResources) { var viewEngine = container.get(_aureliaTemplating.ViewEngine); var importIds = Object.keys(resourcesToLoad); var names = new Array(importIds.length); for (var i = 0, ii = importIds.length; i < ii; ++i) { names[i] = resourcesToLoad[importIds[i]]; } return viewEngine.importViewResources(importIds, names, appResources); } function assertProcessed(plugins) { if (plugins.processed) { throw new Error('This config instance has already been applied. To load more plugins or global resources, create a new FrameworkConfiguration instance.'); } } var FrameworkConfiguration = (function () { function FrameworkConfiguration(aurelia) { var _this = this; _classCallCheck(this, FrameworkConfiguration); this.aurelia = aurelia; this.container = aurelia.container; this.info = []; this.processed = false; this.preTasks = []; this.postTasks = []; this.resourcesToLoad = {}; this.preTask(function () { return _this.bootstrapperName = aurelia.loader.normalizeSync('aurelia-bootstrapper'); }); this.postTask(function () { return loadResources(aurelia.container, _this.resourcesToLoad, aurelia.resources); }); } FrameworkConfiguration.prototype.instance = function instance(type, _instance) { this.container.registerInstance(type, _instance); return this; }; FrameworkConfiguration.prototype.singleton = function singleton(type, implementation) { this.container.registerSingleton(type, implementation); return this; }; FrameworkConfiguration.prototype.transient = function transient(type, implementation) { this.container.registerTransient(type, implementation); return this; }; FrameworkConfiguration.prototype.preTask = function preTask(task) { assertProcessed(this); this.preTasks.push(task); return this; }; FrameworkConfiguration.prototype.postTask = function postTask(task) { assertProcessed(this); this.postTasks.push(task); return this; }; FrameworkConfiguration.prototype.feature = function feature(plugin, config) { plugin = plugin.endsWith('.js') || plugin.endsWith('.ts') ? plugin.substring(0, plugin.length - 3) : plugin; return this.plugin({ moduleId: plugin + '/index', resourcesRelativeTo: plugin, config: config || {} }); }; FrameworkConfiguration.prototype.globalResources = function globalResources(resources) { assertProcessed(this); var toAdd = Array.isArray(resources) ? resources : arguments; var resource = undefined; var path = undefined; var resourcesRelativeTo = this.resourcesRelativeTo || ''; for (var i = 0, ii = toAdd.length; i < ii; ++i) { resource = toAdd[i]; if (typeof resource !== 'string') { throw new Error('Invalid resource path [' + resource + ']. Resources must be specified as relative module IDs.'); } path = _aureliaPath.join(resourcesRelativeTo, resource); this.resourcesToLoad[path] = this.resourcesToLoad[path]; } return this; }; FrameworkConfiguration.prototype.globalName = function globalName(resourcePath, newName) { assertProcessed(this); this.resourcesToLoad[resourcePath] = newName; return this; }; FrameworkConfiguration.prototype.plugin = function plugin(_plugin, config) { assertProcessed(this); if (typeof _plugin === 'string') { _plugin = _plugin.endsWith('.js') || _plugin.endsWith('.ts') ? _plugin.substring(0, _plugin.length - 3) : _plugin; return this.plugin({ moduleId: _plugin, resourcesRelativeTo: _plugin, config: config || {} }); } this.info.push(_plugin); return this; }; FrameworkConfiguration.prototype._addNormalizedPlugin = function _addNormalizedPlugin(name, config) { var _this2 = this; var plugin = { moduleId: name, resourcesRelativeTo: name, config: config || {} }; this.plugin(plugin); this.preTask(function () { var normalizedName = _this2.aurelia.loader.normalizeSync(name, _this2.bootstrapperName); normalizedName = normalizedName.endsWith('.js') || normalizedName.endsWith('.ts') ? normalizedName.substring(0, normalizedName.length - 3) : normalizedName; plugin.moduleId = normalizedName; plugin.resourcesRelativeTo = normalizedName; _this2.aurelia.loader.map(name, normalizedName); }); return this; }; FrameworkConfiguration.prototype.defaultBindingLanguage = function defaultBindingLanguage() { return this._addNormalizedPlugin('aurelia-templating-binding'); }; FrameworkConfiguration.prototype.router = function router() { return this._addNormalizedPlugin('aurelia-templating-router'); }; FrameworkConfiguration.prototype.history = function history() { return this._addNormalizedPlugin('aurelia-history-browser'); }; FrameworkConfiguration.prototype.defaultResources = function defaultResources() { return this._addNormalizedPlugin('aurelia-templating-resources'); }; FrameworkConfiguration.prototype.eventAggregator = function eventAggregator() { return this._addNormalizedPlugin('aurelia-event-aggregator'); }; FrameworkConfiguration.prototype.standardConfiguration = function standardConfiguration() { return this.defaultBindingLanguage().defaultResources().history().router().eventAggregator(); }; FrameworkConfiguration.prototype.developmentLogging = function developmentLogging() { var _this3 = this; this.preTask(function () { var name = _this3.aurelia.loader.normalizeSync('aurelia-logging-console', _this3.bootstrapperName); return _this3.aurelia.loader.loadModule(name).then(function (m) { _aureliaLogging.addAppender(new m.ConsoleAppender()); _aureliaLogging.setLevel(_aureliaLogging.logLevel.debug); }); }); return this; }; FrameworkConfiguration.prototype.apply = function apply() { var _this4 = this; if (this.processed) { return Promise.resolve(); } return runTasks(this, this.preTasks).then(function () { var loader = _this4.aurelia.loader; var info = _this4.info; var current = undefined; var next = function next() { if (current = info.shift()) { return loadPlugin(_this4, loader, current).then(next); } _this4.processed = true; return Promise.resolve(); }; return next().then(function () { return runTasks(_this4, _this4.postTasks); }); }); }; return FrameworkConfiguration; })(); exports.FrameworkConfiguration = FrameworkConfiguration; function preventActionlessFormSubmit() { _aureliaPal.DOM.addEventListener('submit', function (evt) { var target = evt.target; var action = target.action; if (target.tagName.toLowerCase() === 'form' && !action) { evt.preventDefault(); } }); } var Aurelia = (function () { function Aurelia(loader, container, resources) { _classCallCheck(this, Aurelia); this.loader = loader || new _aureliaPal.PLATFORM.Loader(); this.container = container || new _aureliaDependencyInjection.Container().makeGlobal(); this.resources = resources || new _aureliaTemplating.ViewResources(); this.use = new FrameworkConfiguration(this); this.logger = _aureliaLogging.getLogger('aurelia'); this.hostConfigured = false; this.host = null; this.use.instance(Aurelia, this); this.use.instance(_aureliaLoader.Loader, this.loader); this.use.instance(_aureliaTemplating.ViewResources, this.resources); } Aurelia.prototype.start = function start() { var _this5 = this; if (this.started) { return Promise.resolve(this); } this.started = true; this.logger.info('Aurelia Starting'); return this.use.apply().then(function () { preventActionlessFormSubmit(); if (!_this5.container.hasResolver(_aureliaTemplating.BindingLanguage)) { var message = 'You must configure Aurelia with a BindingLanguage implementation.'; _this5.logger.error(message); throw new Error(message); } _this5.logger.info('Aurelia Started'); var evt = _aureliaPal.DOM.createCustomEvent('aurelia-started', { bubbles: true, cancelable: true }); _aureliaPal.DOM.dispatchEvent(evt); return _this5; }); }; Aurelia.prototype.enhance = function enhance() { var _this6 = this; var bindingContext = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var applicationHost = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; this._configureHost(applicationHost); return new Promise(function (resolve) { var engine = _this6.container.get(_aureliaTemplating.TemplatingEngine); _this6.root = engine.enhance({ container: _this6.container, element: _this6.host, resources: _this6.resources, bindingContext: bindingContext }); _this6.root.attached(); _this6._onAureliaComposed(); return _this6; }); }; Aurelia.prototype.setRoot = function setRoot() { var _this7 = this; var root = arguments.length <= 0 || arguments[0] === undefined ? 'app' : arguments[0]; var applicationHost = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; var engine = undefined; var instruction = {}; this._configureHost(applicationHost); engine = this.container.get(_aureliaTemplating.TemplatingEngine); instruction.viewModel = root; instruction.container = instruction.childContainer = this.container; instruction.viewSlot = this.hostSlot; instruction.host = this.host; return engine.compose(instruction).then(function (r) { _this7.root = r; instruction.viewSlot.attached(); _this7._onAureliaComposed(); return _this7; }); }; Aurelia.prototype._configureHost = function _configureHost(applicationHost) { if (this.hostConfigured) { return; } applicationHost = applicationHost || this.host; if (!applicationHost || typeof applicationHost === 'string') { this.host = _aureliaPal.DOM.getElementById(applicationHost || 'applicationHost'); } else { this.host = applicationHost; } if (!this.host) { throw new Error('No applicationHost was specified.'); } this.hostConfigured = true; this.host.aurelia = this; this.hostSlot = new _aureliaTemplating.ViewSlot(this.host, true); this.hostSlot.transformChildNodesIntoView(); this.container.registerInstance(_aureliaPal.DOM.boundary, this.host); }; Aurelia.prototype._onAureliaComposed = function _onAureliaComposed() { var evt = _aureliaPal.DOM.createCustomEvent('aurelia-composed', { bubbles: true, cancelable: true }); setTimeout(function () { return _aureliaPal.DOM.dispatchEvent(evt); }, 1); }; return Aurelia; })(); exports.Aurelia = Aurelia; _defaults(exports, _interopExportWildcard(_aureliaDependencyInjection, _defaults)); _defaults(exports, _interopExportWildcard(_aureliaBinding, _defaults)); _defaults(exports, _interopExportWildcard(_aureliaMetadata, _defaults)); _defaults(exports, _interopExportWildcard(_aureliaTemplating, _defaults)); _defaults(exports, _interopExportWildcard(_aureliaLoader, _defaults)); _defaults(exports, _interopExportWildcard(_aureliaTaskQueue, _defaults)); _defaults(exports, _interopExportWildcard(_aureliaPath, _defaults)); _defaults(exports, _interopExportWildcard(_aureliaPal, _defaults)); var LogManager = _aureliaLogging; exports.LogManager = LogManager; }); define('aurelia-route-recognizer',['exports', 'core-js', 'aurelia-path'], function (exports, _coreJs, _aureliaPath) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var State = (function () { function State(charSpec) { _classCallCheck(this, State); this.charSpec = charSpec; this.nextStates = []; } State.prototype.get = function get(charSpec) { for (var _iterator = this.nextStates, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var child = _ref; var isEqual = child.charSpec.validChars === charSpec.validChars && child.charSpec.invalidChars === charSpec.invalidChars; if (isEqual) { return child; } } }; State.prototype.put = function put(charSpec) { var state = this.get(charSpec); if (state) { return state; } state = new State(charSpec); this.nextStates.push(state); if (charSpec.repeat) { state.nextStates.push(state); } return state; }; State.prototype.match = function match(ch) { var nextStates = this.nextStates; var results = []; for (var i = 0, l = nextStates.length; i < l; i++) { var child = nextStates[i]; var charSpec = child.charSpec; if (charSpec.validChars !== undefined) { if (charSpec.validChars.indexOf(ch) !== -1) { results.push(child); } } else if (charSpec.invalidChars !== undefined) { if (charSpec.invalidChars.indexOf(ch) === -1) { results.push(child); } } } return results; }; return State; })(); exports.State = State; var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\']; var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); var StaticSegment = (function () { function StaticSegment(string) { _classCallCheck(this, StaticSegment); this.string = string; } StaticSegment.prototype.eachChar = function eachChar(callback) { for (var _iterator2 = this.string, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var ch = _ref2; callback({ validChars: ch }); } }; StaticSegment.prototype.regex = function regex() { return this.string.replace(escapeRegex, '\\$1'); }; StaticSegment.prototype.generate = function generate() { return this.string; }; return StaticSegment; })(); exports.StaticSegment = StaticSegment; var DynamicSegment = (function () { function DynamicSegment(name) { _classCallCheck(this, DynamicSegment); this.name = name; } DynamicSegment.prototype.eachChar = function eachChar(callback) { callback({ invalidChars: '/', repeat: true }); }; DynamicSegment.prototype.regex = function regex() { return '([^/]+)'; }; DynamicSegment.prototype.generate = function generate(params, consumed) { consumed[this.name] = true; return params[this.name]; }; return DynamicSegment; })(); exports.DynamicSegment = DynamicSegment; var StarSegment = (function () { function StarSegment(name) { _classCallCheck(this, StarSegment); this.name = name; } StarSegment.prototype.eachChar = function eachChar(callback) { callback({ invalidChars: '', repeat: true }); }; StarSegment.prototype.regex = function regex() { return '(.+)'; }; StarSegment.prototype.generate = function generate(params, consumed) { consumed[this.name] = true; return params[this.name]; }; return StarSegment; })(); exports.StarSegment = StarSegment; var EpsilonSegment = (function () { function EpsilonSegment() { _classCallCheck(this, EpsilonSegment); } EpsilonSegment.prototype.eachChar = function eachChar() {}; EpsilonSegment.prototype.regex = function regex() { return ''; }; EpsilonSegment.prototype.generate = function generate() { return ''; }; return EpsilonSegment; })(); exports.EpsilonSegment = EpsilonSegment; var RouteRecognizer = (function () { function RouteRecognizer() { _classCallCheck(this, RouteRecognizer); this.rootState = new State(); this.names = {}; } RouteRecognizer.prototype.add = function add(route) { var _this = this; if (Array.isArray(route)) { route.forEach(function (r) { return _this.add(r); }); return undefined; } var currentState = this.rootState; var regex = '^'; var types = { statics: 0, dynamics: 0, stars: 0 }; var names = []; var routeName = route.handler.name; var isEmpty = true; var segments = parse(route.path, names, types); for (var i = 0, ii = segments.length; i < ii; i++) { var segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } isEmpty = false; currentState = currentState.put({ validChars: '/' }); regex += '/'; currentState = addSegment(currentState, segment); regex += segment.regex(); } if (isEmpty) { currentState = currentState.put({ validChars: '/' }); regex += '/'; } var handlers = [{ handler: route.handler, names: names }]; if (routeName) { this.names[routeName] = { segments: segments, handlers: handlers }; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + '$'); currentState.types = types; return currentState; }; RouteRecognizer.prototype.handlersFor = function handlersFor(name) { var route = this.names[name]; if (!route) { throw new Error('There is no route named ' + name); } return [].concat(route.handlers); }; RouteRecognizer.prototype.hasRoute = function hasRoute(name) { return !!this.names[name]; }; RouteRecognizer.prototype.generate = function generate(name, params) { var routeParams = Object.assign({}, params); var route = this.names[name]; if (!route) { throw new Error('There is no route named ' + name); } var segments = route.segments; var consumed = {}; var output = ''; for (var i = 0, l = segments.length; i < l; i++) { var segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } output += '/'; var segmentValue = segment.generate(routeParams, consumed); if (segmentValue === null || segmentValue === undefined) { throw new Error('A value is required for route parameter \'' + segment.name + '\' in route \'' + name + '\'.'); } output += segmentValue; } if (output.charAt(0) !== '/') { output = '/' + output; } for (var param in consumed) { delete routeParams[param]; } var queryString = _aureliaPath.buildQueryString(routeParams); output += queryString ? '?' + queryString : ''; return output; }; RouteRecognizer.prototype.recognize = function recognize(path) { var states = [this.rootState]; var queryParams = {}; var isSlashDropped = false; var normalizedPath = path; var queryStart = normalizedPath.indexOf('?'); if (queryStart !== -1) { var queryString = normalizedPath.substr(queryStart + 1, normalizedPath.length); normalizedPath = normalizedPath.substr(0, queryStart); queryParams = _aureliaPath.parseQueryString(queryString); } normalizedPath = decodeURI(normalizedPath); if (normalizedPath.charAt(0) !== '/') { normalizedPath = '/' + normalizedPath; } var pathLen = normalizedPath.length; if (pathLen > 1 && normalizedPath.charAt(pathLen - 1) === '/') { normalizedPath = normalizedPath.substr(0, pathLen - 1); isSlashDropped = true; } for (var i = 0, l = normalizedPath.length; i < l; i++) { states = recognizeChar(states, normalizedPath.charAt(i)); if (!states.length) { break; } } var solutions = []; for (var i = 0, l = states.length; i < l; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); var state = solutions[0]; if (state && state.handlers) { if (isSlashDropped && state.regex.source.slice(-5) === '(.+)$') { normalizedPath = normalizedPath + '/'; } return findHandler(state, normalizedPath, queryParams); } }; return RouteRecognizer; })(); exports.RouteRecognizer = RouteRecognizer; var RecognizeResults = function RecognizeResults(queryParams) { _classCallCheck(this, RecognizeResults); this.splice = Array.prototype.splice; this.slice = Array.prototype.slice; this.push = Array.prototype.push; this.length = 0; this.queryParams = queryParams || {}; }; function parse(route, names, types) { var normalizedRoute = route; if (route.charAt(0) === '/') { normalizedRoute = route.substr(1); } var results = []; for (var _iterator3 = normalizedRoute.split('/'), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { var _ref3; if (_isArray3) { if (_i3 >= _iterator3.length) break; _ref3 = _iterator3[_i3++]; } else { _i3 = _iterator3.next(); if (_i3.done) break; _ref3 = _i3.value; } var segment = _ref3; var match = segment.match(/^:([^\/]+)$/); if (match) { results.push(new DynamicSegment(match[1])); names.push(match[1]); types.dynamics++; continue; } match = segment.match(/^\*([^\/]+)$/); if (match) { results.push(new StarSegment(match[1])); names.push(match[1]); types.stars++; } else if (segment === '') { results.push(new EpsilonSegment()); } else { results.push(new StaticSegment(segment)); types.statics++; } } return results; } function sortSolutions(states) { return states.sort(function (a, b) { if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } if (a.types.stars) { if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } if (a.types.dynamics !== b.types.dynamics) { return b.types.dynamics - a.types.dynamics; } } if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } return 0; }); } function recognizeChar(states, ch) { var nextStates = []; for (var i = 0, l = states.length; i < l; i++) { var state = states[i]; nextStates.push.apply(nextStates, state.match(ch)); } return nextStates; } function findHandler(state, path, queryParams) { var handlers = state.handlers; var regex = state.regex; var captures = path.match(regex); var currentCapture = 1; var result = new RecognizeResults(queryParams); for (var i = 0, l = handlers.length; i < l; i++) { var _handler = handlers[i]; var _names = _handler.names; var _params = {}; for (var j = 0, m = _names.length; j < m; j++) { _params[_names[j]] = captures[currentCapture++]; } result.push({ handler: _handler.handler, params: _params, isDynamic: !!_names.length }); } return result; } function addSegment(currentState, segment) { var state = currentState; segment.eachChar(function (ch) { state = state.put(ch); }); return state; } }); define('aurelia-router',['exports', 'core-js', 'aurelia-logging', 'aurelia-dependency-injection', 'aurelia-route-recognizer', 'aurelia-history', 'aurelia-event-aggregator'], function (exports, _coreJs, _aureliaLogging, _aureliaDependencyInjection, _aureliaRouteRecognizer, _aureliaHistory, _aureliaEventAggregator) { exports.__esModule = true; 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; }; })(); exports._normalizeAbsolutePath = _normalizeAbsolutePath; exports._createRootedPath = _createRootedPath; exports._resolveUrl = _resolveUrl; exports.createRouteFilterStep = createRouteFilterStep; exports.isNavigationCommand = isNavigationCommand; exports._buildNavigationPlan = _buildNavigationPlan; 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _normalizeAbsolutePath(path, hasPushState) { if (!hasPushState && path[0] !== '#') { path = '#' + path; } return path; } function _createRootedPath(fragment, baseUrl, hasPushState) { if (isAbsoluteUrl.test(fragment)) { return fragment; } var path = ''; if (baseUrl.length && baseUrl[0] !== '/') { path += '/'; } path += baseUrl; if ((!path.length || path[path.length - 1] !== '/') && fragment[0] !== '/') { path += '/'; } if (path.length && path[path.length - 1] === '/' && fragment[0] === '/') { path = path.substring(0, path.length - 1); } return _normalizeAbsolutePath(path + fragment, hasPushState); } function _resolveUrl(fragment, baseUrl, hasPushState) { if (isRootedPath.test(fragment)) { return _normalizeAbsolutePath(fragment, hasPushState); } return _createRootedPath(fragment, baseUrl, hasPushState); } var isRootedPath = /^#?\//; var isAbsoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; var RouteFilterContainer = (function () { RouteFilterContainer.inject = function inject() { return [_aureliaDependencyInjection.Container]; }; function RouteFilterContainer(container) { _classCallCheck(this, RouteFilterContainer); this.container = container; this.filters = {}; this.filterCache = {}; } RouteFilterContainer.prototype.addStep = function addStep(name, step) { var index = arguments.length <= 2 || arguments[2] === undefined ? -1 : arguments[2]; var filter = this.filters[name]; if (!filter) { filter = this.filters[name] = []; } if (index === -1) { index = filter.length; } filter.splice(index, 0, step); this.filterCache = {}; }; RouteFilterContainer.prototype.getFilterSteps = function getFilterSteps(name) { if (this.filterCache[name]) { return this.filterCache[name]; } var steps = []; var filter = this.filters[name]; if (!filter) { return steps; } for (var i = 0, l = filter.length; i < l; i++) { if (typeof filter[i] === 'string') { steps.push.apply(steps, this.getFilterSteps(filter[i])); } else { steps.push(this.container.get(filter[i])); } } this.filterCache[name] = steps; return steps; }; return RouteFilterContainer; })(); exports.RouteFilterContainer = RouteFilterContainer; function createRouteFilterStep(name) { function create(routeFilterContainer) { return new RouteFilterStep(name, routeFilterContainer); } create.inject = function () { return [RouteFilterContainer]; }; return create; } var RouteFilterStep = (function () { function RouteFilterStep(name, routeFilterContainer) { _classCallCheck(this, RouteFilterStep); this.isMultiStep = true; this.name = name; this.routeFilterContainer = routeFilterContainer; } RouteFilterStep.prototype.getSteps = function getSteps() { return this.routeFilterContainer.getFilterSteps(this.name); }; return RouteFilterStep; })(); var pipelineStatus = { completed: 'completed', canceled: 'canceled', rejected: 'rejected', running: 'running' }; exports.pipelineStatus = pipelineStatus; var Pipeline = (function () { function Pipeline() { _classCallCheck(this, Pipeline); this.steps = []; } Pipeline.prototype.addStep = function addStep(step) { var run = undefined; if (typeof step === 'function') { run = step; } else if (step.isMultiStep) { var steps = step.getSteps(); for (var i = 0, l = steps.length; i < l; i++) { this.addStep(steps[i]); } return this; } else { run = step.run.bind(step); } this.steps.push(run); return this; }; Pipeline.prototype.run = function run(instruction) { var index = -1; var steps = this.steps; function next() { index++; if (index < steps.length) { var currentStep = steps[index]; try { return currentStep(instruction, next); } catch (e) { return next.reject(e); } } else { return next.complete(); } } next.complete = createCompletionHandler(next, pipelineStatus.completed); next.cancel = createCompletionHandler(next, pipelineStatus.canceled); next.reject = createCompletionHandler(next, pipelineStatus.rejected); return next(); }; return Pipeline; })(); exports.Pipeline = Pipeline; function createCompletionHandler(next, status) { return function (output) { return Promise.resolve({ status: status, output: output, completed: status === pipelineStatus.completed }); }; } var CommitChangesStep = (function () { function CommitChangesStep() { _classCallCheck(this, CommitChangesStep); } CommitChangesStep.prototype.run = function run(navigationInstruction, next) { return navigationInstruction._commitChanges(true).then(function () { navigationInstruction._updateTitle(); return next(); }); }; return CommitChangesStep; })(); exports.CommitChangesStep = CommitChangesStep; var NavigationInstruction = (function () { function NavigationInstruction(init) { _classCallCheck(this, NavigationInstruction); this.plan = null; Object.assign(this, init); this.params = this.params || {}; this.viewPortInstructions = {}; var ancestorParams = []; var current = this; do { var currentParams = Object.assign({}, current.params); if (current.config && current.config.hasChildRouter) { delete currentParams[current.getWildCardName()]; } ancestorParams.unshift(currentParams); current = current.parentInstruction; } while (current); var allParams = Object.assign.apply(Object, [{}, this.queryParams].concat(ancestorParams)); this.lifecycleArgs = [allParams, this.config, this]; } NavigationInstruction.prototype.getAllInstructions = function getAllInstructions() { var instructions = [this]; for (var key in this.viewPortInstructions) { var childInstruction = this.viewPortInstructions[key].childNavigationInstruction; if (childInstruction) { instructions.push.apply(instructions, childInstruction.getAllInstructions()); } } return instructions; }; NavigationInstruction.prototype.getAllPreviousInstructions = function getAllPreviousInstructions() { return this.getAllInstructions().map(function (c) { return c.previousInstruction; }).filter(function (c) { return c; }); }; NavigationInstruction.prototype.addViewPortInstruction = function addViewPortInstruction(viewPortName, strategy, moduleId, component) { var viewportInstruction = this.viewPortInstructions[viewPortName] = { name: viewPortName, strategy: strategy, moduleId: moduleId, component: component, childRouter: component.childRouter, lifecycleArgs: this.lifecycleArgs.slice() }; return viewportInstruction; }; NavigationInstruction.prototype.getWildCardName = function getWildCardName() { var wildcardIndex = this.config.route.lastIndexOf('*'); return this.config.route.substr(wildcardIndex + 1); }; NavigationInstruction.prototype.getWildcardPath = function getWildcardPath() { var wildcardName = this.getWildCardName(); var path = this.params[wildcardName] || ''; if (this.queryString) { path += '?' + this.queryString; } return path; }; NavigationInstruction.prototype.getBaseUrl = function getBaseUrl() { if (!this.params) { return this.fragment; } var wildcardName = this.getWildCardName(); var path = this.params[wildcardName] || ''; if (!path) { return this.fragment; } return this.fragment.substr(0, this.fragment.lastIndexOf(path)); }; NavigationInstruction.prototype._commitChanges = function _commitChanges(waitToSwap) { var _this = this; var router = this.router; router.currentInstruction = this; if (this.previousInstruction) { this.previousInstruction.config.navModel.isActive = false; } this.config.navModel.isActive = true; router._refreshBaseUrl(); router.refreshNavigation(); var loads = []; var delaySwaps = []; var _loop = function (viewPortName) { var viewPortInstruction = _this.viewPortInstructions[viewPortName]; var viewPort = router.viewPorts[viewPortName]; if (!viewPort) { throw new Error('There was no router-view found in the view for ' + viewPortInstruction.moduleId + '.'); } if (viewPortInstruction.strategy === activationStrategy.replace) { if (waitToSwap) { delaySwaps.push({ viewPort: viewPort, viewPortInstruction: viewPortInstruction }); } loads.push(viewPort.process(viewPortInstruction, waitToSwap).then(function (x) { if (viewPortInstruction.childNavigationInstruction) { return viewPortInstruction.childNavigationInstruction._commitChanges(); } })); } else { if (viewPortInstruction.childNavigationInstruction) { loads.push(viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap)); } } }; for (var viewPortName in this.viewPortInstructions) { _loop(viewPortName); } return Promise.all(loads).then(function () { delaySwaps.forEach(function (x) { return x.viewPort.swap(x.viewPortInstruction); }); }).then(function () { return prune(_this); }); }; NavigationInstruction.prototype._updateTitle = function _updateTitle() { var title = this._buildTitle(); if (title) { this.router.history.setTitle(title); } }; NavigationInstruction.prototype._buildTitle = function _buildTitle() { var separator = arguments.length <= 0 || arguments[0] === undefined ? ' | ' : arguments[0]; var title = this.config.navModel.title || ''; var childTitles = []; for (var viewPortName in this.viewPortInstructions) { var viewPortInstruction = this.viewPortInstructions[viewPortName]; if (viewPortInstruction.childNavigationInstruction) { var childTitle = viewPortInstruction.childNavigationInstruction._buildTitle(separator); if (childTitle) { childTitles.push(childTitle); } } } if (childTitles.length) { title = childTitles.join(separator) + (title ? separator : '') + title; } if (this.router.title) { title += (title ? separator : '') + this.router.title; } return title; }; return NavigationInstruction; })(); exports.NavigationInstruction = NavigationInstruction; function prune(instruction) { instruction.previousInstruction = null; instruction.plan = null; } var NavModel = (function () { function NavModel(router, relativeHref) { _classCallCheck(this, NavModel); this.isActive = false; this.title = null; this.href = null; this.relativeHref = null; this.settings = {}; this.config = null; this.router = router; this.relativeHref = relativeHref; } NavModel.prototype.setTitle = function setTitle(title) { this.title = title; if (this.isActive) { this.router.updateTitle(); } }; return NavModel; })(); exports.NavModel = NavModel; function isNavigationCommand(obj) { return obj && typeof obj.navigate === 'function'; } var Redirect = (function () { function Redirect(url) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, Redirect); this.url = url; this.options = Object.assign({ trigger: true, replace: true }, options); this.shouldContinueProcessing = false; } Redirect.prototype.setRouter = function setRouter(router) { this.router = router; }; Redirect.prototype.navigate = function navigate(appRouter) { var navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter; navigatingRouter.navigate(this.url, this.options); }; return Redirect; })(); exports.Redirect = Redirect; var RouterConfiguration = (function () { function RouterConfiguration() { _classCallCheck(this, RouterConfiguration); this.instructions = []; this.options = {}; this.pipelineSteps = []; } RouterConfiguration.prototype.addPipelineStep = function addPipelineStep(name, step) { this.pipelineSteps.push({ name: name, step: step }); return this; }; RouterConfiguration.prototype.map = function map(route) { if (Array.isArray(route)) { route.forEach(this.map.bind(this)); return this; } return this.mapRoute(route); }; RouterConfiguration.prototype.mapRoute = function mapRoute(config) { this.instructions.push(function (router) { var routeConfigs = []; if (Array.isArray(config.route)) { for (var i = 0, ii = config.route.length; i < ii; ++i) { var current = Object.assign({}, config); current.route = config.route[i]; routeConfigs.push(current); } } else { routeConfigs.push(Object.assign({}, config)); } var navModel = undefined; for (var i = 0, ii = routeConfigs.length; i < ii; ++i) { var routeConfig = routeConfigs[i]; routeConfig.settings = routeConfig.settings || {}; if (!navModel) { navModel = router.createNavModel(routeConfig); } router.addRoute(routeConfig, navModel); } }); return this; }; RouterConfiguration.prototype.mapUnknownRoutes = function mapUnknownRoutes(config) { this.unknownRouteConfig = config; return this; }; RouterConfiguration.prototype.exportToRouter = function exportToRouter(router) { var instructions = this.instructions; for (var i = 0, ii = instructions.length; i < ii; ++i) { instructions[i](router); } if (this.title) { router.title = this.title; } if (this.unknownRouteConfig) { router.handleUnknownRoutes(this.unknownRouteConfig); } router.options = this.options; var pipelineSteps = this.pipelineSteps; if (pipelineSteps.length) { if (!router.isRoot) { throw new Error('Pipeline steps can only be added to the root router'); } var filterContainer = router.container.get(RouteFilterContainer); for (var i = 0, ii = pipelineSteps.length; i < ii; ++i) { var _pipelineSteps$i = pipelineSteps[i]; var _name = _pipelineSteps$i.name; var step = _pipelineSteps$i.step; filterContainer.addStep(_name, step); } } }; return RouterConfiguration; })(); exports.RouterConfiguration = RouterConfiguration; var activationStrategy = { noChange: 'no-change', invokeLifecycle: 'invoke-lifecycle', replace: 'replace' }; exports.activationStrategy = activationStrategy; var BuildNavigationPlanStep = (function () { function BuildNavigationPlanStep() { _classCallCheck(this, BuildNavigationPlanStep); } BuildNavigationPlanStep.prototype.run = function run(navigationInstruction, next) { return _buildNavigationPlan(navigationInstruction).then(function (plan) { navigationInstruction.plan = plan; return next(); })['catch'](next.cancel); }; return BuildNavigationPlanStep; })(); exports.BuildNavigationPlanStep = BuildNavigationPlanStep; function _buildNavigationPlan(instruction, forceLifecycleMinimum) { var prev = instruction.previousInstruction; var config = instruction.config; var plan = {}; if ('redirect' in config) { var redirectLocation = _resolveUrl(config.redirect, getInstructionBaseUrl(instruction)); if (instruction.queryString) { redirectLocation += '?' + instruction.queryString; } return Promise.reject(new Redirect(redirectLocation)); } if (prev) { var newParams = hasDifferentParameterValues(prev, instruction); var pending = []; var _loop2 = function (viewPortName) { var prevViewPortInstruction = prev.viewPortInstructions[viewPortName]; var nextViewPortConfig = config.viewPorts[viewPortName]; var viewPortPlan = plan[viewPortName] = { name: viewPortName, config: nextViewPortConfig, prevComponent: prevViewPortInstruction.component, prevModuleId: prevViewPortInstruction.moduleId }; if (prevViewPortInstruction.moduleId !== nextViewPortConfig.moduleId) { viewPortPlan.strategy = activationStrategy.replace; } else if ('determineActivationStrategy' in prevViewPortInstruction.component.viewModel) { var _prevViewPortInstruction$component$viewModel; viewPortPlan.strategy = (_prevViewPortInstruction$component$viewModel = prevViewPortInstruction.component.viewModel).determineActivationStrategy.apply(_prevViewPortInstruction$component$viewModel, instruction.lifecycleArgs); } else if (config.activationStrategy) { viewPortPlan.strategy = config.activationStrategy; } else if (newParams || forceLifecycleMinimum) { viewPortPlan.strategy = activationStrategy.invokeLifecycle; } else { viewPortPlan.strategy = activationStrategy.noChange; } if (viewPortPlan.strategy !== activationStrategy.replace && prevViewPortInstruction.childRouter) { var path = instruction.getWildcardPath(); var task = prevViewPortInstruction.childRouter._createNavigationInstruction(path, instruction).then(function (childInstruction) { viewPortPlan.childNavigationInstruction = childInstruction; return _buildNavigationPlan(childInstruction, viewPortPlan.strategy === activationStrategy.invokeLifecycle).then(function (childPlan) { childInstruction.plan = childPlan; }); }); pending.push(task); } }; for (var viewPortName in prev.viewPortInstructions) { _loop2(viewPortName); } return Promise.all(pending).then(function () { return plan; }); } for (var viewPortName in config.viewPorts) { plan[viewPortName] = { name: viewPortName, strategy: activationStrategy.replace, config: instruction.config.viewPorts[viewPortName] }; } return Promise.resolve(plan); } function hasDifferentParameterValues(prev, next) { var prevParams = prev.params; var nextParams = next.params; var nextWildCardName = next.config.hasChildRouter ? next.getWildCardName() : null; for (var key in nextParams) { if (key === nextWildCardName) { continue; } if (prevParams[key] !== nextParams[key]) { return true; } } for (var key in prevParams) { if (key === nextWildCardName) { continue; } if (prevParams[key] !== nextParams[key]) { return true; } } return false; } function getInstructionBaseUrl(instruction) { var instructionBaseUrlParts = []; instruction = instruction.parentInstruction; while (instruction) { instructionBaseUrlParts.unshift(instruction.getBaseUrl()); instruction = instruction.parentInstruction; } instructionBaseUrlParts.unshift('/'); return instructionBaseUrlParts.join(''); } var Router = (function () { function Router(container, history) { var _this2 = this; _classCallCheck(this, Router); this.viewPorts = {}; this.routes = []; this.baseUrl = ''; this.isConfigured = false; this.isNavigating = false; this.navigation = []; this._fallbackOrder = 100; this._recognizer = new _aureliaRouteRecognizer.RouteRecognizer(); this._childRecognizer = new _aureliaRouteRecognizer.RouteRecognizer(); this.container = container; this.history = history; this._configuredPromise = new Promise(function (resolve) { _this2._resolveConfiguredPromise = resolve; }); } Router.prototype.registerViewPort = function registerViewPort(viewPort, name) { name = name || 'default'; this.viewPorts[name] = viewPort; }; Router.prototype.ensureConfigured = function ensureConfigured() { return this._configuredPromise; }; Router.prototype.configure = function configure(callbackOrConfig) { var _this3 = this; this.isConfigured = true; var result = callbackOrConfig; var config = undefined; if (typeof callbackOrConfig === 'function') { config = new RouterConfiguration(); result = callbackOrConfig(config); } return Promise.resolve(result).then(function (c) { if (c && c.exportToRouter) { config = c; } config.exportToRouter(_this3); _this3.isConfigured = true; _this3._resolveConfiguredPromise(); }); }; Router.prototype.navigate = function navigate(fragment, options) { if (!this.isConfigured && this.parent) { return this.parent.navigate(fragment, options); } return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options); }; Router.prototype.navigateToRoute = function navigateToRoute(route, params, options) { var path = this.generate(route, params); return this.navigate(path, options); }; Router.prototype.navigateBack = function navigateBack() { this.history.navigateBack(); }; Router.prototype.createChild = function createChild(container) { var childRouter = new Router(container || this.container.createChild(), this.history); childRouter.parent = this; return childRouter; }; Router.prototype.generate = function generate(name, params) { var hasRoute = this._recognizer.hasRoute(name); if ((!this.isConfigured || !hasRoute) && this.parent) { return this.parent.generate(name, params); } if (!hasRoute) { throw new Error('A route with name \'' + name + '\' could not be found. Check that `name: \'' + name + '\'` was specified in the route\'s config.'); } var path = this._recognizer.generate(name, params); return _createRootedPath(path, this.baseUrl, this.history._hasPushState); }; Router.prototype.createNavModel = function createNavModel(config) { var navModel = new NavModel(this, 'href' in config ? config.href : config.route); navModel.title = config.title; navModel.order = config.nav; navModel.href = config.href; navModel.settings = config.settings; navModel.config = config; return navModel; }; Router.prototype.addRoute = function addRoute(config, navModel) { validateRouteConfig(config); if (!('viewPorts' in config) && !config.navigationStrategy) { config.viewPorts = { 'default': { moduleId: config.moduleId, view: config.view } }; } if (!navModel) { navModel = this.createNavModel(config); } this.routes.push(config); var path = config.route; if (path.charAt(0) === '/') { path = path.substr(1); } var state = this._recognizer.add({ path: path, handler: config }); if (path) { var _settings = config.settings; delete config.settings; var withChild = JSON.parse(JSON.stringify(config)); config.settings = _settings; withChild.route = path + '/*childRoute'; withChild.hasChildRouter = true; this._childRecognizer.add({ path: withChild.route, handler: withChild }); withChild.navModel = navModel; withChild.settings = config.settings; } config.navModel = navModel; if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) { if (!navModel.href && navModel.href !== '' && (state.types.dynamics || state.types.stars)) { throw new Error('Invalid route config: dynamic routes must specify an href to be included in the navigation model.'); } if (typeof navModel.order !== 'number') { navModel.order = ++this._fallbackOrder; } this.navigation.push(navModel); this.navigation = this.navigation.sort(function (a, b) { return a.order - b.order; }); } }; Router.prototype.hasRoute = function hasRoute(name) { return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name)); }; Router.prototype.hasOwnRoute = function hasOwnRoute(name) { return this._recognizer.hasRoute(name); }; Router.prototype.handleUnknownRoutes = function handleUnknownRoutes(config) { var _this4 = this; if (!config) { throw new Error('Invalid unknown route handler'); } this.catchAllHandler = function (instruction) { return _this4._createRouteConfig(config, instruction).then(function (c) { instruction.config = c; return instruction; }); }; }; Router.prototype.updateTitle = function updateTitle() { if (this.parent) { return this.parent.updateTitle(); } this.currentInstruction._updateTitle(); }; Router.prototype.refreshNavigation = function refreshNavigation() { var nav = this.navigation; for (var i = 0, _length = nav.length; i < _length; i++) { var current = nav[i]; if (!current.href) { current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState); } } }; Router.prototype._refreshBaseUrl = function _refreshBaseUrl() { if (this.parent) { var baseUrl = this.parent.currentInstruction.getBaseUrl(); this.baseUrl = this.parent.baseUrl + baseUrl; } }; Router.prototype._createNavigationInstruction = function _createNavigationInstruction() { var url = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; var parentInstruction = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; var fragment = url; var queryString = ''; var queryIndex = url.indexOf('?'); if (queryIndex !== -1) { fragment = url.substr(0, queryIndex); queryString = url.substr(queryIndex + 1); } var results = this._recognizer.recognize(url); if (!results || !results.length) { results = this._childRecognizer.recognize(url); } var instructionInit = { fragment: fragment, queryString: queryString, config: null, parentInstruction: parentInstruction, previousInstruction: this.currentInstruction, router: this }; if (results && results.length) { var first = results[0]; var _instruction = new NavigationInstruction(Object.assign({}, instructionInit, { params: first.params, queryParams: first.queryParams || results.queryParams, config: first.config || first.handler })); if (typeof first.handler === 'function') { return evaluateNavigationStrategy(_instruction, first.handler, first); } else if (first.handler && 'navigationStrategy' in first.handler) { return evaluateNavigationStrategy(_instruction, first.handler.navigationStrategy, first.handler); } return Promise.resolve(_instruction); } else if (this.catchAllHandler) { var _instruction2 = new NavigationInstruction(Object.assign({}, instructionInit, { params: { path: fragment }, queryParams: results && results.queryParams, config: null })); return evaluateNavigationStrategy(_instruction2, this.catchAllHandler); } return Promise.reject(new Error('Route not found: ' + url)); }; Router.prototype._createRouteConfig = function _createRouteConfig(config, instruction) { var _this5 = this; return Promise.resolve(config).then(function (c) { if (typeof c === 'string') { return { moduleId: c }; } else if (typeof c === 'function') { return c(instruction); } return c; }).then(function (c) { return typeof c === 'string' ? { moduleId: c } : c; }).then(function (c) { c.route = instruction.params.path; validateRouteConfig(c); if (!c.navModel) { c.navModel = _this5.createNavModel(c); } return c; }); }; _createClass(Router, [{ key: 'isRoot', get: function get() { return !this.parent; } }]); return Router; })(); exports.Router = Router; function validateRouteConfig(config) { if (typeof config !== 'object') { throw new Error('Invalid Route Config'); } if (typeof config.route !== 'string') { throw new Error('Invalid Route Config: You must specify a route pattern.'); } if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) { throw new Error('Invalid Route Config: You must specify a moduleId, redirect, navigationStrategy, or viewPorts.'); } } function evaluateNavigationStrategy(instruction, evaluator, context) { return Promise.resolve(evaluator.call(context, instruction)).then(function () { if (!('viewPorts' in instruction.config)) { instruction.config.viewPorts = { 'default': { moduleId: instruction.config.moduleId } }; } return instruction; }); } var CanDeactivatePreviousStep = (function () { function CanDeactivatePreviousStep() { _classCallCheck(this, CanDeactivatePreviousStep); } CanDeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) { return processDeactivatable(navigationInstruction.plan, 'canDeactivate', next); }; return CanDeactivatePreviousStep; })(); exports.CanDeactivatePreviousStep = CanDeactivatePreviousStep; var CanActivateNextStep = (function () { function CanActivateNextStep() { _classCallCheck(this, CanActivateNextStep); } CanActivateNextStep.prototype.run = function run(navigationInstruction, next) { return processActivatable(navigationInstruction, 'canActivate', next); }; return CanActivateNextStep; })(); exports.CanActivateNextStep = CanActivateNextStep; var DeactivatePreviousStep = (function () { function DeactivatePreviousStep() { _classCallCheck(this, DeactivatePreviousStep); } DeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) { return processDeactivatable(navigationInstruction.plan, 'deactivate', next, true); }; return DeactivatePreviousStep; })(); exports.DeactivatePreviousStep = DeactivatePreviousStep; var ActivateNextStep = (function () { function ActivateNextStep() { _classCallCheck(this, ActivateNextStep); } ActivateNextStep.prototype.run = function run(navigationInstruction, next) { return processActivatable(navigationInstruction, 'activate', next, true); }; return ActivateNextStep; })(); exports.ActivateNextStep = ActivateNextStep; function processDeactivatable(plan, callbackName, next, ignoreResult) { var infos = findDeactivatable(plan, callbackName); var i = infos.length; function inspect(val) { if (ignoreResult || shouldContinue(val)) { return iterate(); } return next.cancel(val); } function iterate() { if (i--) { try { var viewModel = infos[i]; var result = viewModel[callbackName](); return processPotential(result, inspect, next.cancel); } catch (error) { return next.cancel(error); } } return next(); } return iterate(); } function findDeactivatable(plan, callbackName) { var list = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; for (var viewPortName in plan) { var viewPortPlan = plan[viewPortName]; var prevComponent = viewPortPlan.prevComponent; if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && prevComponent) { var viewModel = prevComponent.viewModel; if (callbackName in viewModel) { list.push(viewModel); } } if (viewPortPlan.childNavigationInstruction) { findDeactivatable(viewPortPlan.childNavigationInstruction.plan, callbackName, list); } else if (prevComponent) { addPreviousDeactivatable(prevComponent, callbackName, list); } } return list; } function addPreviousDeactivatable(component, callbackName, list) { var childRouter = component.childRouter; if (childRouter && childRouter.currentInstruction) { var viewPortInstructions = childRouter.currentInstruction.viewPortInstructions; for (var viewPortName in viewPortInstructions) { var viewPortInstruction = viewPortInstructions[viewPortName]; var prevComponent = viewPortInstruction.component; var prevViewModel = prevComponent.viewModel; if (callbackName in prevViewModel) { list.push(prevViewModel); } addPreviousDeactivatable(prevComponent, callbackName, list); } } } function processActivatable(navigationInstruction, callbackName, next, ignoreResult) { var infos = findActivatable(navigationInstruction, callbackName); var length = infos.length; var i = -1; function inspect(val, router) { if (ignoreResult || shouldContinue(val, router)) { return iterate(); } return next.cancel(val); } function iterate() { i++; if (i < length) { try { var _ret3 = (function () { var _current$viewModel; var current = infos[i]; var result = (_current$viewModel = current.viewModel)[callbackName].apply(_current$viewModel, current.lifecycleArgs); return { v: processPotential(result, function (val) { return inspect(val, current.router); }, next.cancel) }; })(); if (typeof _ret3 === 'object') return _ret3.v; } catch (error) { return next.cancel(error); } } return next(); } return iterate(); } function findActivatable(navigationInstruction, callbackName, list, router) { if (list === undefined) list = []; var plan = navigationInstruction.plan; Object.keys(plan).filter(function (viewPortName) { var viewPortPlan = plan[viewPortName]; var viewPortInstruction = navigationInstruction.viewPortInstructions[viewPortName]; var viewModel = viewPortInstruction.component.viewModel; if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && callbackName in viewModel) { list.push({ viewModel: viewModel, lifecycleArgs: viewPortInstruction.lifecycleArgs, router: router }); } if (viewPortPlan.childNavigationInstruction) { findActivatable(viewPortPlan.childNavigationInstruction, callbackName, list, viewPortInstruction.component.childRouter || router); } }); return list; } function shouldContinue(output, router) { if (output instanceof Error) { return false; } if (isNavigationCommand(output)) { if (typeof output.setRouter === 'function') { output.setRouter(router); } return !!output.shouldContinueProcessing; } if (output === undefined) { return true; } return output; } function processPotential(obj, resolve, reject) { if (obj && typeof obj.then === 'function') { return Promise.resolve(obj).then(resolve)['catch'](reject); } try { return resolve(obj); } catch (error) { return reject(error); } } var RouteLoader = (function () { function RouteLoader() { _classCallCheck(this, RouteLoader); } RouteLoader.prototype.loadRoute = function loadRoute(router, config, navigationInstruction) { throw Error('Route loaders must implement "loadRoute(router, config, navigationInstruction)".'); }; return RouteLoader; })(); exports.RouteLoader = RouteLoader; var LoadRouteStep = (function () { LoadRouteStep.inject = function inject() { return [RouteLoader]; }; function LoadRouteStep(routeLoader) { _classCallCheck(this, LoadRouteStep); this.routeLoader = routeLoader; } LoadRouteStep.prototype.run = function run(navigationInstruction, next) { return loadNewRoute(this.routeLoader, navigationInstruction).then(next)['catch'](next.cancel); }; return LoadRouteStep; })(); exports.LoadRouteStep = LoadRouteStep; function loadNewRoute(routeLoader, navigationInstruction) { var toLoad = determineWhatToLoad(navigationInstruction); var loadPromises = toLoad.map(function (current) { return loadRoute(routeLoader, current.navigationInstruction, current.viewPortPlan); }); return Promise.all(loadPromises); } function determineWhatToLoad(navigationInstruction) { var toLoad = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var plan = navigationInstruction.plan; for (var viewPortName in plan) { var viewPortPlan = plan[viewPortName]; if (viewPortPlan.strategy === activationStrategy.replace) { toLoad.push({ viewPortPlan: viewPortPlan, navigationInstruction: navigationInstruction }); if (viewPortPlan.childNavigationInstruction) { determineWhatToLoad(viewPortPlan.childNavigationInstruction, toLoad); } } else { var viewPortInstruction = navigationInstruction.addViewPortInstruction(viewPortName, viewPortPlan.strategy, viewPortPlan.prevModuleId, viewPortPlan.prevComponent); if (viewPortPlan.childNavigationInstruction) { viewPortInstruction.childNavigationInstruction = viewPortPlan.childNavigationInstruction; determineWhatToLoad(viewPortPlan.childNavigationInstruction, toLoad); } } } return toLoad; } function loadRoute(routeLoader, navigationInstruction, viewPortPlan) { var moduleId = viewPortPlan.config.moduleId; return loadComponent(routeLoader, navigationInstruction, viewPortPlan.config).then(function (component) { var viewPortInstruction = navigationInstruction.addViewPortInstruction(viewPortPlan.name, viewPortPlan.strategy, moduleId, component); var childRouter = component.childRouter; if (childRouter) { var path = navigationInstruction.getWildcardPath(); return childRouter._createNavigationInstruction(path, navigationInstruction).then(function (childInstruction) { viewPortPlan.childNavigationInstruction = childInstruction; return _buildNavigationPlan(childInstruction).then(function (childPlan) { childInstruction.plan = childPlan; viewPortInstruction.childNavigationInstruction = childInstruction; return loadNewRoute(routeLoader, childInstruction); }); }); } }); } function loadComponent(routeLoader, navigationInstruction, config) { var router = navigationInstruction.router; var lifecycleArgs = navigationInstruction.lifecycleArgs; return routeLoader.loadRoute(router, config, navigationInstruction).then(function (component) { var viewModel = component.viewModel; var childContainer = component.childContainer; component.router = router; component.config = config; if ('configureRouter' in viewModel) { var _ret4 = (function () { var childRouter = childContainer.getChildRouter(); component.childRouter = childRouter; return { v: childRouter.configure(function (c) { return viewModel.configureRouter.apply(viewModel, [c, childRouter].concat(lifecycleArgs)); }).then(function () { return component; }) }; })(); if (typeof _ret4 === 'object') return _ret4.v; } return component; }); } var PipelineProvider = (function () { PipelineProvider.inject = function inject() { return [_aureliaDependencyInjection.Container]; }; function PipelineProvider(container) { _classCallCheck(this, PipelineProvider); this.container = container; this.steps = [BuildNavigationPlanStep, CanDeactivatePreviousStep, LoadRouteStep, createRouteFilterStep('authorize'), createRouteFilterStep('modelbind'), CanActivateNextStep, DeactivatePreviousStep, ActivateNextStep, createRouteFilterStep('precommit'), CommitChangesStep, createRouteFilterStep('postcomplete')]; } PipelineProvider.prototype.createPipeline = function createPipeline() { var _this6 = this; var pipeline = new Pipeline(); this.steps.forEach(function (step) { return pipeline.addStep(_this6.container.get(step)); }); return pipeline; }; return PipelineProvider; })(); exports.PipelineProvider = PipelineProvider; var logger = _aureliaLogging.getLogger('app-router'); var AppRouter = (function (_Router) { _inherits(AppRouter, _Router); AppRouter.inject = function inject() { return [_aureliaDependencyInjection.Container, _aureliaHistory.History, PipelineProvider, _aureliaEventAggregator.EventAggregator]; }; function AppRouter(container, history, pipelineProvider, events) { _classCallCheck(this, AppRouter); _Router.call(this, container, history); this._queue = []; this.pipelineProvider = pipelineProvider; this.events = events; this.maxInstructionCount = 10; } AppRouter.prototype.loadUrl = function loadUrl(url) { var _this7 = this; return this._createNavigationInstruction(url).then(function (instruction) { return _this7._queueInstruction(instruction); })['catch'](function (error) { logger.error(error); restorePreviousLocation(_this7); }); }; AppRouter.prototype.registerViewPort = function registerViewPort(viewPort, name) { var _this8 = this; _Router.prototype.registerViewPort.call(this, viewPort, name); if (!this.isActive) { var _ret5 = (function () { var viewModel = _this8._findViewModel(viewPort); if ('configureRouter' in viewModel) { if (!_this8.isConfigured) { var _ret6 = (function () { var resolveConfiguredPromise = _this8._resolveConfiguredPromise; _this8._resolveConfiguredPromise = function () {}; return { v: { v: _this8.configure(function (config) { return viewModel.configureRouter(config, _this8); }).then(function () { _this8.activate(); resolveConfiguredPromise(); }) } }; })(); if (typeof _ret6 === 'object') return _ret6.v; } } else { _this8.activate(); } })(); if (typeof _ret5 === 'object') return _ret5.v; } else { this._dequeueInstruction(); } return Promise.resolve(); }; AppRouter.prototype.activate = function activate(options) { if (this.isActive) { return; } this.isActive = true; this.options = Object.assign({ routeHandler: this.loadUrl.bind(this) }, this.options, options); this.history.activate(this.options); this._dequeueInstruction(); }; AppRouter.prototype.deactivate = function deactivate() { this.isActive = false; this.history.deactivate(); }; AppRouter.prototype._queueInstruction = function _queueInstruction(instruction) { var _this9 = this; return new Promise(function (resolve) { instruction.resolve = resolve; _this9._queue.unshift(instruction); _this9._dequeueInstruction(); }); }; AppRouter.prototype._dequeueInstruction = function _dequeueInstruction() { var _this10 = this; var instructionCount = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; return Promise.resolve().then(function () { if (_this10.isNavigating && !instructionCount) { return undefined; } var instruction = _this10._queue.shift(); _this10._queue = []; if (!instruction) { return undefined; } _this10.isNavigating = true; instruction.previousInstruction = _this10.currentInstruction; if (!instructionCount) { _this10.events.publish('router:navigation:processing', { instruction: instruction }); } else if (instructionCount === _this10.maxInstructionCount - 1) { logger.error(instructionCount + 1 + ' navigation instructions have been attempted without success. Restoring last known good location.'); restorePreviousLocation(_this10); return _this10._dequeueInstruction(instructionCount + 1); } else if (instructionCount > _this10.maxInstructionCount) { throw new Error('Maximum navigation attempts exceeded. Giving up.'); } var pipeline = _this10.pipelineProvider.createPipeline(); return pipeline.run(instruction).then(function (result) { return processResult(instruction, result, instructionCount, _this10); })['catch'](function (error) { return { output: error instanceof Error ? error : new Error(error) }; }).then(function (result) { return resolveInstruction(instruction, result, !!instructionCount, _this10); }); }); }; AppRouter.prototype._findViewModel = function _findViewModel(viewPort) { if (this.container.viewModel) { return this.container.viewModel; } if (viewPort.container) { var container = viewPort.container; while (container) { if (container.viewModel) { this.container.viewModel = container.viewModel; return container.viewModel; } container = container.parent; } } }; return AppRouter; })(Router); exports.AppRouter = AppRouter; function processResult(instruction, result, instructionCount, router) { if (!(result && 'completed' in result && 'output' in result)) { result = result || {}; result.output = new Error('Expected router pipeline to return a navigation result, but got [' + JSON.stringify(result) + '] instead.'); } var finalResult = null; if (isNavigationCommand(result.output)) { result.output.navigate(router); } else { finalResult = result; if (!result.completed) { if (result.output instanceof Error) { logger.error(result.output); } restorePreviousLocation(router); } } return router._dequeueInstruction(instructionCount + 1).then(function (innerResult) { return finalResult || innerResult || result; }); } function resolveInstruction(instruction, result, isInnerInstruction, router) { instruction.resolve(result); if (!isInnerInstruction) { router.isNavigating = false; var eventArgs = { instruction: instruction, result: result }; var eventName = undefined; if (result.output instanceof Error) { eventName = 'error'; } else if (!result.completed) { eventName = 'canceled'; } else { var _queryString = instruction.queryString ? '?' + instruction.queryString : ''; router.history.previousLocation = instruction.fragment + _queryString; eventName = 'success'; } router.events.publish('router:navigation:' + eventName, eventArgs); router.events.publish('router:navigation:complete', eventArgs); } return result; } function restorePreviousLocation(router) { var previousLocation = router.history.previousLocation; if (previousLocation) { router.navigate(router.history.previousLocation, { trigger: false, replace: true }); } else { logger.error('Router navigation failed, and no previous location could be restored.'); } } }); define('aurelia-templating-binding',['exports', 'aurelia-logging', 'aurelia-binding', 'aurelia-templating'], function (exports, _aureliaLogging, _aureliaBinding, _aureliaTemplating) { exports.__esModule = true; exports.configure = configure; 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var InterpolationBindingExpression = (function () { function InterpolationBindingExpression(observerLocator, targetProperty, parts, mode, lookupFunctions, attribute) { _classCallCheck(this, InterpolationBindingExpression); this.observerLocator = observerLocator; this.targetProperty = targetProperty; this.parts = parts; this.mode = mode; this.lookupFunctions = lookupFunctions; this.attribute = this.attrToRemove = attribute; this.discrete = false; } InterpolationBindingExpression.prototype.createBinding = function createBinding(target) { if (this.parts.length === 3) { return new ChildInterpolationBinding(target, this.observerLocator, this.parts[1], this.mode, this.lookupFunctions, this.targetProperty, this.parts[0], this.parts[2]); } return new InterpolationBinding(this.observerLocator, this.parts, target, this.targetProperty, this.mode, this.lookupFunctions); }; return InterpolationBindingExpression; })(); exports.InterpolationBindingExpression = InterpolationBindingExpression; function validateTarget(target, propertyName) { if (propertyName === 'style') { _aureliaLogging.getLogger('templating-binding').info('Internet Explorer does not support interpolation in "style" attributes. Use the style attribute\'s alias, "css" instead.'); } else if (target.parentElement && target.parentElement.nodeName === 'TEXTAREA' && propertyName === 'textContent') { throw new Error('Interpolation binding cannot be used in the content of a textarea element. Use <textarea value.bind="expression"></textarea> instead.'); } } var InterpolationBinding = (function () { function InterpolationBinding(observerLocator, parts, target, targetProperty, mode, lookupFunctions) { _classCallCheck(this, InterpolationBinding); validateTarget(target, targetProperty); this.observerLocator = observerLocator; this.parts = parts; this.targetProperty = observerLocator.getObserver(target, targetProperty); this.mode = mode; this.lookupFunctions = lookupFunctions; } InterpolationBinding.prototype.interpolate = function interpolate() { if (this.isBound) { var value = ''; var parts = this.parts; for (var i = 0, ii = parts.length; i < ii; i++) { value += i % 2 === 0 ? parts[i] : this['childBinding' + i].value; } this.targetProperty.setValue(value); } }; InterpolationBinding.prototype.bind = function bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.source = source; var parts = this.parts; for (var i = 1, ii = parts.length; i < ii; i += 2) { var binding = new ChildInterpolationBinding(this, this.observerLocator, parts[i], this.mode, this.lookupFunctions); binding.bind(source); this['childBinding' + i] = binding; } this.isBound = true; this.interpolate(); }; InterpolationBinding.prototype.unbind = function unbind() { if (!this.isBound) { return; } this.isBound = false; this.source = null; var parts = this.parts; for (var i = 1, ii = parts.length; i < ii; i += 2) { var _name = 'childBinding' + i; this[_name].unbind(); } }; return InterpolationBinding; })(); exports.InterpolationBinding = InterpolationBinding; var ChildInterpolationBinding = (function () { function ChildInterpolationBinding(target, observerLocator, sourceExpression, mode, lookupFunctions, targetProperty, left, right) { _classCallCheck(this, _ChildInterpolationBinding); if (target instanceof InterpolationBinding) { this.parent = target; } else { validateTarget(target, targetProperty); this.targetProperty = observerLocator.getObserver(target, targetProperty); } this.observerLocator = observerLocator; this.sourceExpression = sourceExpression; this.mode = mode; this.lookupFunctions = lookupFunctions; this.left = left; this.right = right; } ChildInterpolationBinding.prototype.updateTarget = function updateTarget(value) { value = value === null || value === undefined ? '' : value.toString(); if (value !== this.value) { this.value = value; if (this.parent) { this.parent.interpolate(); } else { this.targetProperty.setValue(this.left + value + this.right); } } }; ChildInterpolationBinding.prototype.call = function call() { if (!this.isBound) { return; } var value = this.sourceExpression.evaluate(this.source, this.lookupFunctions); this.updateTarget(value); if (this.mode !== _aureliaBinding.bindingMode.oneTime) { this._version++; this.sourceExpression.connect(this, this.source); if (value instanceof Array) { this.observeArray(value); } this.unobserve(false); } }; ChildInterpolationBinding.prototype.bind = function bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; var sourceExpression = this.sourceExpression; if (sourceExpression.bind) { sourceExpression.bind(this, source, this.lookupFunctions); } var value = sourceExpression.evaluate(source, this.lookupFunctions); this.updateTarget(value); if (this.mode === _aureliaBinding.bindingMode.oneWay) { sourceExpression.connect(this, source); if (value instanceof Array) { this.observeArray(value); } } }; ChildInterpolationBinding.prototype.unbind = function unbind() { if (!this.isBound) { return; } this.isBound = false; var sourceExpression = this.sourceExpression; if (sourceExpression.unbind) { sourceExpression.unbind(this, this.source); } this.source = null; this.unobserve(true); }; var _ChildInterpolationBinding = ChildInterpolationBinding; ChildInterpolationBinding = _aureliaBinding.connectable()(ChildInterpolationBinding) || ChildInterpolationBinding; return ChildInterpolationBinding; })(); exports.ChildInterpolationBinding = ChildInterpolationBinding; var SyntaxInterpreter = (function () { SyntaxInterpreter.inject = function inject() { return [_aureliaBinding.Parser, _aureliaBinding.ObserverLocator, _aureliaBinding.EventManager]; }; function SyntaxInterpreter(parser, observerLocator, eventManager) { _classCallCheck(this, SyntaxInterpreter); this.parser = parser; this.observerLocator = observerLocator; this.eventManager = eventManager; } SyntaxInterpreter.prototype.interpret = function interpret(resources, element, info, existingInstruction) { if (info.command in this) { return this[info.command](resources, element, info, existingInstruction); } return this.handleUnknownCommand(resources, element, info, existingInstruction); }; SyntaxInterpreter.prototype.handleUnknownCommand = function handleUnknownCommand(resources, element, info, existingInstruction) { _aureliaLogging.getLogger('templating-binding').warn('Unknown binding command.', info); return existingInstruction; }; SyntaxInterpreter.prototype.determineDefaultBindingMode = function determineDefaultBindingMode(element, attrName) { var tagName = element.tagName.toLowerCase(); if (tagName === 'input') { return attrName === 'value' || attrName === 'checked' || attrName === 'files' ? _aureliaBinding.bindingMode.twoWay : _aureliaBinding.bindingMode.oneWay; } else if (tagName === 'textarea' || tagName === 'select') { return attrName === 'value' ? _aureliaBinding.bindingMode.twoWay : _aureliaBinding.bindingMode.oneWay; } else if (attrName === 'textcontent' || attrName === 'innerhtml') { return element.contentEditable === 'true' ? _aureliaBinding.bindingMode.twoWay : _aureliaBinding.bindingMode.oneWay; } else if (attrName === 'scrolltop' || attrName === 'scrollleft') { return _aureliaBinding.bindingMode.twoWay; } return _aureliaBinding.bindingMode.oneWay; }; SyntaxInterpreter.prototype.bind = function bind(resources, element, info, existingInstruction) { var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap[info.attrName] || info.attrName, this.parser.parse(info.attrValue), info.defaultBindingMode || this.determineDefaultBindingMode(element, info.attrName), resources.lookupFunctions); return instruction; }; SyntaxInterpreter.prototype.trigger = function trigger(resources, element, info) { return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), false, true, resources.lookupFunctions); }; SyntaxInterpreter.prototype.delegate = function delegate(resources, element, info) { return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), true, true, resources.lookupFunctions); }; SyntaxInterpreter.prototype.call = function call(resources, element, info, existingInstruction) { var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new _aureliaBinding.CallExpression(this.observerLocator, info.attrName, this.parser.parse(info.attrValue), resources.lookupFunctions); return instruction; }; SyntaxInterpreter.prototype.options = function options(resources, element, info, existingInstruction) { var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); var attrValue = info.attrValue; var language = this.language; var name = null; var target = ''; var current = undefined; var i = undefined; var ii = undefined; for (i = 0, ii = attrValue.length; i < ii; ++i) { current = attrValue[i]; if (current === ';') { info = language.inspectAttribute(resources, name, target.trim()); language.createAttributeInstruction(resources, element, info, instruction); if (!instruction.attributes[info.attrName]) { instruction.attributes[info.attrName] = info.attrValue; } target = ''; name = null; } else if (current === ':' && name === null) { name = target.trim(); target = ''; } else { target += current; } } if (name !== null) { info = language.inspectAttribute(resources, name, target.trim()); language.createAttributeInstruction(resources, element, info, instruction); if (!instruction.attributes[info.attrName]) { instruction.attributes[info.attrName] = info.attrValue; } } return instruction; }; SyntaxInterpreter.prototype['for'] = function _for(resources, element, info, existingInstruction) { var parts = undefined; var keyValue = undefined; var instruction = undefined; var attrValue = undefined; var isDestructuring = undefined; attrValue = info.attrValue; isDestructuring = attrValue.match(/^ *[[].+[\]]/); parts = isDestructuring ? attrValue.split('of ') : attrValue.split(' of '); if (parts.length !== 2) { throw new Error('Incorrect syntax for "for". The form is: "$local of $items" or "[$key, $value] of $items".'); } instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); if (isDestructuring) { keyValue = parts[0].replace(/[[\]]/g, '').replace(/,/g, ' ').replace(/\s+/g, ' ').trim().split(' '); instruction.attributes.key = keyValue[0]; instruction.attributes.value = keyValue[1]; } else { instruction.attributes.local = parts[0]; } instruction.attributes.items = new _aureliaBinding.BindingExpression(this.observerLocator, 'items', this.parser.parse(parts[1]), _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions); return instruction; }; SyntaxInterpreter.prototype['two-way'] = function twoWay(resources, element, info, existingInstruction) { var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap[info.attrName] || info.attrName, this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.twoWay, resources.lookupFunctions); return instruction; }; SyntaxInterpreter.prototype['one-way'] = function oneWay(resources, element, info, existingInstruction) { var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap[info.attrName] || info.attrName, this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions); return instruction; }; SyntaxInterpreter.prototype['one-time'] = function oneTime(resources, element, info, existingInstruction) { var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap[info.attrName] || info.attrName, this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.oneTime, resources.lookupFunctions); return instruction; }; return SyntaxInterpreter; })(); exports.SyntaxInterpreter = SyntaxInterpreter; var info = {}; var TemplatingBindingLanguage = (function (_BindingLanguage) { _inherits(TemplatingBindingLanguage, _BindingLanguage); TemplatingBindingLanguage.inject = function inject() { return [_aureliaBinding.Parser, _aureliaBinding.ObserverLocator, SyntaxInterpreter]; }; function TemplatingBindingLanguage(parser, observerLocator, syntaxInterpreter) { _classCallCheck(this, TemplatingBindingLanguage); _BindingLanguage.call(this); this.parser = parser; this.observerLocator = observerLocator; this.syntaxInterpreter = syntaxInterpreter; this.emptyStringExpression = this.parser.parse('\'\''); syntaxInterpreter.language = this; this.attributeMap = syntaxInterpreter.attributeMap = { 'contenteditable': 'contentEditable', 'for': 'htmlFor', 'tabindex': 'tabIndex', 'textcontent': 'textContent', 'innerhtml': 'innerHTML', 'maxlength': 'maxLength', 'minlength': 'minLength', 'formaction': 'formAction', 'formenctype': 'formEncType', 'formmethod': 'formMethod', 'formnovalidate': 'formNoValidate', 'formtarget': 'formTarget', 'rowspan': 'rowSpan', 'colspan': 'colSpan', 'scrolltop': 'scrollTop', 'scrollleft': 'scrollLeft', 'readonly': 'readOnly' }; } TemplatingBindingLanguage.prototype.inspectAttribute = function inspectAttribute(resources, attrName, attrValue) { var parts = attrName.split('.'); info.defaultBindingMode = null; if (parts.length === 2) { info.attrName = parts[0].trim(); info.attrValue = attrValue; info.command = parts[1].trim(); if (info.command === 'ref') { info.expression = new _aureliaBinding.NameExpression(attrValue, info.attrName); info.command = null; info.attrName = 'ref'; } else { info.expression = null; } } else if (attrName === 'ref') { info.attrName = attrName; info.attrValue = attrValue; info.command = null; info.expression = new _aureliaBinding.NameExpression(attrValue, 'element'); } else { info.attrName = attrName; info.attrValue = attrValue; info.command = null; info.expression = this.parseContent(resources, attrName, attrValue); } return info; }; TemplatingBindingLanguage.prototype.createAttributeInstruction = function createAttributeInstruction(resources, element, theInfo, existingInstruction) { var instruction = undefined; if (theInfo.expression) { if (theInfo.attrName === 'ref') { return theInfo.expression; } instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(theInfo.attrName); instruction.attributes[theInfo.attrName] = theInfo.expression; } else if (theInfo.command) { instruction = this.syntaxInterpreter.interpret(resources, element, theInfo, existingInstruction); } return instruction; }; TemplatingBindingLanguage.prototype.parseText = function parseText(resources, value) { return this.parseContent(resources, 'textContent', value); }; TemplatingBindingLanguage.prototype.parseContent = function parseContent(resources, attrName, attrValue) { var i = attrValue.indexOf('${', 0); var ii = attrValue.length; var char = undefined; var pos = 0; var open = 0; var quote = null; var interpolationStart = undefined; var parts = undefined; var partIndex = 0; while (i >= 0 && i < ii - 2) { open = 1; interpolationStart = i; i += 2; do { char = attrValue[i]; i++; if (char === "'" || char === '"') { if (quote === null) { quote = char; } else if (quote === char) { quote = null; } continue; } if (char === '\\') { i++; continue; } if (quote !== null) { continue; } if (char === '{') { open++; } else if (char === '}') { open--; } } while (open > 0 && i < ii); if (open === 0) { parts = parts || []; if (attrValue[interpolationStart - 1] === '\\' && attrValue[interpolationStart - 2] !== '\\') { parts[partIndex] = attrValue.substring(pos, interpolationStart - 1) + attrValue.substring(interpolationStart, i); partIndex++; parts[partIndex] = this.emptyStringExpression; partIndex++; } else { parts[partIndex] = attrValue.substring(pos, interpolationStart); partIndex++; parts[partIndex] = this.parser.parse(attrValue.substring(interpolationStart + 2, i - 1)); partIndex++; } pos = i; i = attrValue.indexOf('${', i); } else { break; } } if (partIndex === 0) { return null; } parts[partIndex] = attrValue.substr(pos); return new InterpolationBindingExpression(this.observerLocator, this.attributeMap[attrName] || attrName, parts, _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions, attrName); }; return TemplatingBindingLanguage; })(_aureliaTemplating.BindingLanguage); exports.TemplatingBindingLanguage = TemplatingBindingLanguage; function configure(config) { config.container.registerSingleton(_aureliaTemplating.BindingLanguage, TemplatingBindingLanguage); config.container.registerAlias(_aureliaTemplating.BindingLanguage, TemplatingBindingLanguage); } }); define('aurelia-templating-resources/compose',['exports', 'aurelia-dependency-injection', 'aurelia-task-queue', 'aurelia-templating', 'aurelia-pal'], function (exports, _aureliaDependencyInjection, _aureliaTaskQueue, _aureliaTemplating, _aureliaPal) { exports.__esModule = true; var _createDecoratedClass = (function () { function defineProperties(target, descriptors, initializers) { for (var i = 0; i < descriptors.length; i++) { var descriptor = descriptors[i]; var decorators = descriptor.decorators; var key = descriptor.key; delete descriptor.key; delete descriptor.decorators; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor || descriptor.initializer) descriptor.writable = true; if (decorators) { for (var f = 0; f < decorators.length; f++) { var decorator = decorators[f]; if (typeof decorator === 'function') { descriptor = decorator(target, key, descriptor) || descriptor; } else { throw new TypeError('The decorator for method ' + descriptor.key + ' is of the invalid type ' + typeof decorator); } } if (descriptor.initializer !== undefined) { initializers[key] = descriptor; continue; } } Object.defineProperty(target, key, descriptor); } } return function (Constructor, protoProps, staticProps, protoInitializers, staticInitializers) { if (protoProps) defineProperties(Constructor.prototype, protoProps, protoInitializers); if (staticProps) defineProperties(Constructor, staticProps, staticInitializers); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _defineDecoratedPropertyDescriptor(target, key, descriptors) { var _descriptor = descriptors[key]; if (!_descriptor) return; var descriptor = {}; for (var _key in _descriptor) descriptor[_key] = _descriptor[_key]; descriptor.value = descriptor.initializer ? descriptor.initializer.call(target) : undefined; Object.defineProperty(target, key, descriptor); } var Compose = (function () { var _instanceInitializers = {}; _createDecoratedClass(Compose, [{ key: 'model', decorators: [_aureliaTemplating.bindable], initializer: null, enumerable: true }, { key: 'view', decorators: [_aureliaTemplating.bindable], initializer: null, enumerable: true }, { key: 'viewModel', decorators: [_aureliaTemplating.bindable], initializer: null, enumerable: true }], null, _instanceInitializers); function Compose(element, container, compositionEngine, viewSlot, viewResources, taskQueue) { _classCallCheck(this, _Compose); _defineDecoratedPropertyDescriptor(this, 'model', _instanceInitializers); _defineDecoratedPropertyDescriptor(this, 'view', _instanceInitializers); _defineDecoratedPropertyDescriptor(this, 'viewModel', _instanceInitializers); this.element = element; this.container = container; this.compositionEngine = compositionEngine; this.viewSlot = viewSlot; this.viewResources = viewResources; this.taskQueue = taskQueue; this.currentController = null; this.currentViewModel = null; } Compose.prototype.bind = function bind(bindingContext, overrideContext) { this.bindingContext = bindingContext; this.overrideContext = overrideContext; processInstruction(this, createInstruction(this, { view: this.view, viewModel: this.viewModel, model: this.model })); }; Compose.prototype.unbind = function unbind(bindingContext, overrideContext) { this.bindingContext = null; this.overrideContext = null; var returnToCache = true; var skipAnimation = true; this.viewSlot.removeAll(returnToCache, skipAnimation); }; Compose.prototype.modelChanged = function modelChanged(newValue, oldValue) { var _this = this; if (this.currentInstruction) { this.currentInstruction.model = newValue; return; } this.taskQueue.queueMicroTask(function () { if (_this.currentInstruction) { _this.currentInstruction.model = newValue; return; } var vm = _this.currentViewModel; if (vm && typeof vm.activate === 'function') { vm.activate(newValue); } }); }; Compose.prototype.viewChanged = function viewChanged(newValue, oldValue) { var _this2 = this; var instruction = createInstruction(this, { view: newValue, viewModel: this.currentViewModel || this.viewModel, model: this.model }); if (this.currentInstruction) { this.currentInstruction = instruction; return; } this.currentInstruction = instruction; this.taskQueue.queueMicroTask(function () { return processInstruction(_this2, _this2.currentInstruction); }); }; Compose.prototype.viewModelChanged = function viewModelChanged(newValue, oldValue) { var _this3 = this; var instruction = createInstruction(this, { viewModel: newValue, view: this.view, model: this.model }); if (this.currentInstruction) { this.currentInstruction = instruction; return; } this.currentInstruction = instruction; this.taskQueue.queueMicroTask(function () { return processInstruction(_this3, _this3.currentInstruction); }); }; var _Compose = Compose; Compose = _aureliaDependencyInjection.inject(_aureliaPal.DOM.Element, _aureliaDependencyInjection.Container, _aureliaTemplating.CompositionEngine, _aureliaTemplating.ViewSlot, _aureliaTemplating.ViewResources, _aureliaTaskQueue.TaskQueue)(Compose) || Compose; Compose = _aureliaTemplating.noView(Compose) || Compose; Compose = _aureliaTemplating.customElement('compose')(Compose) || Compose; return Compose; })(); exports.Compose = Compose; function createInstruction(composer, instruction) { return Object.assign(instruction, { bindingContext: composer.bindingContext, overrideContext: composer.overrideContext, container: composer.container, viewSlot: composer.viewSlot, viewResources: composer.viewResources, currentController: composer.currentController, host: composer.element }); } function processInstruction(composer, instruction) { composer.currentInstruction = null; composer.compositionEngine.compose(instruction).then(function (controller) { composer.currentController = controller; composer.currentViewModel = controller ? controller.viewModel : null; }); } }); define('aurelia-templating-resources/if',['exports', 'aurelia-templating', 'aurelia-dependency-injection', 'aurelia-task-queue'], function (exports, _aureliaTemplating, _aureliaDependencyInjection, _aureliaTaskQueue) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var If = (function () { function If(viewFactory, viewSlot, taskQueue) { _classCallCheck(this, _If); this.viewFactory = viewFactory; this.viewSlot = viewSlot; this.showing = false; this.taskQueue = taskQueue; this.view = null; this.bindingContext = null; this.overrideContext = null; } If.prototype.bind = function bind(bindingContext, overrideContext) { this.bindingContext = bindingContext; this.overrideContext = overrideContext; this.valueChanged(this.value); }; If.prototype.valueChanged = function valueChanged(newValue) { var _this = this; if (!newValue) { if (this.view !== null && this.showing) { this.taskQueue.queueMicroTask(function () { var viewOrPromise = _this.viewSlot.remove(_this.view); if (viewOrPromise instanceof Promise) { viewOrPromise.then(function () { return _this.view.unbind(); }); } else { _this.view.unbind(); } }); } this.showing = false; return; } if (this.view === null) { this.view = this.viewFactory.create(); } if (!this.view.isBound) { this.view.bind(this.bindingContext, this.overrideContext); } if (!this.showing) { this.showing = true; this.viewSlot.add(this.view); } }; If.prototype.unbind = function unbind() { if (this.view === null) { return; } this.view.unbind(); if (!this.viewFactory.isCaching) { return; } if (this.showing) { this.showing = false; this.viewSlot.remove(this.view, true, true); } this.view.returnToCache(); this.view = null; }; var _If = If; If = _aureliaDependencyInjection.inject(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot, _aureliaTaskQueue.TaskQueue)(If) || If; If = _aureliaTemplating.templateController(If) || If; If = _aureliaTemplating.customAttribute('if')(If) || If; return If; })(); exports.If = If; }); define('aurelia-templating-resources/with',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-binding'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaBinding) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var With = (function () { function With(viewFactory, viewSlot) { _classCallCheck(this, _With); this.viewFactory = viewFactory; this.viewSlot = viewSlot; this.parentOverrideContext = null; this.view = null; } With.prototype.bind = function bind(bindingContext, overrideContext) { this.parentOverrideContext = overrideContext; this.valueChanged(this.value); }; With.prototype.valueChanged = function valueChanged(newValue) { var overrideContext = _aureliaBinding.createOverrideContext(newValue, this.parentOverrideContext); if (!this.view) { this.view = this.viewFactory.create(); this.view.bind(newValue, overrideContext); this.viewSlot.add(this.view); } else { this.view.bind(newValue, overrideContext); } }; With.prototype.unbind = function unbind() { this.parentOverrideContext = null; if (this.view) { this.view.unbind(); } }; var _With = With; With = _aureliaDependencyInjection.inject(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot)(With) || With; With = _aureliaTemplating.templateController(With) || With; With = _aureliaTemplating.customAttribute('with')(With) || With; return With; })(); exports.With = With; }); define('aurelia-templating-resources/null-repeat-strategy',["exports"], function (exports) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var NullRepeatStrategy = (function () { function NullRepeatStrategy() { _classCallCheck(this, NullRepeatStrategy); } NullRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) {}; NullRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) {}; return NullRepeatStrategy; })(); exports.NullRepeatStrategy = NullRepeatStrategy; }); define('aurelia-templating-resources/repeat-utilities',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { exports.__esModule = true; exports.updateOverrideContexts = updateOverrideContexts; exports.createFullOverrideContext = createFullOverrideContext; exports.updateOverrideContext = updateOverrideContext; exports.getItemsSourceExpression = getItemsSourceExpression; exports.unwrapExpression = unwrapExpression; exports.isOneTime = isOneTime; function updateOverrideContexts(views, startIndex) { var length = views.length; if (startIndex > 0) { startIndex = startIndex - 1; } for (; startIndex < length; ++startIndex) { updateOverrideContext(views[startIndex].overrideContext, startIndex, length); } } function createFullOverrideContext(repeat, data, index, length, key) { var bindingContext = {}; var overrideContext = _aureliaBinding.createOverrideContext(bindingContext, repeat.scope.overrideContext); if (typeof key !== 'undefined') { bindingContext[repeat.key] = key; bindingContext[repeat.value] = data; } else { bindingContext[repeat.local] = data; } updateOverrideContext(overrideContext, index, length); return overrideContext; } function updateOverrideContext(overrideContext, index, length) { var first = index === 0; var last = index === length - 1; var even = index % 2 === 0; overrideContext.$index = index; overrideContext.$first = first; overrideContext.$last = last; overrideContext.$middle = !(first || last); overrideContext.$odd = !even; overrideContext.$even = even; } function getItemsSourceExpression(instruction, attrName) { return instruction.behaviorInstructions.filter(function (bi) { return bi.originalAttrName === attrName; })[0].attributes.items.sourceExpression; } function unwrapExpression(expression) { var unwrapped = false; while (expression instanceof _aureliaBinding.BindingBehavior) { expression = expression.expression; } while (expression instanceof _aureliaBinding.ValueConverter) { expression = expression.expression; unwrapped = true; } return unwrapped ? expression : null; } function isOneTime(expression) { while (expression instanceof _aureliaBinding.BindingBehavior) { if (expression.name === 'oneTime') { return true; } expression = expression.expression; } return false; } }); define('aurelia-templating-resources/array-repeat-strategy',['exports', './repeat-utilities'], function (exports, _repeatUtilities) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ArrayRepeatStrategy = (function () { function ArrayRepeatStrategy() { _classCallCheck(this, ArrayRepeatStrategy); } ArrayRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) { var i = undefined; var ii = undefined; var overrideContext = undefined; var view = undefined; for (i = 0, ii = items.length; i < ii; ++i) { overrideContext = _repeatUtilities.createFullOverrideContext(repeat, items[i], i, ii); view = repeat.viewFactory.create(); view.bind(overrideContext.bindingContext, overrideContext); repeat.viewSlot.add(view); } }; ArrayRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) { return observerLocator.getArrayObserver(items); }; ArrayRepeatStrategy.prototype.instanceMutated = function instanceMutated(repeat, array, splices) { var _this = this; var removeDelta = 0; var viewSlot = repeat.viewSlot; var rmPromises = []; for (var i = 0, ii = splices.length; i < ii; ++i) { var splice = splices[i]; var removed = splice.removed; for (var j = 0, jj = removed.length; j < jj; ++j) { var viewOrPromise = viewSlot.removeAt(splice.index + removeDelta + rmPromises.length, true); if (viewOrPromise instanceof Promise) { rmPromises.push(viewOrPromise); } } removeDelta -= splice.addedCount; } if (rmPromises.length > 0) { Promise.all(rmPromises).then(function () { var spliceIndexLow = _this._handleAddedSplices(repeat, array, splices); _repeatUtilities.updateOverrideContexts(repeat.viewSlot.children, spliceIndexLow); }); } else { var spliceIndexLow = this._handleAddedSplices(repeat, array, splices); _repeatUtilities.updateOverrideContexts(repeat.viewSlot.children, spliceIndexLow); } }; ArrayRepeatStrategy.prototype._handleAddedSplices = function _handleAddedSplices(repeat, array, splices) { var spliceIndex = undefined; var spliceIndexLow = undefined; var arrayLength = array.length; for (var i = 0, ii = splices.length; i < ii; ++i) { var splice = splices[i]; var addIndex = spliceIndex = splice.index; var end = splice.index + splice.addedCount; if (typeof spliceIndexLow === 'undefined' || spliceIndexLow === null || spliceIndexLow > splice.index) { spliceIndexLow = spliceIndex; } for (; addIndex < end; ++addIndex) { var overrideContext = _repeatUtilities.createFullOverrideContext(repeat, array[addIndex], addIndex, arrayLength); var view = repeat.viewFactory.create(); view.bind(overrideContext.bindingContext, overrideContext); repeat.viewSlot.insert(addIndex, view); } } return spliceIndexLow; }; return ArrayRepeatStrategy; })(); exports.ArrayRepeatStrategy = ArrayRepeatStrategy; }); define('aurelia-templating-resources/map-repeat-strategy',['exports', './repeat-utilities'], function (exports, _repeatUtilities) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var MapRepeatStrategy = (function () { function MapRepeatStrategy() { _classCallCheck(this, MapRepeatStrategy); } MapRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) { return observerLocator.getMapObserver(items); }; MapRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) { var viewFactory = repeat.viewFactory; var viewSlot = repeat.viewSlot; var index = 0; var overrideContext = undefined; var view = undefined; items.forEach(function (value, key) { overrideContext = _repeatUtilities.createFullOverrideContext(repeat, value, index, items.size, key); view = viewFactory.create(); view.bind(overrideContext.bindingContext, overrideContext); viewSlot.add(view); ++index; }); }; MapRepeatStrategy.prototype.instanceMutated = function instanceMutated(repeat, map, records) { var viewSlot = repeat.viewSlot; var key = undefined; var i = undefined; var ii = undefined; var view = undefined; var overrideContext = undefined; var removeIndex = undefined; var record = undefined; var rmPromises = []; var viewOrPromise = undefined; for (i = 0, ii = records.length; i < ii; ++i) { record = records[i]; key = record.key; switch (record.type) { case 'update': removeIndex = this._getViewIndexByKey(repeat, key); viewOrPromise = viewSlot.removeAt(removeIndex, true); if (viewOrPromise instanceof Promise) { rmPromises.push(viewOrPromise); } overrideContext = _repeatUtilities.createFullOverrideContext(repeat, map.get(key), removeIndex, map.size, key); view = repeat.viewFactory.create(); view.bind(overrideContext.bindingContext, overrideContext); viewSlot.insert(removeIndex, view); break; case 'add': overrideContext = _repeatUtilities.createFullOverrideContext(repeat, map.get(key), map.size - 1, map.size, key); view = repeat.viewFactory.create(); view.bind(overrideContext.bindingContext, overrideContext); viewSlot.insert(map.size - 1, view); break; case 'delete': if (record.oldValue === undefined) { return; } removeIndex = this._getViewIndexByKey(repeat, key); viewOrPromise = viewSlot.removeAt(removeIndex, true); if (viewOrPromise instanceof Promise) { rmPromises.push(viewOrPromise); } break; case 'clear': viewSlot.removeAll(true); break; default: continue; } } if (rmPromises.length > 0) { Promise.all(rmPromises).then(function () { _repeatUtilities.updateOverrideContexts(repeat.viewSlot.children, 0); }); } else { _repeatUtilities.updateOverrideContexts(repeat.viewSlot.children, 0); } }; MapRepeatStrategy.prototype._getViewIndexByKey = function _getViewIndexByKey(repeat, key) { var viewSlot = repeat.viewSlot; var i = undefined; var ii = undefined; var child = undefined; for (i = 0, ii = viewSlot.children.length; i < ii; ++i) { child = viewSlot.children[i]; if (child.bindingContext[repeat.key] === key) { return i; } } }; return MapRepeatStrategy; })(); exports.MapRepeatStrategy = MapRepeatStrategy; }); define('aurelia-templating-resources/number-repeat-strategy',['exports', './repeat-utilities'], function (exports, _repeatUtilities) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var NumberRepeatStrategy = (function () { function NumberRepeatStrategy() { _classCallCheck(this, NumberRepeatStrategy); } NumberRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver() { return null; }; NumberRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, value) { var viewFactory = repeat.viewFactory; var viewSlot = repeat.viewSlot; var childrenLength = viewSlot.children.length; var i = undefined; var ii = undefined; var overrideContext = undefined; var view = undefined; var viewsToRemove = undefined; value = Math.floor(value); viewsToRemove = childrenLength - value; if (viewsToRemove > 0) { if (viewsToRemove > childrenLength) { viewsToRemove = childrenLength; } for (i = 0, ii = viewsToRemove; i < ii; ++i) { viewSlot.removeAt(childrenLength - (i + 1), true); } return; } for (i = childrenLength, ii = value; i < ii; ++i) { overrideContext = _repeatUtilities.createFullOverrideContext(repeat, i, i, ii); view = viewFactory.create(); view.bind(overrideContext.bindingContext, overrideContext); viewSlot.add(view); } _repeatUtilities.updateOverrideContexts(repeat.viewSlot.children, 0); }; return NumberRepeatStrategy; })(); exports.NumberRepeatStrategy = NumberRepeatStrategy; }); define('aurelia-templating-resources/repeat-strategy-locator',['exports', './null-repeat-strategy', './array-repeat-strategy', './map-repeat-strategy', './number-repeat-strategy'], function (exports, _nullRepeatStrategy, _arrayRepeatStrategy, _mapRepeatStrategy, _numberRepeatStrategy) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var RepeatStrategyLocator = (function () { function RepeatStrategyLocator() { _classCallCheck(this, RepeatStrategyLocator); this.matchers = []; this.strategies = []; this.addStrategy(function (items) { return items === null || items === undefined; }, new _nullRepeatStrategy.NullRepeatStrategy()); this.addStrategy(function (items) { return items instanceof Array; }, new _arrayRepeatStrategy.ArrayRepeatStrategy()); this.addStrategy(function (items) { return items instanceof Map; }, new _mapRepeatStrategy.MapRepeatStrategy()); this.addStrategy(function (items) { return typeof items === 'number'; }, new _numberRepeatStrategy.NumberRepeatStrategy()); } RepeatStrategyLocator.prototype.addStrategy = function addStrategy(matcher, strategy) { this.matchers.push(matcher); this.strategies.push(strategy); }; RepeatStrategyLocator.prototype.getStrategy = function getStrategy(items) { var matchers = this.matchers; for (var i = 0, ii = matchers.length; i < ii; ++i) { if (matchers[i](items)) { return this.strategies[i]; } } return null; }; return RepeatStrategyLocator; })(); exports.RepeatStrategyLocator = RepeatStrategyLocator; }); define('aurelia-templating-resources/repeat',['exports', 'aurelia-dependency-injection', 'aurelia-binding', 'aurelia-templating', './repeat-strategy-locator', './repeat-utilities'], function (exports, _aureliaDependencyInjection, _aureliaBinding, _aureliaTemplating, _repeatStrategyLocator, _repeatUtilities) { exports.__esModule = true; var _createDecoratedClass = (function () { function defineProperties(target, descriptors, initializers) { for (var i = 0; i < descriptors.length; i++) { var descriptor = descriptors[i]; var decorators = descriptor.decorators; var key = descriptor.key; delete descriptor.key; delete descriptor.decorators; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor || descriptor.initializer) descriptor.writable = true; if (decorators) { for (var f = 0; f < decorators.length; f++) { var decorator = decorators[f]; if (typeof decorator === 'function') { descriptor = decorator(target, key, descriptor) || descriptor; } else { throw new TypeError('The decorator for method ' + descriptor.key + ' is of the invalid type ' + typeof decorator); } } if (descriptor.initializer !== undefined) { initializers[key] = descriptor; continue; } } Object.defineProperty(target, key, descriptor); } } return function (Constructor, protoProps, staticProps, protoInitializers, staticInitializers) { if (protoProps) defineProperties(Constructor.prototype, protoProps, protoInitializers); if (staticProps) defineProperties(Constructor, staticProps, staticInitializers); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _defineDecoratedPropertyDescriptor(target, key, descriptors) { var _descriptor = descriptors[key]; if (!_descriptor) return; var descriptor = {}; for (var _key in _descriptor) descriptor[_key] = _descriptor[_key]; descriptor.value = descriptor.initializer ? descriptor.initializer.call(target) : undefined; Object.defineProperty(target, key, descriptor); } var Repeat = (function () { var _instanceInitializers = {}; _createDecoratedClass(Repeat, [{ key: 'items', decorators: [_aureliaTemplating.bindable], initializer: null, enumerable: true }, { key: 'local', decorators: [_aureliaTemplating.bindable], initializer: null, enumerable: true }, { key: 'key', decorators: [_aureliaTemplating.bindable], initializer: null, enumerable: true }, { key: 'value', decorators: [_aureliaTemplating.bindable], initializer: null, enumerable: true }], null, _instanceInitializers); function Repeat(viewFactory, instruction, viewSlot, viewResources, observerLocator, strategyLocator) { _classCallCheck(this, _Repeat); _defineDecoratedPropertyDescriptor(this, 'items', _instanceInitializers); _defineDecoratedPropertyDescriptor(this, 'local', _instanceInitializers); _defineDecoratedPropertyDescriptor(this, 'key', _instanceInitializers); _defineDecoratedPropertyDescriptor(this, 'value', _instanceInitializers); this.viewFactory = viewFactory; this.instruction = instruction; this.viewSlot = viewSlot; this.lookupFunctions = viewResources.lookupFunctions; this.observerLocator = observerLocator; this.local = 'item'; this.key = 'key'; this.value = 'value'; this.strategyLocator = strategyLocator; this.ignoreMutation = false; this.sourceExpression = _repeatUtilities.getItemsSourceExpression(this.instruction, 'repeat.for'); this.isOneTime = _repeatUtilities.isOneTime(this.sourceExpression); } Repeat.prototype.call = function call(context, changes) { this[context](this.items, changes); }; Repeat.prototype.bind = function bind(bindingContext, overrideContext) { this.scope = { bindingContext: bindingContext, overrideContext: overrideContext }; this.itemsChanged(); }; Repeat.prototype.unbind = function unbind() { this.scope = null; this.items = null; this.viewSlot.removeAll(true); this._unsubscribeCollection(); }; Repeat.prototype._unsubscribeCollection = function _unsubscribeCollection() { if (this.collectionObserver) { this.collectionObserver.unsubscribe(this.callContext, this); this.collectionObserver = null; this.callContext = null; } }; Repeat.prototype.processItemsByStrategy = function processItemsByStrategy() { if (!this.isOneTime && !this._observeInnerCollection()) { this._observeCollection(); } this.strategy.instanceChanged(this, this.items); }; Repeat.prototype.itemsChanged = function itemsChanged() { var _this = this; this._unsubscribeCollection(); if (!this.scope) { return; } var items = this.items; this.strategy = this.strategyLocator.getStrategy(items); var removePromise = this.viewSlot.removeAll(true); if (removePromise instanceof Promise) { removePromise.then(function () { return _this.processItemsByStrategy(); }); return; } this.processItemsByStrategy(); }; Repeat.prototype._getInnerCollection = function _getInnerCollection() { var expression = _repeatUtilities.unwrapExpression(this.sourceExpression); if (!expression) { return null; } return expression.evaluate(this.scope, null); }; Repeat.prototype.handleCollectionMutated = function handleCollectionMutated(collection, changes) { this.strategy.instanceMutated(this, collection, changes); }; Repeat.prototype.handleInnerCollectionMutated = function handleInnerCollectionMutated(collection, changes) { var _this2 = this; if (this.ignoreMutation) { return; } this.ignoreMutation = true; var newItems = this.sourceExpression.evaluate(this.scope, this.lookupFunctions); this.observerLocator.taskQueue.queueMicroTask(function () { return _this2.ignoreMutation = false; }); if (newItems === this.items) { return; } this.items = newItems; this.itemsChanged(); }; Repeat.prototype._observeInnerCollection = function _observeInnerCollection() { var items = this._getInnerCollection(); var strategy = this.strategyLocator.getStrategy(items); if (!strategy) { return false; } this.collectionObserver = strategy.getCollectionObserver(this.observerLocator, items); if (!this.collectionObserver) { return false; } this.callContext = 'handleInnerCollectionMutated'; this.collectionObserver.subscribe(this.callContext, this); return true; }; Repeat.prototype._observeCollection = function _observeCollection() { var items = this.items; this.collectionObserver = this.strategy.getCollectionObserver(this.observerLocator, items); if (this.collectionObserver) { this.callContext = 'handleCollectionMutated'; this.collectionObserver.subscribe(this.callContext, this); } }; var _Repeat = Repeat; Repeat = _aureliaDependencyInjection.inject(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.TargetInstruction, _aureliaTemplating.ViewSlot, _aureliaTemplating.ViewResources, _aureliaBinding.ObserverLocator, _repeatStrategyLocator.RepeatStrategyLocator)(Repeat) || Repeat; Repeat = _aureliaTemplating.templateController(Repeat) || Repeat; Repeat = _aureliaTemplating.customAttribute('repeat')(Repeat) || Repeat; return Repeat; })(); exports.Repeat = Repeat; }); define('aurelia-templating-resources/show',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-pal'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaPal) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Show = (function () { function Show(element, animator) { _classCallCheck(this, _Show); this.element = element; this.animator = animator; } Show.prototype.valueChanged = function valueChanged(newValue) { if (newValue) { this.animator.removeClass(this.element, 'aurelia-hide'); } else { this.animator.addClass(this.element, 'aurelia-hide'); } }; Show.prototype.bind = function bind(bindingContext) { this.valueChanged(this.value); }; var _Show = Show; Show = _aureliaDependencyInjection.inject(_aureliaPal.DOM.Element, _aureliaTemplating.Animator)(Show) || Show; Show = _aureliaTemplating.customAttribute('show')(Show) || Show; return Show; })(); exports.Show = Show; }); define('aurelia-templating-resources/html-sanitizer',['exports'], function (exports) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi; var HTMLSanitizer = (function () { function HTMLSanitizer() { _classCallCheck(this, HTMLSanitizer); } HTMLSanitizer.prototype.sanitize = function sanitize(input) { return input.replace(SCRIPT_REGEX, ''); }; return HTMLSanitizer; })(); exports.HTMLSanitizer = HTMLSanitizer; }); define('aurelia-templating-resources/sanitize-html',['exports', 'aurelia-binding', 'aurelia-dependency-injection', './html-sanitizer'], function (exports, _aureliaBinding, _aureliaDependencyInjection, _htmlSanitizer) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var SanitizeHTMLValueConverter = (function () { function SanitizeHTMLValueConverter(sanitizer) { _classCallCheck(this, _SanitizeHTMLValueConverter); this.sanitizer = sanitizer; } SanitizeHTMLValueConverter.prototype.toView = function toView(untrustedMarkup) { if (untrustedMarkup === null || untrustedMarkup === undefined) { return null; } return this.sanitizer.sanitize(untrustedMarkup); }; var _SanitizeHTMLValueConverter = SanitizeHTMLValueConverter; SanitizeHTMLValueConverter = _aureliaDependencyInjection.inject(_htmlSanitizer.HTMLSanitizer)(SanitizeHTMLValueConverter) || SanitizeHTMLValueConverter; SanitizeHTMLValueConverter = _aureliaBinding.valueConverter('sanitizeHTML')(SanitizeHTMLValueConverter) || SanitizeHTMLValueConverter; return SanitizeHTMLValueConverter; })(); exports.SanitizeHTMLValueConverter = SanitizeHTMLValueConverter; }); define('aurelia-templating-resources/replaceable',['exports', 'aurelia-dependency-injection', 'aurelia-templating'], function (exports, _aureliaDependencyInjection, _aureliaTemplating) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Replaceable = (function () { function Replaceable(viewFactory, viewSlot) { _classCallCheck(this, _Replaceable); this.viewFactory = viewFactory; this.viewSlot = viewSlot; this.view = null; } Replaceable.prototype.bind = function bind(bindingContext, overrideContext) { if (this.view === null) { this.view = this.viewFactory.create(); this.viewSlot.add(this.view); } this.view.bind(bindingContext, overrideContext); }; Replaceable.prototype.unbind = function unbind() { this.view.unbind(); }; var _Replaceable = Replaceable; Replaceable = _aureliaDependencyInjection.inject(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot)(Replaceable) || Replaceable; Replaceable = _aureliaTemplating.templateController(Replaceable) || Replaceable; Replaceable = _aureliaTemplating.customAttribute('replaceable')(Replaceable) || Replaceable; return Replaceable; })(); exports.Replaceable = Replaceable; }); define('aurelia-templating-resources/focus',['exports', 'aurelia-templating', 'aurelia-binding', 'aurelia-dependency-injection', 'aurelia-task-queue', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaBinding, _aureliaDependencyInjection, _aureliaTaskQueue, _aureliaPal) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Focus = (function () { function Focus(element, taskQueue) { var _this = this; _classCallCheck(this, _Focus); this.element = element; this.taskQueue = taskQueue; this.focusListener = function (e) { _this.value = true; }; this.blurListener = function (e) { if (_aureliaPal.DOM.activeElement !== _this.element) { _this.value = false; } }; } Focus.prototype.valueChanged = function valueChanged(newValue) { if (newValue) { this._giveFocus(); } else { this.element.blur(); } }; Focus.prototype._giveFocus = function _giveFocus() { var _this2 = this; this.taskQueue.queueMicroTask(function () { if (_this2.value) { _this2.element.focus(); } }); }; Focus.prototype.attached = function attached() { this.element.addEventListener('focus', this.focusListener); this.element.addEventListener('blur', this.blurListener); }; Focus.prototype.detached = function detached() { this.element.removeEventListener('focus', this.focusListener); this.element.removeEventListener('blur', this.blurListener); }; var _Focus = Focus; Focus = _aureliaDependencyInjection.inject(_aureliaPal.DOM.Element, _aureliaTaskQueue.TaskQueue)(Focus) || Focus; Focus = _aureliaTemplating.customAttribute('focus', _aureliaBinding.bindingMode.twoWay)(Focus) || Focus; return Focus; })(); exports.Focus = Focus; }); define('aurelia-templating-resources/compile-spy',['exports', 'aurelia-templating', 'aurelia-dependency-injection', 'aurelia-logging', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaDependencyInjection, _aureliaLogging, _aureliaPal) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var CompileSpy = (function () { function CompileSpy(element, instruction) { _classCallCheck(this, _CompileSpy); _aureliaLogging.getLogger('compile-spy').info(element, instruction); } var _CompileSpy = CompileSpy; CompileSpy = _aureliaDependencyInjection.inject(_aureliaPal.DOM.Element, _aureliaTemplating.TargetInstruction)(CompileSpy) || CompileSpy; CompileSpy = _aureliaTemplating.customAttribute('compile-spy')(CompileSpy) || CompileSpy; return CompileSpy; })(); exports.CompileSpy = CompileSpy; }); define('aurelia-templating-resources/view-spy',['exports', 'aurelia-templating', 'aurelia-logging'], function (exports, _aureliaTemplating, _aureliaLogging) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ViewSpy = (function () { function ViewSpy() { _classCallCheck(this, _ViewSpy); this.logger = _aureliaLogging.getLogger('view-spy'); } ViewSpy.prototype._log = function _log(lifecycleName, context) { if (!this.value && lifecycleName === 'created') { this.logger.info(lifecycleName, this.view); } else if (this.value && this.value.indexOf(lifecycleName) !== -1) { this.logger.info(lifecycleName, this.view, context); } }; ViewSpy.prototype.created = function created(view) { this.view = view; this._log('created'); }; ViewSpy.prototype.bind = function bind(bindingContext) { this._log('bind', bindingContext); }; ViewSpy.prototype.attached = function attached() { this._log('attached'); }; ViewSpy.prototype.detached = function detached() { this._log('detached'); }; ViewSpy.prototype.unbind = function unbind() { this._log('unbind'); }; var _ViewSpy = ViewSpy; ViewSpy = _aureliaTemplating.customAttribute('view-spy')(ViewSpy) || ViewSpy; return ViewSpy; })(); exports.ViewSpy = ViewSpy; }); define('aurelia-templating-resources/dynamic-element',['exports', 'aurelia-templating'], function (exports, _aureliaTemplating) { exports.__esModule = true; exports._createDynamicElement = _createDynamicElement; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _createDynamicElement(name, viewUrl, bindableNames) { var DynamicElement = (function () { function DynamicElement() { _classCallCheck(this, _DynamicElement); } DynamicElement.prototype.bind = function bind(bindingContext) { this.$parent = bindingContext; }; var _DynamicElement = DynamicElement; DynamicElement = _aureliaTemplating.useView(viewUrl)(DynamicElement) || DynamicElement; DynamicElement = _aureliaTemplating.customElement(name)(DynamicElement) || DynamicElement; return DynamicElement; })(); for (var i = 0, ii = bindableNames.length; i < ii; ++i) { _aureliaTemplating.bindable(bindableNames[i])(DynamicElement); } return DynamicElement; } }); define('aurelia-templating-resources/css-resource',['exports', 'aurelia-templating', 'aurelia-loader', 'aurelia-dependency-injection', 'aurelia-path', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaLoader, _aureliaDependencyInjection, _aureliaPath, _aureliaPal) { exports.__esModule = true; exports._createCSSResource = _createCSSResource; 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var cssUrlMatcher = /url\((?!['"]data)([^)]+)\)/gi; function fixupCSSUrls(address, css) { return css.replace(cssUrlMatcher, function (match, p1) { var quote = p1.charAt(0); if (quote === '\'' || quote === '"') { p1 = p1.substr(1, p1.length - 2); } return 'url(\'' + _aureliaPath.relativeToFile(p1, address) + '\')'; }); } var CSSResource = (function () { function CSSResource(address) { _classCallCheck(this, CSSResource); this.address = address; this._global = null; this._scoped = null; } CSSResource.prototype.initialize = function initialize(container, target) { this._global = new target('global'); this._scoped = new target('scoped'); }; CSSResource.prototype.register = function register(registry, name) { registry.registerViewEngineHooks(name === 'scoped' ? this._scoped : this._global); }; CSSResource.prototype.load = function load(container) { var _this = this; return container.get(_aureliaLoader.Loader).loadText(this.address).then(function (text) { text = fixupCSSUrls(_this.address, text); _this._global.css = text; _this._scoped.css = text; }); }; return CSSResource; })(); var CSSViewEngineHooks = (function () { function CSSViewEngineHooks(mode) { _classCallCheck(this, CSSViewEngineHooks); this.mode = mode; this.css = null; this._alreadyGloballyInjected = false; } CSSViewEngineHooks.prototype.beforeCompile = function beforeCompile(content, resources, instruction) { if (this.mode === 'scoped') { if (instruction.targetShadowDOM) { _aureliaPal.DOM.injectStyles(this.css, content, true); } else if (_aureliaPal.FEATURE.scopedCSS) { var styleNode = _aureliaPal.DOM.injectStyles(this.css, content, true); styleNode.setAttribute('scoped', 'scoped'); } else if (!this._alreadyGloballyInjected) { _aureliaPal.DOM.injectStyles(this.css); this._alreadyGloballyInjected = true; } } else if (!this._alreadyGloballyInjected) { _aureliaPal.DOM.injectStyles(this.css); this._alreadyGloballyInjected = true; } }; return CSSViewEngineHooks; })(); function _createCSSResource(address) { var ViewCSS = (function (_CSSViewEngineHooks) { _inherits(ViewCSS, _CSSViewEngineHooks); function ViewCSS() { _classCallCheck(this, _ViewCSS); _CSSViewEngineHooks.apply(this, arguments); } var _ViewCSS = ViewCSS; ViewCSS = _aureliaTemplating.resource(new CSSResource(address))(ViewCSS) || ViewCSS; return ViewCSS; })(CSSViewEngineHooks); return ViewCSS; } }); define('aurelia-templating-resources/binding-mode-behaviors',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { exports.__esModule = true; 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ModeBindingBehavior = (function () { function ModeBindingBehavior(mode) { _classCallCheck(this, ModeBindingBehavior); this.mode = mode; } ModeBindingBehavior.prototype.bind = function bind(binding, source, lookupFunctions) { binding.originalMode = binding.mode; binding.mode = this.mode; }; ModeBindingBehavior.prototype.unbind = function unbind(binding, source) { binding.mode = binding.originalMode; binding.originalMode = null; }; return ModeBindingBehavior; })(); var OneTimeBindingBehavior = (function (_ModeBindingBehavior) { _inherits(OneTimeBindingBehavior, _ModeBindingBehavior); function OneTimeBindingBehavior() { _classCallCheck(this, OneTimeBindingBehavior); _ModeBindingBehavior.call(this, _aureliaBinding.bindingMode.oneTime); } return OneTimeBindingBehavior; })(ModeBindingBehavior); exports.OneTimeBindingBehavior = OneTimeBindingBehavior; var OneWayBindingBehavior = (function (_ModeBindingBehavior2) { _inherits(OneWayBindingBehavior, _ModeBindingBehavior2); function OneWayBindingBehavior() { _classCallCheck(this, OneWayBindingBehavior); _ModeBindingBehavior2.call(this, _aureliaBinding.bindingMode.oneWay); } return OneWayBindingBehavior; })(ModeBindingBehavior); exports.OneWayBindingBehavior = OneWayBindingBehavior; var TwoWayBindingBehavior = (function (_ModeBindingBehavior3) { _inherits(TwoWayBindingBehavior, _ModeBindingBehavior3); function TwoWayBindingBehavior() { _classCallCheck(this, TwoWayBindingBehavior); _ModeBindingBehavior3.call(this, _aureliaBinding.bindingMode.twoWay); } return TwoWayBindingBehavior; })(ModeBindingBehavior); exports.TwoWayBindingBehavior = TwoWayBindingBehavior; }); define('aurelia-templating-resources/throttle-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function throttle(newValue) { var _this = this; var state = this.throttleState; var elapsed = +new Date() - state.last; if (elapsed >= state.delay) { clearTimeout(state.timeoutId); state.timeoutId = null; state.last = +new Date(); this.throttledMethod(newValue); return; } state.newValue = newValue; if (state.timeoutId === null) { state.timeoutId = setTimeout(function () { state.timeoutId = null; state.last = +new Date(); _this.throttledMethod(state.newValue); }, state.delay - elapsed); } } var ThrottleBindingBehavior = (function () { function ThrottleBindingBehavior() { _classCallCheck(this, ThrottleBindingBehavior); } ThrottleBindingBehavior.prototype.bind = function bind(binding, source) { var delay = arguments.length <= 2 || arguments[2] === undefined ? 200 : arguments[2]; var methodToThrottle = 'updateTarget'; if (binding.callSource) { methodToThrottle = 'callSource'; } else if (binding.updateSource && binding.mode === _aureliaBinding.bindingMode.twoWay) { methodToThrottle = 'updateSource'; } binding.throttledMethod = binding[methodToThrottle]; binding.throttledMethod.originalName = methodToThrottle; binding[methodToThrottle] = throttle; binding.throttleState = { delay: delay, last: 0, timeoutId: null }; }; ThrottleBindingBehavior.prototype.unbind = function unbind(binding, source) { var methodToRestore = binding.throttledMethod.originalName; binding[methodToRestore] = binding.throttledMethod; binding.throttledMethod = null; clearTimeout(binding.throttleState.timeoutId); binding.throttleState = null; }; return ThrottleBindingBehavior; })(); exports.ThrottleBindingBehavior = ThrottleBindingBehavior; }); define('aurelia-templating-resources/debounce-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function debounce(newValue) { var _this = this; var state = this.debounceState; if (state.immediate) { state.immediate = false; this.debouncedMethod(newValue); return; } clearTimeout(state.timeoutId); state.timeoutId = setTimeout(function () { return _this.debouncedMethod(newValue); }, state.delay); } var DebounceBindingBehavior = (function () { function DebounceBindingBehavior() { _classCallCheck(this, DebounceBindingBehavior); } DebounceBindingBehavior.prototype.bind = function bind(binding, source) { var delay = arguments.length <= 2 || arguments[2] === undefined ? 200 : arguments[2]; var methodToDebounce = 'updateTarget'; if (binding.callSource) { methodToDebounce = 'callSource'; } else if (binding.updateSource && binding.mode === _aureliaBinding.bindingMode.twoWay) { methodToDebounce = 'updateSource'; } binding.debouncedMethod = binding[methodToDebounce]; binding.debouncedMethod.originalName = methodToDebounce; binding[methodToDebounce] = debounce; binding.debounceState = { delay: delay, timeoutId: null, immediate: methodToDebounce === 'updateTarget' }; }; DebounceBindingBehavior.prototype.unbind = function unbind(binding, source) { var methodToRestore = binding.debouncedMethod.originalName; binding[methodToRestore] = binding.debouncedMethod; binding.debouncedMethod = null; clearTimeout(binding.debounceState.timeoutId); binding.debounceState = null; }; return DebounceBindingBehavior; })(); exports.DebounceBindingBehavior = DebounceBindingBehavior; }); define('aurelia-templating-resources/binding-signaler',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var BindingSignaler = (function () { function BindingSignaler() { _classCallCheck(this, BindingSignaler); this.signals = {}; } BindingSignaler.prototype.signal = function signal(name) { var bindings = this.signals[name]; if (!bindings) { return; } var i = bindings.length; while (i--) { bindings[i].call(_aureliaBinding.sourceContext); } }; return BindingSignaler; })(); exports.BindingSignaler = BindingSignaler; }); define('aurelia-templating-resources/signal-binding-behavior',['exports', 'aurelia-binding', './binding-signaler'], function (exports, _aureliaBinding, _bindingSignaler) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var SignalBindingBehavior = (function () { SignalBindingBehavior.inject = function inject() { return [_bindingSignaler.BindingSignaler]; }; function SignalBindingBehavior(bindingSignaler) { _classCallCheck(this, SignalBindingBehavior); this.signals = bindingSignaler.signals; } SignalBindingBehavior.prototype.bind = function bind(binding, source, name) { if (!binding.updateTarget) { throw new Error('Only property bindings and string interpolation bindings can be signaled. Trigger, delegate and call bindings cannot be signaled.'); } if (binding.mode === _aureliaBinding.bindingMode.oneTime) { throw new Error('One-time bindings cannot be signaled.'); } var bindings = this.signals[name] || (this.signals[name] = []); bindings.push(binding); binding.signalName = name; }; SignalBindingBehavior.prototype.unbind = function unbind(binding, source) { var name = binding.signalName; binding.signalName = null; var bindings = this.signals[name]; bindings.splice(bindings.indexOf(binding), 1); }; return SignalBindingBehavior; })(); exports.SignalBindingBehavior = SignalBindingBehavior; }); define('aurelia-templating-resources/update-trigger-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) { exports.__esModule = true; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var eventNamesRequired = 'The updateTrigger binding behavior requires at least one event name argument: eg <input value.bind="firstName & updateTrigger:\'blur\'">'; var notApplicableMessage = 'The updateTrigger binding behavior can only be applied to two-way bindings on input/select elements.'; var UpdateTriggerBindingBehavior = (function () { _createClass(UpdateTriggerBindingBehavior, null, [{ key: 'inject', value: [_aureliaBinding.EventManager], enumerable: true }]); function UpdateTriggerBindingBehavior(eventManager) { _classCallCheck(this, UpdateTriggerBindingBehavior); this.eventManager = eventManager; } UpdateTriggerBindingBehavior.prototype.bind = function bind(binding, source) { for (var _len = arguments.length, events = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { events[_key - 2] = arguments[_key]; } if (events.length === 0) { throw new Error(eventNamesRequired); } if (binding.mode !== _aureliaBinding.bindingMode.twoWay || !binding.targetProperty.handler) { throw new Error(notApplicableMessage); } binding.targetProperty.originalHandler = binding.targetProperty.handler; var handler = this.eventManager.createElementHandler(events); binding.targetProperty.handler = handler; }; UpdateTriggerBindingBehavior.prototype.unbind = function unbind(binding, source) { binding.targetProperty.handler = binding.targetProperty.originalHandler; binding.targetProperty.originalHandler = null; }; return UpdateTriggerBindingBehavior; })(); exports.UpdateTriggerBindingBehavior = UpdateTriggerBindingBehavior; }); define('aurelia-templating-resources/aurelia-templating-resources',['exports', './compose', './if', './with', './repeat', './show', './sanitize-html', './replaceable', './focus', './compile-spy', './view-spy', 'aurelia-templating', './dynamic-element', './css-resource', 'aurelia-pal', './html-sanitizer', './binding-mode-behaviors', './throttle-binding-behavior', './debounce-binding-behavior', './signal-binding-behavior', './binding-signaler', './update-trigger-binding-behavior'], function (exports, _compose, _if, _with, _repeat, _show, _sanitizeHtml, _replaceable, _focus, _compileSpy, _viewSpy, _aureliaTemplating, _dynamicElement, _cssResource, _aureliaPal, _htmlSanitizer, _bindingModeBehaviors, _throttleBindingBehavior, _debounceBindingBehavior, _signalBindingBehavior, _bindingSignaler, _updateTriggerBindingBehavior) { exports.__esModule = true; function configure(config) { if (_aureliaPal.FEATURE.shadowDOM) { _aureliaPal.DOM.injectStyles('body /deep/ .aurelia-hide { display:none !important; }'); } else { _aureliaPal.DOM.injectStyles('.aurelia-hide { display:none !important; }'); } config.globalResources('./compose', './if', './with', './repeat', './show', './replaceable', './sanitize-html', './focus', './compile-spy', './view-spy', './binding-mode-behaviors', './throttle-binding-behavior', './debounce-binding-behavior', './signal-binding-behavior', './update-trigger-binding-behavior'); var viewEngine = config.container.get(_aureliaTemplating.ViewEngine); var loader = config.aurelia.loader; viewEngine.addResourcePlugin('.html', { 'fetch': function fetch(address) { return loader.loadTemplate(address).then(function (registryEntry) { var _ref; var bindable = registryEntry.template.getAttribute('bindable'); var elementName = address.replace('.html', ''); var index = elementName.lastIndexOf('/'); if (index !== 0) { elementName = elementName.substring(index + 1); } if (bindable) { bindable = bindable.split(',').map(function (x) { return x.trim(); }); registryEntry.template.removeAttribute('bindable'); } else { bindable = []; } return _ref = {}, _ref[elementName] = _dynamicElement._createDynamicElement(elementName, address, bindable), _ref; }); } }); viewEngine.addResourcePlugin('.css', { 'fetch': function fetch(address) { var _ref2; return _ref2 = {}, _ref2[address] = _cssResource._createCSSResource(address), _ref2; } }); } exports.Compose = _compose.Compose; exports.If = _if.If; exports.With = _with.With; exports.Repeat = _repeat.Repeat; exports.Show = _show.Show; exports.HTMLSanitizer = _htmlSanitizer.HTMLSanitizer; exports.SanitizeHTMLValueConverter = _sanitizeHtml.SanitizeHTMLValueConverter; exports.Replaceable = _replaceable.Replaceable; exports.Focus = _focus.Focus; exports.CompileSpy = _compileSpy.CompileSpy; exports.ViewSpy = _viewSpy.ViewSpy; exports.configure = configure; exports.OneTimeBindingBehavior = _bindingModeBehaviors.OneTimeBindingBehavior; exports.OneWayBindingBehavior = _bindingModeBehaviors.OneWayBindingBehavior; exports.TwoWayBindingBehavior = _bindingModeBehaviors.TwoWayBindingBehavior; exports.ThrottleBindingBehavior = _throttleBindingBehavior.ThrottleBindingBehavior; exports.DebounceBindingBehavior = _debounceBindingBehavior.DebounceBindingBehavior; exports.SignalBindingBehavior = _signalBindingBehavior.SignalBindingBehavior; exports.BindingSignaler = _bindingSignaler.BindingSignaler; exports.UpdateTriggerBindingBehavior = _updateTriggerBindingBehavior.UpdateTriggerBindingBehavior; }); define('aurelia-templating-resources', ['aurelia-templating-resources/aurelia-templating-resources'], function (main) { return main; }); define('aurelia-templating-router/route-loader',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-router', 'aurelia-path', 'aurelia-metadata'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaRouter, _aureliaPath, _aureliaMetadata) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var TemplatingRouteLoader = (function (_RouteLoader) { _inherits(TemplatingRouteLoader, _RouteLoader); function TemplatingRouteLoader(compositionEngine) { _classCallCheck(this, _TemplatingRouteLoader); _RouteLoader.call(this); this.compositionEngine = compositionEngine; } TemplatingRouteLoader.prototype.loadRoute = function loadRoute(router, config) { var childContainer = router.container.createChild(); var instruction = { viewModel: _aureliaPath.relativeToFile(config.moduleId, _aureliaMetadata.Origin.get(router.container.viewModel.constructor).moduleId), childContainer: childContainer, view: config.view || config.viewStrategy, router: router }; childContainer.getChildRouter = function () { var childRouter = undefined; childContainer.registerHandler(_aureliaRouter.Router, function (c) { return childRouter || (childRouter = router.createChild(childContainer)); }); return childContainer.get(_aureliaRouter.Router); }; return this.compositionEngine.ensureViewModel(instruction); }; var _TemplatingRouteLoader = TemplatingRouteLoader; TemplatingRouteLoader = _aureliaDependencyInjection.inject(_aureliaTemplating.CompositionEngine)(TemplatingRouteLoader) || TemplatingRouteLoader; return TemplatingRouteLoader; })(_aureliaRouter.RouteLoader); exports.TemplatingRouteLoader = TemplatingRouteLoader; }); define('aurelia-templating-router/router-view',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-router', 'aurelia-metadata', 'aurelia-pal'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaRouter, _aureliaMetadata, _aureliaPal) { exports.__esModule = true; var _createDecoratedClass = (function () { function defineProperties(target, descriptors, initializers) { for (var i = 0; i < descriptors.length; i++) { var descriptor = descriptors[i]; var decorators = descriptor.decorators; var key = descriptor.key; delete descriptor.key; delete descriptor.decorators; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor || descriptor.initializer) descriptor.writable = true; if (decorators) { for (var f = 0; f < decorators.length; f++) { var decorator = decorators[f]; if (typeof decorator === 'function') { descriptor = decorator(target, key, descriptor) || descriptor; } else { throw new TypeError('The decorator for method ' + descriptor.key + ' is of the invalid type ' + typeof decorator); } } if (descriptor.initializer !== undefined) { initializers[key] = descriptor; continue; } } Object.defineProperty(target, key, descriptor); } } return function (Constructor, protoProps, staticProps, protoInitializers, staticInitializers) { if (protoProps) defineProperties(Constructor.prototype, protoProps, protoInitializers); if (staticProps) defineProperties(Constructor, staticProps, staticInitializers); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _defineDecoratedPropertyDescriptor(target, key, descriptors) { var _descriptor = descriptors[key]; if (!_descriptor) return; var descriptor = {}; for (var _key in _descriptor) descriptor[_key] = _descriptor[_key]; descriptor.value = descriptor.initializer ? descriptor.initializer.call(target) : undefined; Object.defineProperty(target, key, descriptor); } var swapStrategies = { 'default': 'before', before: function before(viewSlot, view, callback) { var promised = callback(); var promise = Promise.resolve(promised); if (view !== undefined) { promise.then(function () { return viewSlot.remove(view); }); } }, 'with': function _with(viewSlot, view, callback) { view && viewSlot.remove(view); callback(); }, after: function after(viewSlot, view, callback) { var promised = viewSlot.removeAll(true); Promise.resolve(promised).then(callback); } }; var RouterView = (function () { var _instanceInitializers = {}; _createDecoratedClass(RouterView, [{ key: 'swapOrder', decorators: [_aureliaTemplating.bindable], initializer: function initializer() { return swapStrategies[swapStrategies['default']]; }, enumerable: true }], null, _instanceInitializers); function RouterView(element, container, viewSlot, router, viewLocator) { _classCallCheck(this, _RouterView); _defineDecoratedPropertyDescriptor(this, 'swapOrder', _instanceInitializers); this.element = element; this.container = container; this.viewSlot = viewSlot; this.router = router; this.viewLocator = viewLocator; this.router.registerViewPort(this, this.element.getAttribute('name')); } RouterView.prototype.bind = function bind(bindingContext) { this.container.viewModel = bindingContext; }; RouterView.prototype.process = function process(viewPortInstruction, waitToSwap) { var _this = this; var component = viewPortInstruction.component; var childContainer = component.childContainer; var viewModel = component.viewModel; var viewModelResource = component.viewModelResource; var metadata = viewModelResource.metadata; var viewStrategy = this.viewLocator.getViewStrategy(component.view || viewModel); if (viewStrategy) { viewStrategy.makeRelativeTo(_aureliaMetadata.Origin.get(component.router.container.viewModel.constructor).moduleId); } return metadata.load(childContainer, viewModelResource.value, null, viewStrategy, true).then(function (viewFactory) { viewPortInstruction.controller = metadata.create(childContainer, _aureliaTemplating.BehaviorInstruction.dynamic(_this.element, viewModel, viewFactory)); if (waitToSwap) { return; } _this.swap(viewPortInstruction); }); }; RouterView.prototype.swap = function swap(viewPortInstruction) { var view = this.view; var viewSlot = this.viewSlot; var swapStrategy = this.swapOrder in swapStrategies ? swapStrategies[this.swapOrder] : swapStrategies[swapStrategies['default']]; if (swapStrategy) { swapStrategy(viewSlot, view, next); } this.view = viewPortInstruction.controller.view; function next() { viewPortInstruction.controller.automate(); viewSlot.add(viewPortInstruction.controller.view); } }; var _RouterView = RouterView; RouterView = _aureliaDependencyInjection.inject(_aureliaPal.DOM.Element, _aureliaDependencyInjection.Container, _aureliaTemplating.ViewSlot, _aureliaRouter.Router, _aureliaTemplating.ViewLocator)(RouterView) || RouterView; RouterView = _aureliaTemplating.noView(RouterView) || RouterView; RouterView = _aureliaTemplating.customElement('router-view')(RouterView) || RouterView; return RouterView; })(); exports.RouterView = RouterView; }); define('aurelia-templating-router/route-href',['exports', 'aurelia-templating', 'aurelia-dependency-injection', 'aurelia-router', 'aurelia-pal', 'aurelia-logging'], function (exports, _aureliaTemplating, _aureliaDependencyInjection, _aureliaRouter, _aureliaPal, _aureliaLogging) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var logger = _aureliaLogging.getLogger('route-href'); var RouteHref = (function () { function RouteHref(router, element) { _classCallCheck(this, _RouteHref); this.router = router; this.element = element; } RouteHref.prototype.bind = function bind() { this.isActive = true; this.processChange(); }; RouteHref.prototype.unbind = function unbind() { this.isActive = false; }; RouteHref.prototype.attributeChanged = function attributeChanged(value, previous) { if (previous) { this.element.removeAttribute(previous); } this.processChange(); }; RouteHref.prototype.processChange = function processChange() { var _this = this; return this.router.ensureConfigured().then(function () { if (!_this.isActive) { return; } var href = _this.router.generate(_this.route, _this.params); _this.element.setAttribute(_this.attribute, href); })['catch'](function (reason) { logger.error(reason); }); }; var _RouteHref = RouteHref; RouteHref = _aureliaDependencyInjection.inject(_aureliaRouter.Router, _aureliaPal.DOM.Element)(RouteHref) || RouteHref; RouteHref = _aureliaTemplating.bindable({ name: 'attribute', defaultValue: 'href' })(RouteHref) || RouteHref; RouteHref = _aureliaTemplating.bindable({ name: 'params', changeHandler: 'processChange' })(RouteHref) || RouteHref; RouteHref = _aureliaTemplating.bindable({ name: 'route', changeHandler: 'processChange' })(RouteHref) || RouteHref; RouteHref = _aureliaTemplating.customAttribute('route-href')(RouteHref) || RouteHref; return RouteHref; })(); exports.RouteHref = RouteHref; }); define('aurelia-templating-router/aurelia-templating-router',['exports', 'aurelia-router', './route-loader', './router-view', './route-href'], function (exports, _aureliaRouter, _routeLoader, _routerView, _routeHref) { exports.__esModule = true; function configure(config) { config.singleton(_aureliaRouter.RouteLoader, _routeLoader.TemplatingRouteLoader).singleton(_aureliaRouter.Router, _aureliaRouter.AppRouter).globalResources('./router-view', './route-href'); } exports.TemplatingRouteLoader = _routeLoader.TemplatingRouteLoader; exports.RouterView = _routerView.RouterView; exports.RouteHref = _routeHref.RouteHref; exports.configure = configure; }); define('aurelia-templating-router', ['aurelia-templating-router/aurelia-templating-router'], function (main) { return main; }); define('aurelia-http-client',['exports', 'core-js', 'aurelia-path', 'aurelia-pal'], function (exports, _coreJs, _aureliaPath, _aureliaPal) { exports.__esModule = true; 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; }; })(); exports.timeoutTransformer = timeoutTransformer; exports.callbackParameterNameTransformer = callbackParameterNameTransformer; exports.credentialsTransformer = credentialsTransformer; exports.progressTransformer = progressTransformer; exports.responseTypeTransformer = responseTypeTransformer; exports.headerTransformer = headerTransformer; exports.contentTransformer = contentTransformer; exports.createJSONPRequestMessageProcessor = createJSONPRequestMessageProcessor; exports.createHttpRequestMessageProcessor = createHttpRequestMessageProcessor; 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Headers = (function () { function Headers() { var headers = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; _classCallCheck(this, Headers); this.headers = headers; } Headers.prototype.add = function add(key, value) { this.headers[key] = value; }; Headers.prototype.get = function get(key) { return this.headers[key]; }; Headers.prototype.clear = function clear() { this.headers = {}; }; Headers.prototype.has = function has(header) { var lowered = header.toLowerCase(); var headers = this.headers; for (var _key in headers) { if (_key.toLowerCase() === lowered) { return true; } } return false; }; Headers.prototype.configureXHR = function configureXHR(xhr) { var headers = this.headers; for (var _key2 in headers) { xhr.setRequestHeader(_key2, headers[_key2]); } }; Headers.parse = function parse(headerStr) { var headers = new Headers(); if (!headerStr) { return headers; } var headerPairs = headerStr.split('\r\n'); for (var i = 0; i < headerPairs.length; i++) { var headerPair = headerPairs[i]; var index = headerPair.indexOf(': '); if (index > 0) { var _key3 = headerPair.substring(0, index); var val = headerPair.substring(index + 2); headers.add(_key3, val); } } return headers; }; return Headers; })(); exports.Headers = Headers; var RequestMessage = (function () { function RequestMessage(method, url, content, headers) { _classCallCheck(this, RequestMessage); this.method = method; this.url = url; this.content = content; this.headers = headers || new Headers(); this.baseUrl = ''; } RequestMessage.prototype.buildFullUrl = function buildFullUrl() { var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; var url = absoluteUrl.test(this.url) ? this.url : _aureliaPath.join(this.baseUrl, this.url); if (this.params) { var qs = _aureliaPath.buildQueryString(this.params); url = qs ? url + '?' + qs : url; } return url; }; return RequestMessage; })(); exports.RequestMessage = RequestMessage; var HttpResponseMessage = (function () { function HttpResponseMessage(requestMessage, xhr, responseType, reviver) { _classCallCheck(this, HttpResponseMessage); this.requestMessage = requestMessage; this.statusCode = xhr.status; this.response = xhr.response || xhr.responseText; this.isSuccess = xhr.status >= 200 && xhr.status < 400; this.statusText = xhr.statusText; this.reviver = reviver; this.mimeType = null; if (xhr.getAllResponseHeaders) { try { this.headers = Headers.parse(xhr.getAllResponseHeaders()); } catch (err) { if (xhr.requestHeaders) this.headers = { headers: xhr.requestHeaders }; } } else { this.headers = new Headers(); } var contentType = undefined; if (this.headers && this.headers.headers) contentType = this.headers.headers['Content-Type']; if (contentType) { this.mimeType = responseType = contentType.split(';')[0].trim(); if (mimeTypes.hasOwnProperty(this.mimeType)) responseType = mimeTypes[this.mimeType]; } this.responseType = responseType; } _createClass(HttpResponseMessage, [{ key: 'content', get: function get() { try { if (this._content !== undefined) { return this._content; } if (this.response === undefined || this.response === null) { this._content = this.response; return this._content; } if (this.responseType === 'json') { this._content = JSON.parse(this.response, this.reviver); return this._content; } if (this.reviver) { this._content = this.reviver(this.response); return this._content; } this._content = this.response; return this._content; } catch (e) { if (this.isSuccess) { throw e; } this._content = null; return this._content; } } }]); return HttpResponseMessage; })(); exports.HttpResponseMessage = HttpResponseMessage; var mimeTypes = { 'text/html': 'html', 'text/javascript': 'js', 'application/javascript': 'js', 'text/json': 'json', 'application/json': 'json', 'application/rss+xml': 'rss', 'application/atom+xml': 'atom', 'application/xhtml+xml': 'xhtml', 'text/markdown': 'md', 'text/xml': 'xml', 'text/mathml': 'mml', 'application/xml': 'xml', 'text/yml': 'yml', 'text/csv': 'csv', 'text/css': 'css', 'text/less': 'less', 'text/stylus': 'styl', 'text/scss': 'scss', 'text/sass': 'sass', 'text/plain': 'txt' }; exports.mimeTypes = mimeTypes; function applyXhrTransformers(xhrTransformers, client, processor, message, xhr) { var i = undefined; var ii = undefined; for (i = 0, ii = xhrTransformers.length; i < ii; ++i) { xhrTransformers[i](client, processor, message, xhr); } } var RequestMessageProcessor = (function () { function RequestMessageProcessor(xhrType, xhrTransformers) { _classCallCheck(this, RequestMessageProcessor); this.XHRType = xhrType; this.xhrTransformers = xhrTransformers; this.isAborted = false; } RequestMessageProcessor.prototype.abort = function abort() { if (this.xhr && this.xhr.readyState !== _aureliaPal.PLATFORM.XMLHttpRequest.UNSENT) { this.xhr.abort(); } this.isAborted = true; }; RequestMessageProcessor.prototype.process = function process(client, requestMessage) { var _this = this; var promise = new Promise(function (resolve, reject) { var xhr = _this.xhr = new _this.XHRType(); xhr.onload = function (e) { var response = new HttpResponseMessage(requestMessage, xhr, requestMessage.responseType, requestMessage.reviver); if (response.isSuccess) { resolve(response); } else { reject(response); } }; xhr.ontimeout = function (e) { reject(new HttpResponseMessage(requestMessage, { response: e, status: xhr.status, statusText: xhr.statusText }, 'timeout')); }; xhr.onerror = function (e) { reject(new HttpResponseMessage(requestMessage, { response: e, status: xhr.status, statusText: xhr.statusText }, 'error')); }; xhr.onabort = function (e) { reject(new HttpResponseMessage(requestMessage, { response: e, status: xhr.status, statusText: xhr.statusText }, 'abort')); }; }); return Promise.resolve(requestMessage).then(function (message) { var processRequest = function processRequest() { if (_this.isAborted) { _this.xhr.abort(); } else { _this.xhr.open(message.method, message.buildFullUrl(), true, message.user, message.password); applyXhrTransformers(_this.xhrTransformers, client, _this, message, _this.xhr); _this.xhr.send(message.content); } return promise; }; var chain = [[processRequest, undefined]]; var interceptors = message.interceptors || []; interceptors.forEach(function (interceptor) { if (interceptor.request || interceptor.requestError) { chain.unshift([interceptor.request ? interceptor.request.bind(interceptor) : undefined, interceptor.requestError ? interceptor.requestError.bind(interceptor) : undefined]); } if (interceptor.response || interceptor.responseError) { chain.push([interceptor.response ? interceptor.response.bind(interceptor) : undefined, interceptor.responseError ? interceptor.responseError.bind(interceptor) : undefined]); } }); var interceptorsPromise = Promise.resolve(message); while (chain.length) { var _interceptorsPromise; interceptorsPromise = (_interceptorsPromise = interceptorsPromise).then.apply(_interceptorsPromise, chain.shift()); } return interceptorsPromise; }); }; return RequestMessageProcessor; })(); exports.RequestMessageProcessor = RequestMessageProcessor; function timeoutTransformer(client, processor, message, xhr) { if (message.timeout !== undefined) { xhr.timeout = message.timeout; } } function callbackParameterNameTransformer(client, processor, message, xhr) { if (message.callbackParameterName !== undefined) { xhr.callbackParameterName = message.callbackParameterName; } } function credentialsTransformer(client, processor, message, xhr) { if (message.withCredentials !== undefined) { xhr.withCredentials = message.withCredentials; } } function progressTransformer(client, processor, message, xhr) { if (message.progressCallback) { xhr.upload.onprogress = message.progressCallback; } } function responseTypeTransformer(client, processor, message, xhr) { var responseType = message.responseType; if (responseType === 'json') { responseType = 'text'; } xhr.responseType = responseType; } function headerTransformer(client, processor, message, xhr) { message.headers.configureXHR(xhr); } function contentTransformer(client, processor, message, xhr) { if (message.skipContentProcessing) { return; } if (_aureliaPal.PLATFORM.global.FormData && message.content instanceof FormData) { return; } if (_aureliaPal.PLATFORM.global.Blob && message.content instanceof Blob) { return; } if (_aureliaPal.PLATFORM.global.ArrayBufferView && message.content instanceof ArrayBufferView) { return; } if (message.content instanceof Document) { return; } if (typeof message.content === 'string') { return; } if (message.content === null || message.content === undefined) { return; } message.content = JSON.stringify(message.content, message.replacer); if (!message.headers.has('Content-Type')) { message.headers.add('Content-Type', 'application/json'); } } var JSONPRequestMessage = (function (_RequestMessage) { _inherits(JSONPRequestMessage, _RequestMessage); function JSONPRequestMessage(url, callbackParameterName) { _classCallCheck(this, JSONPRequestMessage); _RequestMessage.call(this, 'JSONP', url); this.responseType = 'jsonp'; this.callbackParameterName = callbackParameterName; } return JSONPRequestMessage; })(RequestMessage); exports.JSONPRequestMessage = JSONPRequestMessage; var JSONPXHR = (function () { function JSONPXHR() { _classCallCheck(this, JSONPXHR); } JSONPXHR.prototype.open = function open(method, url) { this.method = method; this.url = url; this.callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random()); }; JSONPXHR.prototype.send = function send() { var _this2 = this; var url = this.url + (this.url.indexOf('?') >= 0 ? '&' : '?') + encodeURIComponent(this.callbackParameterName) + '=' + this.callbackName; var script = _aureliaPal.DOM.createElement('script'); script.src = url; script.onerror = function (e) { cleanUp(); _this2.status = 0; _this2.onerror(new Error('error')); }; var cleanUp = function cleanUp() { delete _aureliaPal.PLATFORM.global[_this2.callbackName]; _aureliaPal.DOM.removeNode(script); }; _aureliaPal.PLATFORM.global[this.callbackName] = function (data) { cleanUp(); if (_this2.status === undefined) { _this2.status = 200; _this2.statusText = 'OK'; _this2.response = data; _this2.onload(_this2); } }; _aureliaPal.DOM.appendNode(script); if (this.timeout !== undefined) { setTimeout(function () { if (_this2.status === undefined) { _this2.status = 0; _this2.ontimeout(new Error('timeout')); } }, this.timeout); } }; JSONPXHR.prototype.abort = function abort() { if (this.status === undefined) { this.status = 0; this.onabort(new Error('abort')); } }; JSONPXHR.prototype.setRequestHeader = function setRequestHeader() {}; return JSONPXHR; })(); function createJSONPRequestMessageProcessor() { return new RequestMessageProcessor(JSONPXHR, [timeoutTransformer, callbackParameterNameTransformer]); } var HttpRequestMessage = (function (_RequestMessage2) { _inherits(HttpRequestMessage, _RequestMessage2); function HttpRequestMessage(method, url, content, headers) { _classCallCheck(this, HttpRequestMessage); _RequestMessage2.call(this, method, url, content, headers); this.responseType = 'json'; } return HttpRequestMessage; })(RequestMessage); exports.HttpRequestMessage = HttpRequestMessage; function createHttpRequestMessageProcessor() { return new RequestMessageProcessor(_aureliaPal.PLATFORM.XMLHttpRequest, [timeoutTransformer, credentialsTransformer, progressTransformer, responseTypeTransformer, contentTransformer, headerTransformer]); } var RequestBuilder = (function () { function RequestBuilder(client) { _classCallCheck(this, RequestBuilder); this.client = client; this.transformers = client.requestTransformers.slice(0); this.useJsonp = false; } RequestBuilder.prototype.asDelete = function asDelete() { return this._addTransformer(function (client, processor, message) { message.method = 'DELETE'; }); }; RequestBuilder.prototype.asGet = function asGet() { return this._addTransformer(function (client, processor, message) { message.method = 'GET'; }); }; RequestBuilder.prototype.asHead = function asHead() { return this._addTransformer(function (client, processor, message) { message.method = 'HEAD'; }); }; RequestBuilder.prototype.asOptions = function asOptions() { return this._addTransformer(function (client, processor, message) { message.method = 'OPTIONS'; }); }; RequestBuilder.prototype.asPatch = function asPatch() { return this._addTransformer(function (client, processor, message) { message.method = 'PATCH'; }); }; RequestBuilder.prototype.asPost = function asPost() { return this._addTransformer(function (client, processor, message) { message.method = 'POST'; }); }; RequestBuilder.prototype.asPut = function asPut() { return this._addTransformer(function (client, processor, message) { message.method = 'PUT'; }); }; RequestBuilder.prototype.asJsonp = function asJsonp(callbackParameterName) { this.useJsonp = true; return this._addTransformer(function (client, processor, message) { message.callbackParameterName = callbackParameterName; }); }; RequestBuilder.prototype.withUrl = function withUrl(url) { return this._addTransformer(function (client, processor, message) { message.url = url; }); }; RequestBuilder.prototype.withContent = function withContent(content) { return this._addTransformer(function (client, processor, message) { message.content = content; }); }; RequestBuilder.prototype.withBaseUrl = function withBaseUrl(baseUrl) { return this._addTransformer(function (client, processor, message) { message.baseUrl = baseUrl; }); }; RequestBuilder.prototype.withParams = function withParams(params) { return this._addTransformer(function (client, processor, message) { message.params = params; }); }; RequestBuilder.prototype.withResponseType = function withResponseType(responseType) { return this._addTransformer(function (client, processor, message) { message.responseType = responseType; }); }; RequestBuilder.prototype.withTimeout = function withTimeout(timeout) { return this._addTransformer(function (client, processor, message) { message.timeout = timeout; }); }; RequestBuilder.prototype.withHeader = function withHeader(key, value) { return this._addTransformer(function (client, processor, message) { message.headers.add(key, value); }); }; RequestBuilder.prototype.withCredentials = function withCredentials(value) { return this._addTransformer(function (client, processor, message) { message.withCredentials = value; }); }; RequestBuilder.prototype.withLogin = function withLogin(user, password) { return this._addTransformer(function (client, processor, message) { message.user = user;message.password = password; }); }; RequestBuilder.prototype.withReviver = function withReviver(reviver) { return this._addTransformer(function (client, processor, message) { message.reviver = reviver; }); }; RequestBuilder.prototype.withReplacer = function withReplacer(replacer) { return this._addTransformer(function (client, processor, message) { message.replacer = replacer; }); }; RequestBuilder.prototype.withProgressCallback = function withProgressCallback(progressCallback) { return this._addTransformer(function (client, processor, message) { message.progressCallback = progressCallback; }); }; RequestBuilder.prototype.withCallbackParameterName = function withCallbackParameterName(callbackParameterName) { return this._addTransformer(function (client, processor, message) { message.callbackParameterName = callbackParameterName; }); }; RequestBuilder.prototype.withInterceptor = function withInterceptor(interceptor) { return this._addTransformer(function (client, processor, message) { message.interceptors = message.interceptors || []; message.interceptors.unshift(interceptor); }); }; RequestBuilder.prototype.skipContentProcessing = function skipContentProcessing() { return this._addTransformer(function (client, processor, message) { message.skipContentProcessing = true; }); }; RequestBuilder.prototype._addTransformer = function _addTransformer(fn) { this.transformers.push(fn); return this; }; RequestBuilder.addHelper = function addHelper(name, fn) { RequestBuilder.prototype[name] = function () { return this._addTransformer(fn.apply(this, arguments)); }; }; RequestBuilder.prototype.send = function send() { var message = this.useJsonp ? new JSONPRequestMessage() : new HttpRequestMessage(); return this.client.send(message, this.transformers); }; return RequestBuilder; })(); exports.RequestBuilder = RequestBuilder; function trackRequestStart(client, processor) { client.pendingRequests.push(processor); client.isRequesting = true; } function trackRequestEnd(client, processor) { var index = client.pendingRequests.indexOf(processor); client.pendingRequests.splice(index, 1); client.isRequesting = client.pendingRequests.length > 0; if (!client.isRequesting) { (function () { var evt = _aureliaPal.DOM.createCustomEvent('aurelia-http-client-requests-drained', { bubbles: true, cancelable: true }); setTimeout(function () { return _aureliaPal.DOM.dispatchEvent(evt); }, 1); })(); } } var HttpClient = (function () { function HttpClient() { _classCallCheck(this, HttpClient); this.requestTransformers = []; this.requestProcessorFactories = new Map(); this.requestProcessorFactories.set(HttpRequestMessage, createHttpRequestMessageProcessor); this.requestProcessorFactories.set(JSONPRequestMessage, createJSONPRequestMessageProcessor); this.pendingRequests = []; this.isRequesting = false; } HttpClient.prototype.configure = function configure(fn) { var builder = new RequestBuilder(this); fn(builder); this.requestTransformers = builder.transformers; return this; }; HttpClient.prototype.createRequest = function createRequest(url) { var builder = new RequestBuilder(this); if (url) { builder.withUrl(url); } return builder; }; HttpClient.prototype.send = function send(requestMessage, transformers) { var _this3 = this; var createProcessor = this.requestProcessorFactories.get(requestMessage.constructor); var processor = undefined; var promise = undefined; var i = undefined; var ii = undefined; if (!createProcessor) { throw new Error('No request message processor factory for ' + requestMessage.constructor + '.'); } processor = createProcessor(); trackRequestStart(this, processor); transformers = transformers || this.requestTransformers; promise = Promise.resolve(requestMessage).then(function (message) { for (i = 0, ii = transformers.length; i < ii; ++i) { transformers[i](_this3, processor, message); } return processor.process(_this3, message).then(function (response) { trackRequestEnd(_this3, processor); return response; })['catch'](function (response) { trackRequestEnd(_this3, processor); throw response; }); }); promise.abort = promise.cancel = function () { processor.abort(); }; return promise; }; HttpClient.prototype['delete'] = function _delete(url) { return this.createRequest(url).asDelete().send(); }; HttpClient.prototype.get = function get(url) { return this.createRequest(url).asGet().send(); }; HttpClient.prototype.head = function head(url) { return this.createRequest(url).asHead().send(); }; HttpClient.prototype.jsonp = function jsonp(url) { var callbackParameterName = arguments.length <= 1 || arguments[1] === undefined ? 'jsoncallback' : arguments[1]; return this.createRequest(url).asJsonp(callbackParameterName).send(); }; HttpClient.prototype.options = function options(url) { return this.createRequest(url).asOptions().send(); }; HttpClient.prototype.put = function put(url, content) { return this.createRequest(url).asPut().withContent(content).send(); }; HttpClient.prototype.patch = function patch(url, content) { return this.createRequest(url).asPatch().withContent(content).send(); }; HttpClient.prototype.post = function post(url, content) { return this.createRequest(url).asPost().withContent(content).send(); }; return HttpClient; })(); exports.HttpClient = HttpClient; }); define('aurelia-fetch-client',['exports', 'core-js'], function (exports, _coreJs) { exports.__esModule = true; exports.json = json; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function json(body) { return new Blob([JSON.stringify(body)], { type: 'application/json' }); } var HttpClientConfiguration = (function () { function HttpClientConfiguration() { _classCallCheck(this, HttpClientConfiguration); this.baseUrl = ''; this.defaults = {}; this.interceptors = []; } HttpClientConfiguration.prototype.withBaseUrl = function withBaseUrl(baseUrl) { this.baseUrl = baseUrl; return this; }; HttpClientConfiguration.prototype.withDefaults = function withDefaults(defaults) { this.defaults = defaults; return this; }; HttpClientConfiguration.prototype.withInterceptor = function withInterceptor(interceptor) { this.interceptors.push(interceptor); return this; }; HttpClientConfiguration.prototype.useStandardConfiguration = function useStandardConfiguration() { var standardConfig = { credentials: 'same-origin' }; Object.assign(this.defaults, standardConfig, this.defaults); return this.rejectErrorResponses(); }; HttpClientConfiguration.prototype.rejectErrorResponses = function rejectErrorResponses() { return this.withInterceptor({ response: rejectOnError }); }; return HttpClientConfiguration; })(); exports.HttpClientConfiguration = HttpClientConfiguration; function rejectOnError(response) { if (!response.ok) { throw response; } return response; } var HttpClient = (function () { function HttpClient() { _classCallCheck(this, HttpClient); this.activeRequestCount = 0; this.isRequesting = false; this.isConfigured = false; this.baseUrl = ''; this.defaults = null; this.interceptors = []; if (typeof fetch === 'undefined') { throw new Error('HttpClient requires a Fetch API implementation, but the current environment doesn\'t support it. You may need to load a polyfill such as https://github.com/github/fetch.'); } } HttpClient.prototype.configure = function configure(config) { var _interceptors; var normalizedConfig = undefined; if (typeof config === 'object') { normalizedConfig = { defaults: config }; } else if (typeof config === 'function') { normalizedConfig = new HttpClientConfiguration(); var c = config(normalizedConfig); if (typeof c === HttpClientConfiguration) { normalizedConfig = c; } } else { throw new Error('invalid config'); } var defaults = normalizedConfig.defaults; if (defaults && defaults.headers instanceof Headers) { throw new Error('Default headers must be a plain object.'); } this.baseUrl = normalizedConfig.baseUrl; this.defaults = defaults; (_interceptors = this.interceptors).push.apply(_interceptors, normalizedConfig.interceptors || []); this.isConfigured = true; return this; }; HttpClient.prototype.fetch = (function (_fetch) { function fetch(_x, _x2) { return _fetch.apply(this, arguments); } fetch.toString = function () { return _fetch.toString(); }; return fetch; })(function (input, init) { var _this = this; trackRequestStart.call(this); var request = Promise.resolve().then(function () { return buildRequest.call(_this, input, init, _this.defaults); }); var promise = processRequest(request, this.interceptors).then(function (result) { var response = null; if (result instanceof Response) { response = result; } else if (result instanceof Request) { response = fetch(result); } else { throw new Error('An invalid result was returned by the interceptor chain. Expected a Request or Response instance, but got [' + result + ']'); } return processResponse(response, _this.interceptors); }); return trackRequestEndWith.call(this, promise); }); return HttpClient; })(); exports.HttpClient = HttpClient; function trackRequestStart() { this.isRequesting = !! ++this.activeRequestCount; } function trackRequestEnd() { this.isRequesting = !! --this.activeRequestCount; } function trackRequestEndWith(promise) { var handle = trackRequestEnd.bind(this); promise.then(handle, handle); return promise; } function parseHeaderValues(headers) { var parsedHeaders = {}; for (var _name in headers || {}) { if (headers.hasOwnProperty(_name)) { parsedHeaders[_name] = typeof headers[_name] === 'function' ? headers[_name]() : headers[_name]; } } return parsedHeaders; } function buildRequest(input) { var init = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var defaults = this.defaults || {}; var source = undefined; var url = undefined; var body = undefined; if (input instanceof Request) { if (!this.isConfigured) { return input; } source = input; url = input.url; body = input.blob(); } else { source = init; url = input; body = init.body; } var parsedDefaultHeaders = parseHeaderValues(defaults.headers); var requestInit = Object.assign({}, defaults, { headers: {} }, source, { body: body }); var request = new Request((this.baseUrl || '') + url, requestInit); setDefaultHeaders(request.headers, parsedDefaultHeaders); return request; } function setDefaultHeaders(headers, defaultHeaders) { for (var _name2 in defaultHeaders || {}) { if (defaultHeaders.hasOwnProperty(_name2) && !headers.has(_name2)) { headers.set(_name2, defaultHeaders[_name2]); } } } function processRequest(request, interceptors) { return applyInterceptors(request, interceptors, 'request', 'requestError'); } function processResponse(response, interceptors) { return applyInterceptors(response, interceptors, 'response', 'responseError'); } function applyInterceptors(input, interceptors, successName, errorName) { return (interceptors || []).reduce(function (chain, interceptor) { var successHandler = interceptor[successName]; var errorHandler = interceptor[errorName]; return chain.then(successHandler && successHandler.bind(interceptor), errorHandler && errorHandler.bind(interceptor)); }, Promise.resolve(input)); } }); define('aurelia-pal-browser',['exports', 'aurelia-pal'], function (exports, _aureliaPal) { exports.__esModule = true; exports._ensureFunctionName = _ensureFunctionName; exports._ensureClassList = _ensureClassList; exports._ensureCustomEvent = _ensureCustomEvent; exports._ensureElementMatches = _ensureElementMatches; exports._ensureHTMLTemplateElement = _ensureHTMLTemplateElement; exports.initialize = initialize; function _ensureFunctionName() { function test() {} if (!test.name) { Object.defineProperty(Function.prototype, 'name', { get: function get() { var name = this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1]; Object.defineProperty(this, 'name', { value: name }); return name; } }); } } function _ensureClassList() { if (!('classList' in document.createElement('_')) || document.createElementNS && !('classList' in document.createElementNS('http://www.w3.org/2000/svg', 'g'))) { (function () { var protoProp = 'prototype'; var strTrim = String.prototype.trim; var arrIndexOf = Array.prototype.indexOf; var emptyArray = []; var DOMEx = function DOMEx(type, message) { this.name = type; this.code = DOMException[type]; this.message = message; }; var checkTokenAndGetIndex = function checkTokenAndGetIndex(classList, token) { if (token === '') { throw new DOMEx('SYNTAX_ERR', 'An invalid or illegal string was specified'); } if (/\s/.test(token)) { throw new DOMEx('INVALID_CHARACTER_ERR', 'String contains an invalid character'); } return arrIndexOf.call(classList, token); }; var ClassList = function ClassList(elem) { var trimmedClasses = strTrim.call(elem.getAttribute('class') || ''); var classes = trimmedClasses ? trimmedClasses.split(/\s+/) : emptyArray; for (var i = 0, ii = classes.length; i < ii; ++i) { this.push(classes[i]); } this._updateClassName = function () { elem.setAttribute('class', this.toString()); }; }; var classListProto = ClassList[protoProp] = []; DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { token += ''; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function () { var tokens = arguments; var i = 0; var ii = tokens.length; var token = undefined; var updated = false; do { token = tokens[i] + ''; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); updated = true; } } while (++i < ii); if (updated) { this._updateClassName(); } }; classListProto.remove = function () { var tokens = arguments; var i = 0; var ii = tokens.length; var token = undefined; var updated = false; var index = undefined; do { token = tokens[i] + ''; index = checkTokenAndGetIndex(this, token); while (index !== -1) { this.splice(index, 1); updated = true; index = checkTokenAndGetIndex(this, token); } } while (++i < ii); if (updated) { this._updateClassName(); } }; classListProto.toggle = function (token, force) { token += ''; var result = this.contains(token); var method = result ? force !== true && 'remove' : force !== false && 'add'; if (method) { this[method](token); } if (force === true || force === false) { return force; } return !result; }; classListProto.toString = function () { return this.join(' '); }; Object.defineProperty(Element.prototype, 'classList', { get: function get() { return new ClassList(this); }, enumerable: true, configurable: true }); })(); } else { var testElement = document.createElement('_'); testElement.classList.add('c1', 'c2'); if (!testElement.classList.contains('c2')) { var createMethod = function createMethod(method) { var original = DOMTokenList.prototype[method]; DOMTokenList.prototype[method] = function (token) { for (var i = 0, ii = arguments.length; i < ii; ++i) { token = arguments[i]; original.call(this, token); } }; }; createMethod('add'); createMethod('remove'); } testElement.classList.toggle('c3', false); if (testElement.classList.contains('c3')) { (function () { var _toggle = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function (token, force) { if (1 in arguments && !this.contains(token) === !force) { return force; } return _toggle.call(this, token); }; })(); } testElement = null; } } function _ensureCustomEvent() { if (!window.CustomEvent || typeof window.CustomEvent !== 'function') { var _CustomEvent = function _CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; }; _CustomEvent.prototype = window.Event.prototype; window.CustomEvent = _CustomEvent; } } function _ensureElementMatches() { if (Element && !Element.prototype.matches) { var proto = Element.prototype; proto.matches = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; } } var _FEATURE = {}; exports._FEATURE = _FEATURE; _FEATURE.shadowDOM = (function () { return !!HTMLElement.prototype.createShadowRoot; })(); _FEATURE.scopedCSS = (function () { return 'scoped' in document.createElement('style'); })(); _FEATURE.htmlTemplateElement = (function () { return 'content' in document.createElement('template'); })(); _FEATURE.objectObserve = (function detectObjectObserve() { if (typeof Object.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; Object.observe(test, callback); test.id = 1; test.id = 2; delete test.id; Object.deliverChangeRecords(callback); if (records.length !== 3) { return false; } if (records[0].type !== 'add' || records[1].type !== 'update' || records[2].type !== 'delete') { return false; } Object.unobserve(test, callback); return true; })(); _FEATURE.arrayObserve = (function detectArrayObserve() { if (typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var arr = []; Array.observe(arr, callback); arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 2) { return false; } if (records[0].type !== 'splice' || records[1].type !== 'splice') { return false; } Array.unobserve(arr, callback); return true; })(); function _ensureHTMLTemplateElement() { function isSVGTemplate(el) { return el.tagName === 'template' && el.namespaceURI === 'http://www.w3.org/2000/svg'; } function fixSVGTemplateElement(el) { var template = el.ownerDocument.createElement('template'); var attrs = el.attributes; var length = attrs.length; var attr = undefined; el.parentNode.insertBefore(template, el); while (length-- > 0) { attr = attrs[length]; template.setAttribute(attr.name, attr.value); el.removeAttribute(attr.name); } el.parentNode.removeChild(el); return fixHTMLTemplateElement(template); } function fixHTMLTemplateElement(template) { var content = template.content = document.createDocumentFragment(); var child = undefined; while (child = template.firstChild) { content.appendChild(child); } return template; } function fixHTMLTemplateElementRoot(template) { var content = fixHTMLTemplateElement(template).content; var childTemplates = content.querySelectorAll('template'); for (var i = 0, ii = childTemplates.length; i < ii; ++i) { var child = childTemplates[i]; if (isSVGTemplate(child)) { fixSVGTemplateElement(child); } else { fixHTMLTemplateElement(child); } } return template; } if (_FEATURE.htmlTemplateElement) { _FEATURE.ensureHTMLTemplateElement = function (template) { return template; }; } else { _FEATURE.ensureHTMLTemplateElement = fixHTMLTemplateElementRoot; } } var shadowPoly = window.ShadowDOMPolyfill || null; var _DOM = { Element: Element, SVGElement: SVGElement, boundary: 'aurelia-dom-boundary', addEventListener: function addEventListener(eventName, callback, capture) { document.addEventListener(eventName, callback, capture); }, removeEventListener: function removeEventListener(eventName, callback, capture) { document.removeEventListener(eventName, callback, capture); }, adoptNode: function adoptNode(node) { return document.adoptNode(node, true); }, createElement: function createElement(tagName) { return document.createElement(tagName); }, createTextNode: function createTextNode(text) { return document.createTextNode(text); }, createComment: function createComment(text) { return document.createComment(text); }, createDocumentFragment: function createDocumentFragment() { return document.createDocumentFragment(); }, createMutationObserver: function createMutationObserver(callback) { return new (window.MutationObserver || window.WebKitMutationObserver)(callback); }, createCustomEvent: function createCustomEvent(eventType, options) { return new window.CustomEvent(eventType, options); }, dispatchEvent: function dispatchEvent(evt) { document.dispatchEvent(evt); }, getComputedStyle: function getComputedStyle(element) { return window.getComputedStyle(element); }, getElementById: function getElementById(id) { return document.getElementById(id); }, querySelectorAll: function querySelectorAll(query) { return document.querySelectorAll(query); }, nextElementSibling: function nextElementSibling(element) { if (element.nextElementSibling) { return element.nextElementSibling; } do { element = element.nextSibling; } while (element && element.nodeType !== 1); return element; }, createTemplateFromMarkup: function createTemplateFromMarkup(markup) { var parser = document.createElement('div'); parser.innerHTML = markup; var temp = parser.firstElementChild; if (!temp || temp.nodeName !== 'TEMPLATE') { throw new Error('Template markup must be wrapped in a <template> element e.g. <template> <!-- markup here --> </template>'); } return _FEATURE.ensureHTMLTemplateElement(temp); }, appendNode: function appendNode(newNode, parentNode) { (parentNode || document.body).appendChild(newNode); }, replaceNode: function replaceNode(newNode, node, parentNode) { if (node.parentNode) { node.parentNode.replaceChild(newNode, node); } else if (shadowPoly !== null) { shadowPoly.unwrap(parentNode).replaceChild(shadowPoly.unwrap(newNode), shadowPoly.unwrap(node)); } else { parentNode.replaceChild(newNode, node); } }, removeNode: function removeNode(node, parentNode) { if (node.parentNode) { node.parentNode.removeChild(node); } else if (shadowPoly !== null) { shadowPoly.unwrap(parentNode).removeChild(shadowPoly.unwrap(node)); } else { parentNode.removeChild(node); } }, injectStyles: function injectStyles(styles, destination, prepend) { var node = document.createElement('style'); node.innerHTML = styles; node.type = 'text/css'; destination = destination || document.head; if (prepend && destination.childNodes.length > 0) { destination.insertBefore(node, destination.childNodes[0]); } else { destination.appendChild(node); } return node; } }; exports._DOM = _DOM; var _PLATFORM = { location: window.location, history: window.history, addEventListener: function addEventListener(eventName, callback, capture) { this.global.addEventListener(eventName, callback, capture); }, removeEventListener: function removeEventListener(eventName, callback, capture) { this.global.removeEventListener(eventName, callback, capture); } }; exports._PLATFORM = _PLATFORM; var isInitialized = false; function initialize() { if (isInitialized) { return; } isInitialized = true; _ensureCustomEvent(); _ensureFunctionName(); _ensureHTMLTemplateElement(); _ensureElementMatches(); _ensureClassList(); _aureliaPal.initializePAL(function (platform, feature, dom) { Object.assign(platform, _PLATFORM); Object.assign(feature, _FEATURE); Object.assign(dom, _DOM); Object.defineProperty(dom, 'title', { get: function get() { return document.title; }, set: function set(value) { document.title = value; } }); Object.defineProperty(dom, 'activeElement', { get: function get() { return document.activeElement; } }); Object.defineProperty(platform, 'XMLHttpRequest', { get: function get() { return platform.global.XMLHttpRequest; } }); }); } }); (function() { if (self.fetch) { return } function normalizeName(name) { if (typeof name !== 'string') { name = String(name) } if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { throw new TypeError('Invalid character in header field name') } return name.toLowerCase() } function normalizeValue(value) { if (typeof value !== 'string') { value = String(value) } return value } function Headers(headers) { this.map = {} if (headers instanceof Headers) { headers.forEach(function(value, name) { this.append(name, value) }, this) } else if (headers) { Object.getOwnPropertyNames(headers).forEach(function(name) { this.append(name, headers[name]) }, this) } } Headers.prototype.append = function(name, value) { name = normalizeName(name) value = normalizeValue(value) var list = this.map[name] if (!list) { list = [] this.map[name] = list } list.push(value) } Headers.prototype['delete'] = function(name) { delete this.map[normalizeName(name)] } Headers.prototype.get = function(name) { var values = this.map[normalizeName(name)] return values ? values[0] : null } Headers.prototype.getAll = function(name) { return this.map[normalizeName(name)] || [] } Headers.prototype.has = function(name) { return this.map.hasOwnProperty(normalizeName(name)) } Headers.prototype.set = function(name, value) { this.map[normalizeName(name)] = [normalizeValue(value)] } Headers.prototype.forEach = function(callback, thisArg) { Object.getOwnPropertyNames(this.map).forEach(function(name) { this.map[name].forEach(function(value) { callback.call(thisArg, value, name, this) }, this) }, this) } function consumed(body) { if (body.bodyUsed) { return Promise.reject(new TypeError('Already read')) } body.bodyUsed = true } function fileReaderReady(reader) { return new Promise(function(resolve, reject) { reader.onload = function() { resolve(reader.result) } reader.onerror = function() { reject(reader.error) } }) } function readBlobAsArrayBuffer(blob) { var reader = new FileReader() reader.readAsArrayBuffer(blob) return fileReaderReady(reader) } function readBlobAsText(blob) { var reader = new FileReader() reader.readAsText(blob) return fileReaderReady(reader) } var support = { blob: 'FileReader' in self && 'Blob' in self && (function() { try { new Blob(); return true } catch(e) { return false } })(), formData: 'FormData' in self, arrayBuffer: 'ArrayBuffer' in self } function Body() { this.bodyUsed = false this._initBody = function(body) { this._bodyInit = body if (typeof body === 'string') { this._bodyText = body } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { this._bodyBlob = body } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { this._bodyFormData = body } else if (!body) { this._bodyText = '' } else if (support.arrayBuffer && ArrayBuffer.prototype.isPrototypeOf(body)) { // Only support ArrayBuffers for POST method. // Receiving ArrayBuffers happens via Blobs, instead. } else { throw new Error('unsupported BodyInit type') } } if (support.blob) { this.blob = function() { var rejected = consumed(this) if (rejected) { return rejected } if (this._bodyBlob) { return Promise.resolve(this._bodyBlob) } else if (this._bodyFormData) { throw new Error('could not read FormData body as blob') } else { return Promise.resolve(new Blob([this._bodyText])) } } this.arrayBuffer = function() { return this.blob().then(readBlobAsArrayBuffer) } this.text = function() { var rejected = consumed(this) if (rejected) { return rejected } if (this._bodyBlob) { return readBlobAsText(this._bodyBlob) } else if (this._bodyFormData) { throw new Error('could not read FormData body as text') } else { return Promise.resolve(this._bodyText) } } } else { this.text = function() { var rejected = consumed(this) return rejected ? rejected : Promise.resolve(this._bodyText) } } if (support.formData) { this.formData = function() { return this.text().then(decode) } } this.json = function() { return this.text().then(JSON.parse) } return this } // HTTP methods whose capitalization should be normalized var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] function normalizeMethod(method) { var upcased = method.toUpperCase() return (methods.indexOf(upcased) > -1) ? upcased : method } function Request(input, options) { options = options || {} var body = options.body if (Request.prototype.isPrototypeOf(input)) { if (input.bodyUsed) { throw new TypeError('Already read') } this.url = input.url this.credentials = input.credentials if (!options.headers) { this.headers = new Headers(input.headers) } this.method = input.method this.mode = input.mode if (!body) { body = input._bodyInit input.bodyUsed = true } } else { this.url = input } this.credentials = options.credentials || this.credentials || 'omit' if (options.headers || !this.headers) { this.headers = new Headers(options.headers) } this.method = normalizeMethod(options.method || this.method || 'GET') this.mode = options.mode || this.mode || null this.referrer = null if ((this.method === 'GET' || this.method === 'HEAD') && body) { throw new TypeError('Body not allowed for GET or HEAD requests') } this._initBody(body) } Request.prototype.clone = function() { return new Request(this) } function decode(body) { var form = new FormData() body.trim().split('&').forEach(function(bytes) { if (bytes) { var split = bytes.split('=') var name = split.shift().replace(/\+/g, ' ') var value = split.join('=').replace(/\+/g, ' ') form.append(decodeURIComponent(name), decodeURIComponent(value)) } }) return form } function headers(xhr) { var head = new Headers() var pairs = xhr.getAllResponseHeaders().trim().split('\n') pairs.forEach(function(header) { var split = header.trim().split(':') var key = split.shift().trim() var value = split.join(':').trim() head.append(key, value) }) return head } Body.call(Request.prototype) function Response(bodyInit, options) { if (!options) { options = {} } this._initBody(bodyInit) this.type = 'default' this.status = options.status this.ok = this.status >= 200 && this.status < 300 this.statusText = options.statusText this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers) this.url = options.url || '' } Body.call(Response.prototype) Response.prototype.clone = function() { return new Response(this._bodyInit, { status: this.status, statusText: this.statusText, headers: new Headers(this.headers), url: this.url }) } Response.error = function() { var response = new Response(null, {status: 0, statusText: ''}) response.type = 'error' return response } var redirectStatuses = [301, 302, 303, 307, 308] Response.redirect = function(url, status) { if (redirectStatuses.indexOf(status) === -1) { throw new RangeError('Invalid status code') } return new Response(null, {status: status, headers: {location: url}}) } self.Headers = Headers; self.Request = Request; self.Response = Response; self.fetch = function(input, init) { return new Promise(function(resolve, reject) { var request if (Request.prototype.isPrototypeOf(input) && !init) { request = input } else { request = new Request(input, init) } var xhr = new XMLHttpRequest() function responseURL() { if ('responseURL' in xhr) { return xhr.responseURL } // Avoid security warnings on getResponseHeader when not allowed by CORS if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) { return xhr.getResponseHeader('X-Request-URL') } return; } xhr.onload = function() { var status = (xhr.status === 1223) ? 204 : xhr.status if (status < 100 || status > 599) { reject(new TypeError('Network request failed')) return } var options = { status: status, statusText: xhr.statusText, headers: headers(xhr), url: responseURL() } var body = 'response' in xhr ? xhr.response : xhr.responseText; resolve(new Response(body, options)) } xhr.onerror = function() { reject(new TypeError('Network request failed')) } xhr.open(request.method, request.url, true) if (request.credentials === 'include') { xhr.withCredentials = true } if ('responseType' in xhr && support.blob) { xhr.responseType = 'blob' } request.headers.forEach(function(value, name) { xhr.setRequestHeader(name, value) }) xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) }) } self.fetch.polyfill = true })(); define("fetch", function(){}); define('aurelia-bootstrapper',['exports', 'core-js', 'aurelia-pal', 'aurelia-pal-browser'], function (exports, _coreJs, _aureliaPal, _aureliaPalBrowser) { exports.__esModule = true; exports.bootstrap = bootstrap; var bootstrapQueue = []; var sharedLoader = null; var Aurelia = null; function onBootstrap(callback) { return new Promise(function (resolve, reject) { if (sharedLoader) { resolve(callback(sharedLoader)); } else { bootstrapQueue.push(function () { try { resolve(callback(sharedLoader)); } catch (e) { reject(e); } }); } }); } function ready(global) { return new Promise(function (resolve, reject) { if (global.document.readyState === 'complete') { resolve(global.document); } else { global.document.addEventListener('DOMContentLoaded', completed, false); global.addEventListener('load', completed, false); } function completed() { global.document.removeEventListener('DOMContentLoaded', completed, false); global.removeEventListener('load', completed, false); resolve(global.document); } }); } function createLoader() { if (_aureliaPal.PLATFORM.Loader) { return Promise.resolve(new _aureliaPal.PLATFORM.Loader()); } if (window.System) { var bootstrapperName = System.normalizeSync('aurelia-bootstrapper'); var loaderName = System.normalizeSync('aurelia-loader-default', bootstrapperName); return System['import'](loaderName).then(function (m) { return new m.DefaultLoader(); }); } else if (window.require) { return new Promise(function (resolve, reject) { return require(['aurelia-loader-default'], function (m) { return resolve(new m.DefaultLoader()); }, reject); }); } throw new Error('No PLATFORM.Loader is defined and there is neither a System API (ES6) or a Require API (AMD) globally available to load your app.'); } function preparePlatform(loader) { var bootstrapperName = loader.normalizeSync('aurelia-bootstrapper'); var frameworkName = loader.normalizeSync('aurelia-framework', bootstrapperName); loader.map('aurelia-framework', frameworkName); var diName = loader.normalizeSync('aurelia-dependency-injection', frameworkName); loader.map('aurelia-dependency-injection', diName); var routerName = loader.normalizeSync('aurelia-router', bootstrapperName); loader.map('aurelia-router', routerName); var loggingConsoleName = loader.normalizeSync('aurelia-logging-console', bootstrapperName); loader.map('aurelia-logging-console', loggingConsoleName); return loader.loadModule(frameworkName).then(function (m) { return Aurelia = m.Aurelia; }); } function handleApp(loader, appHost) { var configModuleId = appHost.getAttribute('aurelia-app'); return configModuleId ? customConfig(loader, appHost, configModuleId) : defaultConfig(loader, appHost); } function customConfig(loader, appHost, configModuleId) { return loader.loadModule(configModuleId).then(function (m) { var aurelia = new Aurelia(loader); aurelia.host = appHost; return m.configure(aurelia); }); } function defaultConfig(loader, appHost) { var aurelia = new Aurelia(loader); aurelia.host = appHost; if (window.location.protocol !== 'http' && window.location.protocol !== 'https') { aurelia.use.developmentLogging(); } aurelia.use.standardConfiguration(); return aurelia.start().then(function (a) { return a.setRoot(); }); } function run() { return ready(window).then(function (doc) { _aureliaPalBrowser.initialize(); var appHost = doc.querySelectorAll('[aurelia-app]'); return createLoader().then(function (loader) { return preparePlatform(loader).then(function () { for (var i = 0, ii = appHost.length; i < ii; ++i) { handleApp(loader, appHost[i])['catch'](console.error.bind(console)); } sharedLoader = loader; for (var i = 0, ii = bootstrapQueue.length; i < ii; ++i) { bootstrapQueue[i](); } bootstrapQueue = null; }); }); }); } function bootstrap(configure) { return onBootstrap(function (loader) { var aurelia = new Aurelia(loader); return configure(aurelia); }); } run(); }); (function(global) { var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); var hasTemplateElement = typeof HTMLTemplateElement !== 'undefined'; var hasProto = '__proto__' in {}; var htmlElement = global.HTMLUnknownElement || HTMLElement; var contentDescriptor = { get: function() { return this.content_; }, enumerable: true, configurable: true }; function isSVGTemplate(el) { return el.tagName === 'template' && el.namespaceURI === 'http://www.w3.org/2000/svg'; } function isHTMLTemplate(el) { return el.tagName === 'TEMPLATE' && el.namespaceURI === 'http://www.w3.org/1999/xhtml'; } function isTemplate(el) { if (el.isTemplate_ === undefined) { el.isTemplate_ = el.tagName === 'TEMPLATE'; } return el.isTemplate_; } function extractTemplateFromSVGTemplate(el) { var template = el.ownerDocument.createElement('template'); var attribs = el.attributes; var count = attribs.length; var attrib; el.parentNode.insertBefore(template, el); while (count-- > 0) { attrib = attribs[count]; template.setAttribute(attrib.name, attrib.value); el.removeAttribute(attrib.name); } el.parentNode.removeChild(el); return template; } function forAllTemplatesFrom(node, fn) { var subTemplates = node.querySelectorAll('template'); if (isTemplate(node)) { fn(node); } forEach(subTemplates, fn); } function bootstrapTemplatesRecursivelyFrom(node) { function bootstrap(template) { if (!HTMLTemplateElement.decorate(template)) { bootstrapTemplatesRecursivelyFrom(template.content); } } forAllTemplatesFrom(node, bootstrap); } if (!hasTemplateElement) { global.HTMLTemplateElement = function() { throw new TypeError('Illegal constructor'); }; } function getOrCreateTemplateContentsOwner(template) { var doc = template.ownerDocument; var d; if (!doc.defaultView) { return doc; } d = doc.templateContentsOwner_; if (!d) { // TODO(arv): This should either be a Document or HTMLDocument depending // on doc. d = doc.implementation.createHTMLDocument(''); while (d.lastChild) { d.removeChild(d.lastChild); } doc.templateContentsOwner_ = d; } return d; } function liftNonNativeTemplateChildrenIntoContent(template, el, useRoot) { var content = template.content; var child; if (useRoot) { content.appendChild(el); return; } while (child = el.firstChild) { content.appendChild(child); } } function mixin(to, from) { Object.getOwnPropertyNames(from).forEach(function(name) { Object.defineProperty(to, name, Object.getOwnPropertyDescriptor(from, name)); }); } function fixTemplateElementPrototype(el) { if (hasProto) { el.__proto__ = HTMLTemplateElement.prototype; } else { mixin(el, HTMLTemplateElement.prototype); } } HTMLTemplateElement.decorate = function(el, instanceRef) { var templateElement; var isNativeHTMLTemplate; var bootstrapContents; var liftContents; var liftRoot; var doc; if (el.templateIsDecorated_) { return false; } templateElement = el; templateElement.templateIsDecorated_ = true; isNativeHTMLTemplate = isHTMLTemplate(templateElement) && hasTemplateElement; bootstrapContents = isNativeHTMLTemplate; liftContents = !isNativeHTMLTemplate; liftRoot = false; if (!isNativeHTMLTemplate) { if (isSVGTemplate(templateElement)) { templateElement = extractTemplateFromSVGTemplate(el); templateElement.templateIsDecorated_ = true; isNativeHTMLTemplate = hasTemplateElement; } } if (!isNativeHTMLTemplate) { fixTemplateElementPrototype(templateElement); doc = getOrCreateTemplateContentsOwner(templateElement); templateElement.content_ = doc.createDocumentFragment(); } if (instanceRef) { // template is contained within an instance, its direct content must be // empty templateElement.instanceRef_ = instanceRef; } else if (liftContents) { liftNonNativeTemplateChildrenIntoContent(templateElement, el, liftRoot); } else if (bootstrapContents) { bootstrapTemplatesRecursivelyFrom(templateElement.content); } return true; }; if (!hasTemplateElement) { // Gecko is more picky with the prototype than WebKit. Make sure to use the // same prototype as created in the constructor. HTMLTemplateElement.prototype = Object.create(htmlElement.prototype); Object.defineProperty(HTMLTemplateElement.prototype, 'content', contentDescriptor); } HTMLTemplateElement.bootstrap = bootstrapTemplatesRecursivelyFrom; }(window)); define("aurelia-html-template-element", function(){}); define('aurelia-validation/validation-locale',['exports'], function (exports) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationLocale = (function () { function ValidationLocale(defaults, data) { _classCallCheck(this, ValidationLocale); this.defaults = defaults; this.currentLocale = data; } ValidationLocale.prototype.getValueFor = function getValueFor(identifier, category) { var currentLocaleSetting = undefined; var defaultSetting = undefined; if (this.currentLocale && this.currentLocale[category]) { currentLocaleSetting = this.currentLocale[category][identifier]; if (currentLocaleSetting !== undefined && currentLocaleSetting !== null) { return currentLocaleSetting; } } if (this.defaults[category]) { defaultSetting = this.defaults[category][identifier]; if (defaultSetting !== undefined && defaultSetting !== null) { return defaultSetting; } } throw new Error('validation: I18N: Could not find: ' + identifier + ' in category: ' + category); }; ValidationLocale.prototype.setting = function setting(settingIdentifier) { return this.getValueFor(settingIdentifier, 'settings'); }; ValidationLocale.prototype.translate = function translate(translationIdentifier, newValue, threshold) { var translation = this.getValueFor(translationIdentifier, 'messages'); if (typeof translation === 'function') { return translation(newValue, threshold); } if (typeof translation === 'string') { return translation; } throw new Error('Validation message for ' + translationIdentifier + 'was in an unsupported format'); }; return ValidationLocale; })(); exports.ValidationLocale = ValidationLocale; var ValidationLocaleRepository = (function () { function ValidationLocaleRepository() { _classCallCheck(this, ValidationLocaleRepository); this['default'] = null; this.instances = new Map(); this.defaults = { settings: { 'numericRegex': /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/ }, messages: {} }; } ValidationLocaleRepository.prototype.load = function load(localeIdentifier, basePath) { var _this = this; if (!basePath) { basePath = 'aurelia-validation/resources/'; } return new Promise(function (resolve, reject) { if (_this.instances.has(localeIdentifier)) { var locale = _this.instances.get(localeIdentifier); resolve(locale); } else { System['import'](basePath + localeIdentifier).then(function (resource) { var locale = _this.addLocale(localeIdentifier, resource.data); resolve(locale); }); } }); }; ValidationLocaleRepository.prototype.addLocale = function addLocale(localeIdentifier, data) { var instance = new ValidationLocale(this.defaults, data); this.instances.set(localeIdentifier, instance); if (this['default'] === null) { this['default'] = instance; } return instance; }; return ValidationLocaleRepository; })(); ValidationLocale.Repository = new ValidationLocaleRepository(); }); define('aurelia-validation/validation-view-strategy',['exports'], function (exports) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationViewStrategy = (function () { function ValidationViewStrategy() { _classCallCheck(this, ValidationViewStrategy); this.bindingPathAttributes = ['validate', 'value.bind', 'value.two-way']; } ValidationViewStrategy.prototype.getValidationProperty = function getValidationProperty(validation, element) { var atts = element.attributes; for (var i = 0; i < this.bindingPathAttributes.length; i++) { var attributeName = this.bindingPathAttributes[i]; var bindingPath = undefined; var validationProperty = undefined; if (atts[attributeName]) { bindingPath = atts[attributeName].value.trim(); if (bindingPath.indexOf('|') !== -1) { bindingPath = bindingPath.split('|')[0].trim(); } validationProperty = validation.result.properties[bindingPath]; if (attributeName === 'validate' && (validationProperty === null || validationProperty === undefined)) { validation.ensure(bindingPath); validationProperty = validation.result.properties[bindingPath]; } return validationProperty; } } return null; }; ValidationViewStrategy.prototype.prepareElement = function prepareElement(validationProperty, element) { throw Error('View strategy must implement prepareElement(validationProperty, element)'); }; ValidationViewStrategy.prototype.updateElement = function updateElement(validationProperty, element) { throw Error('View strategy must implement updateElement(validationProperty, element)'); }; return ValidationViewStrategy; })(); exports.ValidationViewStrategy = ValidationViewStrategy; }); define('aurelia-validation/strategies/twbootstrap-view-strategy',['exports', '../validation-view-strategy'], function (exports, _validationViewStrategy) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var TWBootstrapViewStrategyBase = (function (_ValidationViewStrategy) { _inherits(TWBootstrapViewStrategyBase, _ValidationViewStrategy); function TWBootstrapViewStrategyBase(appendMessageToInput, appendMessageToLabel, helpBlockClass) { _classCallCheck(this, TWBootstrapViewStrategyBase); _ValidationViewStrategy.call(this); this.appendMessageToInput = appendMessageToInput; this.appendMessageToLabel = appendMessageToLabel; this.helpBlockClass = helpBlockClass; } TWBootstrapViewStrategyBase.prototype.searchFormGroup = function searchFormGroup(currentElement, currentDepth) { if (currentDepth === 5) { return null; } if (currentElement.classList && currentElement.classList.contains('form-group')) { return currentElement; } return this.searchFormGroup(currentElement.parentNode, 1 + currentDepth); }; TWBootstrapViewStrategyBase.prototype.findLabels = function findLabels(formGroup, inputId) { var labels = []; this.findLabelsRecursively(formGroup, inputId, labels, 0); return labels; }; TWBootstrapViewStrategyBase.prototype.findLabelsRecursively = function findLabelsRecursively(currentElement, inputId, currentLabels, currentDepth) { if (currentDepth === 5) { return; } if (currentElement.nodeName === 'LABEL' && (currentElement.attributes['for'] && currentElement.attributes['for'].value === inputId || !currentElement.attributes['for'])) { currentLabels.push(currentElement); } for (var i = 0; i < currentElement.children.length; i++) { this.findLabelsRecursively(currentElement.children[i], inputId, currentLabels, 1 + currentDepth); } }; TWBootstrapViewStrategyBase.prototype.appendMessageToElement = function appendMessageToElement(element, validationProperty) { var helpBlock = element.nextSibling; if (helpBlock) { if (!helpBlock.classList) { helpBlock = null; } else if (!helpBlock.classList.contains(this.helpBlockClass)) { helpBlock = null; } } if (!helpBlock) { helpBlock = document.createElement('p'); helpBlock.classList.add('help-block'); helpBlock.classList.add(this.helpBlockClass); if (element.nextSibling) { element.parentNode.insertBefore(helpBlock, element.nextSibling); } else { element.parentNode.appendChild(helpBlock); } } helpBlock.textContent = validationProperty ? validationProperty.message : ''; }; TWBootstrapViewStrategyBase.prototype.appendUIVisuals = function appendUIVisuals(validationProperty, currentElement) { var formGroup = this.searchFormGroup(currentElement, 0); if (formGroup === null) { return; } if (validationProperty && validationProperty.isDirty) { if (validationProperty.isValid) { formGroup.classList.remove('has-warning'); formGroup.classList.add('has-success'); } else { formGroup.classList.remove('has-success'); formGroup.classList.add('has-warning'); } } else { formGroup.classList.remove('has-warning'); formGroup.classList.remove('has-success'); } if (this.appendMessageToInput) { this.appendMessageToElement(currentElement, validationProperty); } if (this.appendMessageToLabel) { var labels = this.findLabels(formGroup, currentElement.id); for (var ii = 0; ii < labels.length; ii++) { var label = labels[ii]; this.appendMessageToElement(label, validationProperty); } } }; TWBootstrapViewStrategyBase.prototype.prepareElement = function prepareElement(validationProperty, element) { this.appendUIVisuals(null, element); }; TWBootstrapViewStrategyBase.prototype.updateElement = function updateElement(validationProperty, element) { this.appendUIVisuals(validationProperty, element); }; return TWBootstrapViewStrategyBase; })(_validationViewStrategy.ValidationViewStrategy); exports.TWBootstrapViewStrategyBase = TWBootstrapViewStrategyBase; var TWBootstrapViewStrategy = function TWBootstrapViewStrategy() { _classCallCheck(this, TWBootstrapViewStrategy); }; exports.TWBootstrapViewStrategy = TWBootstrapViewStrategy; TWBootstrapViewStrategy.AppendToInput = new TWBootstrapViewStrategyBase(true, false, 'aurelia-validation-message'); TWBootstrapViewStrategy.AppendToMessage = new TWBootstrapViewStrategyBase(false, true, 'aurelia-validation-message'); }); define('aurelia-validation/validation-config',['exports', './validation-locale', './strategies/twbootstrap-view-strategy'], function (exports, _validationLocale, _strategiesTwbootstrapViewStrategy) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationConfigDefaults = function ValidationConfigDefaults() { _classCallCheck(this, ValidationConfigDefaults); }; exports.ValidationConfigDefaults = ValidationConfigDefaults; ValidationConfigDefaults._defaults = { debounceTimeout: 0, dependencies: [], locale: 'en-US', localeResources: 'aurelia-validation/resources/', viewStrategy: _strategiesTwbootstrapViewStrategy.TWBootstrapViewStrategy.AppendToMessage, allPropertiesAreMandatory: false }; ValidationConfigDefaults.defaults = function () { var defaults = {}; Object.assign(defaults, ValidationConfigDefaults._defaults); return defaults; }; var ValidationConfig = (function () { function ValidationConfig(innerConfig) { _classCallCheck(this, ValidationConfig); this.innerConfig = innerConfig; this.values = this.innerConfig ? {} : ValidationConfigDefaults.defaults(); this.changedHandlers = new Map(); } ValidationConfig.prototype.getValue = function getValue(identifier) { if (this.values.hasOwnProperty(identifier) !== null && this.values[identifier] !== undefined) { return this.values[identifier]; } if (this.innerConfig !== null) { return this.innerConfig.getValue(identifier); } throw Error('Config not found: ' + identifier); }; ValidationConfig.prototype.setValue = function setValue(identifier, value) { this.values[identifier] = value; return this; }; ValidationConfig.prototype.onLocaleChanged = function onLocaleChanged(callback) { var _this = this; if (this.innerConfig !== undefined) { return this.innerConfig.onLocaleChanged(callback); } var id = ++ValidationConfig.uniqueListenerId; this.changedHandlers.set(id, callback); return function () { _this.changedHandlers['delete'](id); }; }; ValidationConfig.prototype.getDebounceTimeout = function getDebounceTimeout() { return this.getValue('debounceTimeout'); }; ValidationConfig.prototype.useDebounceTimeout = function useDebounceTimeout(value) { return this.setValue('debounceTimeout', value); }; ValidationConfig.prototype.getDependencies = function getDependencies() { return this.getValue('dependencies'); }; ValidationConfig.prototype.computedFrom = function computedFrom(dependencies) { var deps = dependencies; if (typeof dependencies === 'string') { deps = []; deps.push(dependencies); } return this.setValue('dependencies', deps); }; ValidationConfig.prototype.useLocale = function useLocale(localeIdentifier) { this.setValue('locale', localeIdentifier); var callbacks = Array.from(this.changedHandlers.values()); for (var i = 0; i < callbacks.length; i++) { callbacks[i](); } return this; }; ValidationConfig.prototype.locale = function locale() { return _validationLocale.ValidationLocale.Repository.load(this.getValue('locale'), this.getValue('localeResources')); }; ValidationConfig.prototype.useViewStrategy = function useViewStrategy(viewStrategy) { return this.setValue('viewStrategy', viewStrategy); }; ValidationConfig.prototype.getViewStrategy = function getViewStrategy() { return this.getValue('viewStrategy'); }; ValidationConfig.prototype.treatAllPropertiesAsMandatory = function treatAllPropertiesAsMandatory() { this.setValue('allPropertiesAreMandatory', true); return this; }; ValidationConfig.prototype.treatAllPropertiesAsOptional = function treatAllPropertiesAsOptional() { this.setValue('allPropertiesAreMandatory', false); return this; }; return ValidationConfig; })(); exports.ValidationConfig = ValidationConfig; ValidationConfig.uniqueListenerId = 0; }); define('aurelia-validation/utilities',['exports'], function (exports) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Utilities = (function () { function Utilities() { _classCallCheck(this, Utilities); } Utilities.getValue = function getValue(val) { if (val !== undefined && typeof val === 'function') { return val(); } return val; }; Utilities.isEmptyValue = function isEmptyValue(val) { if (val === undefined) { return true; } if (val === null) { return true; } if (val === '') { return true; } if (typeof val === 'string') { if (String.prototype.trim) { val = val.trim(); } else { val = val.replace(/^\s+|\s+$/g, ''); } } if (val.length !== undefined) { return val.length === 0; } return false; }; return Utilities; })(); exports.Utilities = Utilities; }); define('aurelia-validation/validation-rules-collection',['exports', './utilities', './validation-locale'], function (exports, _utilities, _validationLocale) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationRulesCollection = (function () { function ValidationRulesCollection(config) { _classCallCheck(this, ValidationRulesCollection); this.isRequired = config ? config.getValue('allPropertiesAreMandatory') : false; this.validationRules = []; this.validationCollections = []; this.isRequiredMessage = null; } ValidationRulesCollection.prototype.validate = function validate(newValue, locale) { var executeRules = true; var thisMessage = undefined; var checks = undefined; if (locale === undefined) { locale = _validationLocale.ValidationLocale.Repository['default']; } newValue = _utilities.Utilities.getValue(newValue); if (this.isRequiredMessage) { thisMessage = typeof this.isRequiredMessage === 'function' ? this.isRequiredMessage(newValue) : this.isRequiredMessage; } else { thisMessage = locale.translate('isRequired'); } if (_utilities.Utilities.isEmptyValue(newValue)) { if (this.isRequired) { return Promise.resolve({ isValid: false, message: thisMessage, failingRule: 'isRequired', latestValue: newValue }); } executeRules = false; } checks = Promise.resolve({ isValid: true, message: '', failingRule: null, latestValue: newValue }); if (executeRules) { this.validationRules.forEach(function (rule) { checks = checks.then(function (previousRuleResult) { if (previousRuleResult.isValid === false) { return previousRuleResult; } return rule.validate(newValue, locale).then(function (thisRuleResult) { if (thisRuleResult === false) { return { isValid: false, message: rule.explain(), failingRule: rule.ruleName, latestValue: newValue }; } if (!previousRuleResult.isValid) { throw Error("ValidationRulesCollection.validate caught an unexpected result while validating it's chain of rules."); } return previousRuleResult; }); }); }); } this.validationCollections.forEach(function (validationCollection) { checks = checks.then(function (previousValidationResult) { if (previousValidationResult.isValid) { return validationCollection.validate(newValue, locale); } return previousValidationResult; }); }); return checks; }; ValidationRulesCollection.prototype.addValidationRule = function addValidationRule(validationRule) { if (validationRule.validate === undefined) { throw new Error("That's not a valid validationRule"); } this.validationRules.push(validationRule); }; ValidationRulesCollection.prototype.addValidationRuleCollection = function addValidationRuleCollection(validationRulesCollection) { this.validationCollections.push(validationRulesCollection); }; ValidationRulesCollection.prototype.isNotEmpty = function isNotEmpty() { this.isRequired = true; }; ValidationRulesCollection.prototype.canBeEmpty = function canBeEmpty() { this.isRequired = false; }; ValidationRulesCollection.prototype.withMessage = function withMessage(message) { if (this.validationRules.length === 0) { this.isRequiredMessage = message; } else { this.validationRules[this.validationRules.length - 1].withMessage(message); } }; return ValidationRulesCollection; })(); exports.ValidationRulesCollection = ValidationRulesCollection; var SwitchCaseValidationRulesCollection = (function () { function SwitchCaseValidationRulesCollection(conditionExpression, config) { _classCallCheck(this, SwitchCaseValidationRulesCollection); this.conditionExpression = conditionExpression; this.config = config; this.innerCollections = []; this.defaultCollection = new ValidationRulesCollection(this.config); this.caseLabel = ''; this.defaultCaseLabel = { description: 'this is the case label for \'default\'' }; } SwitchCaseValidationRulesCollection.prototype['case'] = function _case(caseLabel) { this.caseLabel = caseLabel; this.getCurrentCollection(caseLabel, true); }; SwitchCaseValidationRulesCollection.prototype['default'] = function _default() { this.caseLabel = this.defaultCaseLabel; }; SwitchCaseValidationRulesCollection.prototype.getCurrentCollection = function getCurrentCollection(caseLabel) { var createIfNotExists = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (caseLabel === this.defaultCaseLabel) { return this.defaultCollection; } var currentCollection = null; for (var i = 0; i < this.innerCollections.length; i++) { currentCollection = this.innerCollections[i]; if (currentCollection.caseLabel === caseLabel) { return currentCollection.collection; } } if (createIfNotExists) { currentCollection = { caseLabel: caseLabel, collection: new ValidationRulesCollection(this.config) }; this.innerCollections.push(currentCollection); return currentCollection.collection; } return null; }; SwitchCaseValidationRulesCollection.prototype.validate = function validate(newValue, locale) { var collection = this.getCurrentCollection(this.conditionExpression(newValue)); if (collection !== null) { return collection.validate(newValue, locale); } return this.defaultCollection.validate(newValue, locale); }; SwitchCaseValidationRulesCollection.prototype.addValidationRule = function addValidationRule(validationRule) { var currentCollection = this.getCurrentCollection(this.caseLabel, true); currentCollection.addValidationRule(validationRule); }; SwitchCaseValidationRulesCollection.prototype.addValidationRuleCollection = function addValidationRuleCollection(validationRulesCollection) { var currentCollection = this.getCurrentCollection(this.caseLabel, true); currentCollection.addValidationRuleCollection(validationRulesCollection); }; SwitchCaseValidationRulesCollection.prototype.isNotEmpty = function isNotEmpty() { var collection = this.getCurrentCollection(this.caseLabel); if (collection !== null) { collection.isNotEmpty(); } else { this.defaultCollection.isNotEmpty(); } }; SwitchCaseValidationRulesCollection.prototype.canBeEmpty = function canBeEmpty() { var collection = this.getCurrentCollection(this.caseLabel); if (collection !== null) { collection.canBeEmpty(); } else { this.defaultCollection.canBeEmpty(); } }; SwitchCaseValidationRulesCollection.prototype.withMessage = function withMessage(message) { var collection = this.getCurrentCollection(this.caseLabel); if (collection !== null) { collection.withMessage(message); } else { this.defaultCollection.withMessage(message); } }; return SwitchCaseValidationRulesCollection; })(); exports.SwitchCaseValidationRulesCollection = SwitchCaseValidationRulesCollection; }); define('aurelia-validation/path-observer',['exports'], function (exports) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var PathObserver = (function () { function PathObserver(observerLocator, subject, path) { _classCallCheck(this, PathObserver); this.observerLocator = observerLocator; this.path = path.split('.'); this.subject = subject; this.observers = []; this.callbacks = []; if (this.path.length > 1) { this.observeParts(); } } PathObserver.prototype.observeParts = function observeParts(propertyName) { var _this = this; var currentSubject = this.subject; var observersAreComplete = undefined; if (propertyName !== undefined && propertyName !== null) { for (var i = this.observers.length - 1; i >= 0; i--) { var currentObserver = this.observers[i]; var observer = undefined; if (currentObserver.propertyName === propertyName) { break; } observer = this.observers.pop(); if (observer && observer.subscription) { observer.subscription(); } } } observersAreComplete = this.observers.length === this.path.length; var _loop = function (i) { var observer = _this.observers[i]; var currentPath = _this.path[i]; var subscription = undefined; var currentValue = undefined; if (!observer) { observer = _this.observerLocator.getObserver(currentSubject, currentPath); _this.observers.push(observer); subscription = observer.subscribe(function (newValue, oldValue) { _this.observeParts(observer.propertyName); }); observer.subscription = subscription; } currentValue = observer.getValue(); if (currentValue === undefined || currentValue === null) { return 'break'; } else { currentSubject = currentValue; } }; for (var i = 0; i < this.path.length; i++) { var _ret = _loop(i); if (_ret === 'break') break; } if (!observersAreComplete && this.observers.length === this.path.length) { var actualObserver = this.observers[this.observers.length - 1]; for (var i = 0; i < this.callbacks.length; i++) { actualObserver.subscribe(this.callbacks[i]); } } }; PathObserver.prototype.observePart = function observePart(part) { if (part !== this.path[this.path.length - 1]) { this.observeParts(); } }; PathObserver.prototype.getObserver = function getObserver() { if (this.path.length === 1) { this.subject[this.path[0]]; return this.observerLocator.getObserver(this.subject, this.path[0]); } return this; }; PathObserver.prototype.getValue = function getValue() { var expectedSubject = this.subject; for (var i = 0; this.path.length; i++) { var currentObserver = this.observers[i]; if (currentObserver === null || currentObserver === undefined) { this.observeParts(this.path[i]); currentObserver = this.observers[i]; if (currentObserver === null || currentObserver === undefined) { break; } } if (currentObserver.obj !== expectedSubject) { this.observeParts(this.path[i - 1]); break; } expectedSubject = currentObserver.getValue(); } if (this.observers.length !== this.path.length) { return undefined; } var value = this.observers[this.observers.length - 1].getValue(); return value; }; PathObserver.prototype.subscribe = function subscribe(callback) { var _this2 = this; this.callbacks.unshift(callback); if (this.observers.length === this.path.length) { this.subscription = this.observers[this.observers.length - 1].subscribe(callback); return function () { return _this2.unsubscribe(); }; } }; PathObserver.prototype.unsubscribe = function unsubscribe() { this.callbacks = []; if (this.subscription) { this.subscription(); } for (var i = this.observers.length - 1; i >= 0; i--) { var observer = this.observers.pop(); if (observer && observer.subscription) { observer.subscription(); } } }; return PathObserver; })(); exports.PathObserver = PathObserver; }); define('aurelia-validation/debouncer',["exports"], function (exports) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Debouncer = (function () { function Debouncer(debounceTimeout) { _classCallCheck(this, Debouncer); this.currentFunction = null; this.debounceTimeout = debounceTimeout; } Debouncer.prototype.debounce = function debounce(func) { var _this = this; this.currentFunction = func; setTimeout(function () { if (func !== null && func !== undefined) { if (func === _this.currentFunction) { _this.currentFunction = null; func(); } } }, this.debounceTimeout); }; return Debouncer; })(); exports.Debouncer = Debouncer; }); define('aurelia-validation/validation-property',['exports', './validation-rules-collection', './path-observer', './debouncer'], function (exports, _validationRulesCollection, _pathObserver, _debouncer) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationProperty = (function () { function ValidationProperty(observerLocator, propertyName, validationGroup, propertyResult, config) { var _this = this; _classCallCheck(this, ValidationProperty); this.propertyResult = propertyResult; this.propertyName = propertyName; this.validationGroup = validationGroup; this.collectionOfValidationRules = new _validationRulesCollection.ValidationRulesCollection(config); this.config = config; this.latestValue = undefined; this.observer = new _pathObserver.PathObserver(observerLocator, validationGroup.subject, propertyName).getObserver(); this.debouncer = new _debouncer.Debouncer(config.getDebounceTimeout()); this.subscription = this.observer.subscribe(function () { _this.debouncer.debounce(function () { var newValue = _this.observer.getValue(); if (newValue !== _this.latestValue) { _this.validate(newValue, true); } }); }); this.dependencyObservers = []; var dependencies = this.config.getDependencies(); for (var i = 0; i < dependencies.length; i++) { var dependencyObserver = new _pathObserver.PathObserver(observerLocator, validationGroup.subject, dependencies[i]).getObserver(); dependencyObserver.subscribe(function () { _this.debouncer.debounce(function () { _this.validateCurrentValue(true); }); }); this.dependencyObservers.push(dependencyObserver); } } ValidationProperty.prototype.addValidationRule = function addValidationRule(validationRule) { if (validationRule.validate === undefined) { throw new Error("That's not a valid validationRule"); } this.collectionOfValidationRules.addValidationRule(validationRule); this.validateCurrentValue(false); }; ValidationProperty.prototype.validateCurrentValue = function validateCurrentValue(forceDirty, forceExecution) { return this.validate(this.observer.getValue(), forceDirty, forceExecution); }; ValidationProperty.prototype.clear = function clear() { this.latestValue = this.observer.getValue(); this.propertyResult.clear(); }; ValidationProperty.prototype.destroy = function destroy() { if (this.subscription) { this.subscription(); } }; ValidationProperty.prototype.validate = function validate(newValue, shouldBeDirty, forceExecution) { var _this2 = this; if (!this.propertyResult.isDirty && shouldBeDirty || this.latestValue !== newValue || forceExecution) { this.latestValue = newValue; return this.config.locale().then(function (locale) { return _this2.collectionOfValidationRules.validate(newValue, locale).then(function (validationResponse) { if (_this2.latestValue === validationResponse.latestValue) { _this2.propertyResult.setValidity(validationResponse, shouldBeDirty); } return validationResponse.isValid; })['catch'](function (err) { throw Error('Unexpected behavior: a validation-rules-collection should always fulfil'); }); }, function () { throw Error('An exception occurred while trying to load the locale'); }); } }; return ValidationProperty; })(); exports.ValidationProperty = ValidationProperty; }); define('aurelia-validation/validation-rules',['exports', './utilities', './validation-locale'], function (exports, _utilities, _validationLocale) { exports.__esModule = true; 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationRule = (function () { function ValidationRule(threshold, onValidate, message, ruleName) { _classCallCheck(this, ValidationRule); this.onValidate = onValidate; this.threshold = threshold; this.message = message; this.errorMessage = null; this.ruleName = ruleName; } ValidationRule.prototype.withMessage = function withMessage(message) { this.message = message; }; ValidationRule.prototype.explain = function explain() { return this.errorMessage; }; ValidationRule.prototype.setResult = function setResult(result, currentValue, locale) { if (result === true || result === undefined || result === null || result === '') { this.errorMessage = null; return true; } if (typeof result === 'string') { this.errorMessage = result; } else { if (this.message) { if (typeof this.message === 'function') { this.errorMessage = this.message(currentValue, this.threshold); } else if (typeof this.message === 'string') { this.errorMessage = this.message; } else { throw Error('Unable to handle the error message:' + this.message); } } else { this.errorMessage = locale.translate(this.ruleName, currentValue, this.threshold); } } return false; }; ValidationRule.prototype.validate = function validate(currentValue, locale) { var _this = this; if (locale === undefined) { locale = _validationLocale.ValidationLocale.Repository['default']; } currentValue = _utilities.Utilities.getValue(currentValue); var result = this.onValidate(currentValue, this.threshold, locale); var promise = Promise.resolve(result); var nextPromise = promise.then(function (promiseResult) { return _this.setResult(promiseResult, currentValue, locale); }, function (promiseFailure) { if (typeof promiseFailure === 'string' && promiseFailure !== '') { return _this.setResult(promiseFailure, currentValue, locale); } return _this.setResult(false, currentValue, locale); }); return nextPromise; }; return ValidationRule; })(); exports.ValidationRule = ValidationRule; var URLValidationRule = (function (_ValidationRule) { _inherits(URLValidationRule, _ValidationRule); URLValidationRule.isIP = function isIP(str, version) { var ipv4Maybe = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/; var ipv6Block = /^[0-9A-F]{1,4}$/i; if (!version) { return this.isIP(str, 4) || this.isIP(str, 6); } else if (version === 4) { if (!ipv4Maybe.test(str)) { return false; } var parts = str.split('.').sort(function (a, b) { return a - b; }); return parts[3] <= 255; } else if (version === 6) { var blocks = str.split(':'); var foundOmissionBlock = false; if (blocks.length > 8) { return false; } if (str === '::') { return true; } else if (str.substr(0, 2) === '::') { blocks.shift(); blocks.shift(); foundOmissionBlock = true; } else if (str.substr(str.length - 2) === '::') { blocks.pop(); blocks.pop(); foundOmissionBlock = true; } for (var i = 0; i < blocks.length; ++i) { if (blocks[i] === '' && i > 0 && i < blocks.length - 1) { if (foundOmissionBlock) { return false; } foundOmissionBlock = true; } else if (!ipv6Block.test(blocks[i])) { return false; } } if (foundOmissionBlock) { return blocks.length >= 1; } return blocks.length === 8; } return false; }; URLValidationRule.isFQDN = function isFQDN(str, options) { if (options.allow_trailing_dot && str[str.length - 1] === '.') { str = str.substring(0, str.length - 1); } var parts = str.split('.'); if (options.require_tld) { var tld = parts.pop(); if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) { return false; } } for (var part = undefined, i = 0; i < parts.length; i++) { part = parts[i]; if (options.allow_underscores) { if (part.indexOf('__') >= 0) { return false; } part = part.replace(/_/g, ''); } if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) { return false; } if (part[0] === '-' || part[part.length - 1] === '-' || part.indexOf('---') >= 0) { return false; } } return true; }; function URLValidationRule(startingThreshold) { _classCallCheck(this, URLValidationRule); var defaultUrlOptions = { protocols: ['http', 'https', 'ftp'], require_tld: true, require_protocol: false, allow_underscores: true, allow_trailing_dot: false, allow_protocol_relative_urls: true }; if (startingThreshold === undefined) { startingThreshold = defaultUrlOptions; } _ValidationRule.call(this, startingThreshold, function (newValue, threshold) { var url = newValue; var protocol = undefined; var auth = undefined; var host = undefined; var hostname = undefined; var port = undefined; var portStr = undefined; var split = undefined; if (!url || url.length >= 2083 || /\s/.test(url)) { return false; } if (url.indexOf('mailto:') === 0) { return false; } split = url.split('://'); if (split.length > 1) { protocol = split.shift(); if (threshold.protocols.indexOf(protocol) === -1) { return false; } } else if (threshold.require_protocol) { return false; } else if (threshold.allow_protocol_relative_urls && url.substr(0, 2) === '//') { split[0] = url.substr(2); } url = split.join('://'); split = url.split('#'); url = split.shift(); split = url.split('?'); url = split.shift(); split = url.split('/'); url = split.shift(); split = url.split('@'); if (split.length > 1) { auth = split.shift(); if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) { return false; } } hostname = split.join('@'); split = hostname.split(':'); host = split.shift(); if (split.length) { portStr = split.join(':'); port = parseInt(portStr, 10); if (!/^[0-9]+$/.test(portStr) || port <= 0 || port > 65535) { return false; } } if (!URLValidationRule.isIP(host) && !URLValidationRule.isFQDN(host, threshold) && host !== 'localhost') { return false; } if (threshold.host_whitelist && threshold.host_whitelist.indexOf(host) === -1) { return false; } if (threshold.host_blacklist && threshold.host_blacklist.indexOf(host) !== -1) { return false; } return true; }, null, 'URLValidationRule'); } return URLValidationRule; })(ValidationRule); exports.URLValidationRule = URLValidationRule; var EmailValidationRule = (function (_ValidationRule2) { _inherits(EmailValidationRule, _ValidationRule2); EmailValidationRule.testEmailUserUtf8Regex = function testEmailUserUtf8Regex(user) { var emailUserUtf8Regex = /^((([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)))$/i; return emailUserUtf8Regex.test(user); }; EmailValidationRule.isFQDN = function isFQDN(str) { var parts = str.split('.'); for (var part = undefined, i = 0; i < parts.length; i++) { part = parts[i]; if (part.indexOf('__') >= 0) { return false; } part = part.replace(/_/g, ''); if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) { return false; } if (part[0] === '-' || part[part.length - 1] === '-' || part.indexOf('---') >= 0) { return false; } } return true; }; function EmailValidationRule() { _classCallCheck(this, EmailValidationRule); _ValidationRule2.call(this, null, function (newValue, threshold) { if (/\s/.test(newValue)) { return false; } var parts = newValue.split('@'); var domain = parts.pop(); var user = parts.join('@'); if (!EmailValidationRule.isFQDN(domain)) { return false; } return EmailValidationRule.testEmailUserUtf8Regex(user); }, null, 'EmailValidationRule'); } return EmailValidationRule; })(ValidationRule); exports.EmailValidationRule = EmailValidationRule; var MinimumLengthValidationRule = (function (_ValidationRule3) { _inherits(MinimumLengthValidationRule, _ValidationRule3); function MinimumLengthValidationRule(minimumLength) { _classCallCheck(this, MinimumLengthValidationRule); _ValidationRule3.call(this, minimumLength, function (newValue, minLength) { newValue = typeof newValue === 'number' ? newValue.toString() : newValue; return newValue.length !== undefined && newValue.length >= minLength; }, null, 'MinimumLengthValidationRule'); } return MinimumLengthValidationRule; })(ValidationRule); exports.MinimumLengthValidationRule = MinimumLengthValidationRule; var MaximumLengthValidationRule = (function (_ValidationRule4) { _inherits(MaximumLengthValidationRule, _ValidationRule4); function MaximumLengthValidationRule(maximumLength) { _classCallCheck(this, MaximumLengthValidationRule); _ValidationRule4.call(this, maximumLength, function (newValue, maxLength) { newValue = typeof newValue === 'number' ? newValue.toString() : newValue; return newValue.length !== undefined && newValue.length <= maxLength; }, null, 'MaximumLengthValidationRule'); } return MaximumLengthValidationRule; })(ValidationRule); exports.MaximumLengthValidationRule = MaximumLengthValidationRule; var BetweenLengthValidationRule = (function (_ValidationRule5) { _inherits(BetweenLengthValidationRule, _ValidationRule5); function BetweenLengthValidationRule(minimumLength, maximumLength) { _classCallCheck(this, BetweenLengthValidationRule); _ValidationRule5.call(this, { minimumLength: minimumLength, maximumLength: maximumLength }, function (newValue, threshold) { newValue = typeof newValue === 'number' ? newValue.toString() : newValue; return newValue.length !== undefined && newValue.length >= threshold.minimumLength && newValue.length <= threshold.maximumLength; }, null, 'BetweenLengthValidationRule'); } return BetweenLengthValidationRule; })(ValidationRule); exports.BetweenLengthValidationRule = BetweenLengthValidationRule; var CustomFunctionValidationRule = (function (_ValidationRule6) { _inherits(CustomFunctionValidationRule, _ValidationRule6); function CustomFunctionValidationRule(customFunction, threshold) { _classCallCheck(this, CustomFunctionValidationRule); _ValidationRule6.call(this, threshold, customFunction, null, 'CustomFunctionValidationRule'); } return CustomFunctionValidationRule; })(ValidationRule); exports.CustomFunctionValidationRule = CustomFunctionValidationRule; var NumericValidationRule = (function (_ValidationRule7) { _inherits(NumericValidationRule, _ValidationRule7); function NumericValidationRule() { _classCallCheck(this, NumericValidationRule); _ValidationRule7.call(this, null, function (newValue, threshold, locale) { var numericRegex = locale.setting('numericRegex'); var floatValue = parseFloat(newValue); return !Number.isNaN(parseFloat(newValue)) && Number.isFinite(floatValue) && numericRegex.test(newValue); }, null, 'NumericValidationRule'); } return NumericValidationRule; })(ValidationRule); exports.NumericValidationRule = NumericValidationRule; var RegexValidationRule = (function (_ValidationRule8) { _inherits(RegexValidationRule, _ValidationRule8); function RegexValidationRule(startingRegex, ruleName) { _classCallCheck(this, RegexValidationRule); _ValidationRule8.call(this, startingRegex, function (newValue, regex) { return regex.test(newValue); }, null, ruleName || 'RegexValidationRule'); } return RegexValidationRule; })(ValidationRule); exports.RegexValidationRule = RegexValidationRule; var ContainsOnlyValidationRule = (function (_RegexValidationRule) { _inherits(ContainsOnlyValidationRule, _RegexValidationRule); function ContainsOnlyValidationRule(regex) { _classCallCheck(this, ContainsOnlyValidationRule); _RegexValidationRule.call(this, regex, 'ContainsOnlyValidationRule'); } return ContainsOnlyValidationRule; })(RegexValidationRule); exports.ContainsOnlyValidationRule = ContainsOnlyValidationRule; var MinimumValueValidationRule = (function (_ValidationRule9) { _inherits(MinimumValueValidationRule, _ValidationRule9); function MinimumValueValidationRule(minimumValue) { _classCallCheck(this, MinimumValueValidationRule); _ValidationRule9.call(this, minimumValue, function (newValue, minValue) { return _utilities.Utilities.getValue(minValue) < newValue; }, null, 'MinimumValueValidationRule'); } return MinimumValueValidationRule; })(ValidationRule); exports.MinimumValueValidationRule = MinimumValueValidationRule; var MinimumInclusiveValueValidationRule = (function (_ValidationRule10) { _inherits(MinimumInclusiveValueValidationRule, _ValidationRule10); function MinimumInclusiveValueValidationRule(minimumValue) { _classCallCheck(this, MinimumInclusiveValueValidationRule); _ValidationRule10.call(this, minimumValue, function (newValue, minValue) { return _utilities.Utilities.getValue(minValue) <= newValue; }, null, 'MinimumInclusiveValueValidationRule'); } return MinimumInclusiveValueValidationRule; })(ValidationRule); exports.MinimumInclusiveValueValidationRule = MinimumInclusiveValueValidationRule; var MaximumValueValidationRule = (function (_ValidationRule11) { _inherits(MaximumValueValidationRule, _ValidationRule11); function MaximumValueValidationRule(maximumValue) { _classCallCheck(this, MaximumValueValidationRule); _ValidationRule11.call(this, maximumValue, function (newValue, maxValue) { return newValue < _utilities.Utilities.getValue(maxValue); }, null, 'MaximumValueValidationRule'); } return MaximumValueValidationRule; })(ValidationRule); exports.MaximumValueValidationRule = MaximumValueValidationRule; var MaximumInclusiveValueValidationRule = (function (_ValidationRule12) { _inherits(MaximumInclusiveValueValidationRule, _ValidationRule12); function MaximumInclusiveValueValidationRule(maximumValue) { _classCallCheck(this, MaximumInclusiveValueValidationRule); _ValidationRule12.call(this, maximumValue, function (newValue, maxValue) { return newValue <= _utilities.Utilities.getValue(maxValue); }, null, 'MaximumInclusiveValueValidationRule'); } return MaximumInclusiveValueValidationRule; })(ValidationRule); exports.MaximumInclusiveValueValidationRule = MaximumInclusiveValueValidationRule; var BetweenValueValidationRule = (function (_ValidationRule13) { _inherits(BetweenValueValidationRule, _ValidationRule13); function BetweenValueValidationRule(minimumValue, maximumValue) { _classCallCheck(this, BetweenValueValidationRule); _ValidationRule13.call(this, { minimumValue: minimumValue, maximumValue: maximumValue }, function (newValue, threshold) { return _utilities.Utilities.getValue(threshold.minimumValue) <= newValue && newValue <= _utilities.Utilities.getValue(threshold.maximumValue); }, null, 'BetweenValueValidationRule'); } return BetweenValueValidationRule; })(ValidationRule); exports.BetweenValueValidationRule = BetweenValueValidationRule; var DigitValidationRule = (function (_ValidationRule14) { _inherits(DigitValidationRule, _ValidationRule14); function DigitValidationRule() { _classCallCheck(this, DigitValidationRule); _ValidationRule14.call(this, null, function (newValue, threshold) { return (/^\d+$/.test(newValue) ); }, null, 'DigitValidationRule'); } return DigitValidationRule; })(ValidationRule); exports.DigitValidationRule = DigitValidationRule; var NoSpacesValidationRule = (function (_ValidationRule15) { _inherits(NoSpacesValidationRule, _ValidationRule15); function NoSpacesValidationRule() { _classCallCheck(this, NoSpacesValidationRule); _ValidationRule15.call(this, null, function (newValue, threshold) { return (/^\S*$/.test(newValue) ); }, null, 'NoSpacesValidationRule'); } return NoSpacesValidationRule; })(ValidationRule); exports.NoSpacesValidationRule = NoSpacesValidationRule; var AlphaNumericValidationRule = (function (_ValidationRule16) { _inherits(AlphaNumericValidationRule, _ValidationRule16); function AlphaNumericValidationRule() { _classCallCheck(this, AlphaNumericValidationRule); _ValidationRule16.call(this, null, function (newValue, threshold) { return (/^[a-z0-9]+$/i.test(newValue) ); }, null, 'AlphaNumericValidationRule'); } return AlphaNumericValidationRule; })(ValidationRule); exports.AlphaNumericValidationRule = AlphaNumericValidationRule; var AlphaValidationRule = (function (_ValidationRule17) { _inherits(AlphaValidationRule, _ValidationRule17); function AlphaValidationRule() { _classCallCheck(this, AlphaValidationRule); _ValidationRule17.call(this, null, function (newValue, threshold) { return (/^[a-z]+$/i.test(newValue) ); }, null, 'AlphaValidationRule'); } return AlphaValidationRule; })(ValidationRule); exports.AlphaValidationRule = AlphaValidationRule; var AlphaOrWhitespaceValidationRule = (function (_ValidationRule18) { _inherits(AlphaOrWhitespaceValidationRule, _ValidationRule18); function AlphaOrWhitespaceValidationRule() { _classCallCheck(this, AlphaOrWhitespaceValidationRule); _ValidationRule18.call(this, null, function (newValue, threshold) { return (/^[a-z\s]+$/i.test(newValue) ); }, null, 'AlphaOrWhitespaceValidationRule'); } return AlphaOrWhitespaceValidationRule; })(ValidationRule); exports.AlphaOrWhitespaceValidationRule = AlphaOrWhitespaceValidationRule; var AlphaNumericOrWhitespaceValidationRule = (function (_ValidationRule19) { _inherits(AlphaNumericOrWhitespaceValidationRule, _ValidationRule19); function AlphaNumericOrWhitespaceValidationRule() { _classCallCheck(this, AlphaNumericOrWhitespaceValidationRule); _ValidationRule19.call(this, null, function (newValue, threshold) { return (/^[a-z0-9\s]+$/i.test(newValue) ); }, null, 'AlphaNumericOrWhitespaceValidationRule'); } return AlphaNumericOrWhitespaceValidationRule; })(ValidationRule); exports.AlphaNumericOrWhitespaceValidationRule = AlphaNumericOrWhitespaceValidationRule; var MediumPasswordValidationRule = (function (_ValidationRule20) { _inherits(MediumPasswordValidationRule, _ValidationRule20); function MediumPasswordValidationRule(minimumComplexityLevel, ruleName) { _classCallCheck(this, MediumPasswordValidationRule); _ValidationRule20.call(this, minimumComplexityLevel ? minimumComplexityLevel : 3, function (newValue, threshold) { if (typeof newValue !== 'string') { return false; } var strength = 0; strength += /[A-Z]+/.test(newValue) ? 1 : 0; strength += /[a-z]+/.test(newValue) ? 1 : 0; strength += /[0-9]+/.test(newValue) ? 1 : 0; strength += /[\W]+/.test(newValue) ? 1 : 0; return strength >= threshold; }, null, ruleName || 'MediumPasswordValidationRule'); } return MediumPasswordValidationRule; })(ValidationRule); exports.MediumPasswordValidationRule = MediumPasswordValidationRule; var StrongPasswordValidationRule = (function (_MediumPasswordValidationRule) { _inherits(StrongPasswordValidationRule, _MediumPasswordValidationRule); function StrongPasswordValidationRule() { _classCallCheck(this, StrongPasswordValidationRule); _MediumPasswordValidationRule.call(this, 4, 'StrongPasswordValidationRule'); } return StrongPasswordValidationRule; })(MediumPasswordValidationRule); exports.StrongPasswordValidationRule = StrongPasswordValidationRule; var EqualityValidationRuleBase = (function (_ValidationRule21) { _inherits(EqualityValidationRuleBase, _ValidationRule21); function EqualityValidationRuleBase(startingOtherValue, equality, otherValueLabel, ruleName) { _classCallCheck(this, EqualityValidationRuleBase); _ValidationRule21.call(this, { otherValue: startingOtherValue, equality: equality, otherValueLabel: otherValueLabel }, function (newValue, threshold) { var otherValue = _utilities.Utilities.getValue(threshold.otherValue); if (newValue instanceof Date && otherValue instanceof Date) { return threshold.equality === (newValue.getTime() === otherValue.getTime()); } return threshold.equality === (newValue === otherValue); }, null, ruleName || 'EqualityValidationRuleBase'); } return EqualityValidationRuleBase; })(ValidationRule); exports.EqualityValidationRuleBase = EqualityValidationRuleBase; var EqualityValidationRule = (function (_EqualityValidationRuleBase) { _inherits(EqualityValidationRule, _EqualityValidationRuleBase); function EqualityValidationRule(otherValue) { _classCallCheck(this, EqualityValidationRule); _EqualityValidationRuleBase.call(this, otherValue, true, null, 'EqualityValidationRule'); } return EqualityValidationRule; })(EqualityValidationRuleBase); exports.EqualityValidationRule = EqualityValidationRule; var EqualityWithOtherLabelValidationRule = (function (_EqualityValidationRuleBase2) { _inherits(EqualityWithOtherLabelValidationRule, _EqualityValidationRuleBase2); function EqualityWithOtherLabelValidationRule(otherValue, otherLabel) { _classCallCheck(this, EqualityWithOtherLabelValidationRule); _EqualityValidationRuleBase2.call(this, otherValue, true, otherLabel, 'EqualityWithOtherLabelValidationRule'); } return EqualityWithOtherLabelValidationRule; })(EqualityValidationRuleBase); exports.EqualityWithOtherLabelValidationRule = EqualityWithOtherLabelValidationRule; var InEqualityValidationRule = (function (_EqualityValidationRuleBase3) { _inherits(InEqualityValidationRule, _EqualityValidationRuleBase3); function InEqualityValidationRule(otherValue) { _classCallCheck(this, InEqualityValidationRule); _EqualityValidationRuleBase3.call(this, otherValue, false, null, 'InEqualityValidationRule'); } return InEqualityValidationRule; })(EqualityValidationRuleBase); exports.InEqualityValidationRule = InEqualityValidationRule; var InEqualityWithOtherLabelValidationRule = (function (_EqualityValidationRuleBase4) { _inherits(InEqualityWithOtherLabelValidationRule, _EqualityValidationRuleBase4); function InEqualityWithOtherLabelValidationRule(otherValue, otherLabel) { _classCallCheck(this, InEqualityWithOtherLabelValidationRule); _EqualityValidationRuleBase4.call(this, otherValue, false, otherLabel, 'InEqualityWithOtherLabelValidationRule'); } return InEqualityWithOtherLabelValidationRule; })(EqualityValidationRuleBase); exports.InEqualityWithOtherLabelValidationRule = InEqualityWithOtherLabelValidationRule; var InCollectionValidationRule = (function (_ValidationRule22) { _inherits(InCollectionValidationRule, _ValidationRule22); function InCollectionValidationRule(startingCollection) { _classCallCheck(this, InCollectionValidationRule); _ValidationRule22.call(this, startingCollection, function (newValue, threshold) { var collection = _utilities.Utilities.getValue(threshold); for (var i = 0; i < collection.length; i++) { if (newValue === collection[i]) { return true; } } return false; }, null, 'InCollectionValidationRule'); } return InCollectionValidationRule; })(ValidationRule); exports.InCollectionValidationRule = InCollectionValidationRule; }); define('aurelia-validation/validation-group-builder',['exports', './validation-rules-collection', './validation-property', './validation-config', './validation-rules'], function (exports, _validationRulesCollection, _validationProperty, _validationConfig, _validationRules) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationGroupBuilder = (function () { function ValidationGroupBuilder(observerLocator, validationGroup) { _classCallCheck(this, ValidationGroupBuilder); this.observerLocator = observerLocator; this.validationRuleCollections = []; this.validationGroup = validationGroup; } ValidationGroupBuilder.prototype.ensure = function ensure(propertyName, configurationCallback) { var newValidationProperty = null; this.validationRuleCollections = []; for (var i = 0; i < this.validationGroup.validationProperties.length; i++) { if (this.validationGroup.validationProperties[i].propertyName === propertyName) { newValidationProperty = this.validationGroup.validationProperties[i]; if (configurationCallback !== undefined && typeof configurationCallback === 'function') { throw Error('When creating validation rules on binding path ' + propertyName + ' a configuration callback function was provided, but validation rules have previously already been instantiated for this binding path'); } break; } } if (newValidationProperty === null) { var propertyResult = this.validationGroup.result.addProperty(propertyName); var config = new _validationConfig.ValidationConfig(this.validationGroup.config); if (configurationCallback !== undefined && typeof configurationCallback === 'function') { configurationCallback(config); } newValidationProperty = new _validationProperty.ValidationProperty(this.observerLocator, propertyName, this.validationGroup, propertyResult, config); this.validationGroup.validationProperties.push(newValidationProperty); } this.validationRuleCollections.unshift(newValidationProperty.collectionOfValidationRules); return this.validationGroup; }; ValidationGroupBuilder.prototype.isNotEmpty = function isNotEmpty() { this.validationRuleCollections[0].isNotEmpty(); this.checkLast(); return this.validationGroup; }; ValidationGroupBuilder.prototype.canBeEmpty = function canBeEmpty() { this.validationRuleCollections[0].canBeEmpty(); this.checkLast(); return this.validationGroup; }; ValidationGroupBuilder.prototype.isGreaterThan = function isGreaterThan(minimumValue) { return this.passesRule(new _validationRules.MinimumValueValidationRule(minimumValue)); }; ValidationGroupBuilder.prototype.isGreaterThanOrEqualTo = function isGreaterThanOrEqualTo(minimumValue) { return this.passesRule(new _validationRules.MinimumInclusiveValueValidationRule(minimumValue)); }; ValidationGroupBuilder.prototype.isBetween = function isBetween(minimumValue, maximumValue) { return this.passesRule(new _validationRules.BetweenValueValidationRule(minimumValue, maximumValue)); }; ValidationGroupBuilder.prototype.isIn = function isIn(collection) { return this.passesRule(new _validationRules.InCollectionValidationRule(collection)); }; ValidationGroupBuilder.prototype.isLessThan = function isLessThan(maximumValue) { return this.passesRule(new _validationRules.MaximumValueValidationRule(maximumValue)); }; ValidationGroupBuilder.prototype.isLessThanOrEqualTo = function isLessThanOrEqualTo(maximumValue) { return this.passesRule(new _validationRules.MaximumInclusiveValueValidationRule(maximumValue)); }; ValidationGroupBuilder.prototype.isEqualTo = function isEqualTo(otherValue, otherValueLabel) { if (!otherValueLabel) { return this.passesRule(new _validationRules.EqualityValidationRule(otherValue)); } return this.passesRule(new _validationRules.EqualityWithOtherLabelValidationRule(otherValue, otherValueLabel)); }; ValidationGroupBuilder.prototype.isNotEqualTo = function isNotEqualTo(otherValue, otherValueLabel) { if (!otherValueLabel) { return this.passesRule(new _validationRules.InEqualityValidationRule(otherValue)); } return this.passesRule(new _validationRules.InEqualityWithOtherLabelValidationRule(otherValue, otherValueLabel)); }; ValidationGroupBuilder.prototype.isEmail = function isEmail() { return this.passesRule(new _validationRules.EmailValidationRule()); }; ValidationGroupBuilder.prototype.isURL = function isURL() { return this.passesRule(new _validationRules.URLValidationRule()); }; ValidationGroupBuilder.prototype.hasMinLength = function hasMinLength(minimumValue) { return this.passesRule(new _validationRules.MinimumLengthValidationRule(minimumValue)); }; ValidationGroupBuilder.prototype.hasMaxLength = function hasMaxLength(maximumValue) { return this.passesRule(new _validationRules.MaximumLengthValidationRule(maximumValue)); }; ValidationGroupBuilder.prototype.hasLengthBetween = function hasLengthBetween(minimumValue, maximumValue) { return this.passesRule(new _validationRules.BetweenLengthValidationRule(minimumValue, maximumValue)); }; ValidationGroupBuilder.prototype.isNumber = function isNumber() { return this.passesRule(new _validationRules.NumericValidationRule()); }; ValidationGroupBuilder.prototype.containsNoSpaces = function containsNoSpaces() { return this.passesRule(new _validationRules.NoSpacesValidationRule()); }; ValidationGroupBuilder.prototype.containsOnlyDigits = function containsOnlyDigits() { return this.passesRule(new _validationRules.DigitValidationRule()); }; ValidationGroupBuilder.prototype.containsOnlyAlpha = function containsOnlyAlpha() { return this.passesRule(new _validationRules.AlphaValidationRule()); }; ValidationGroupBuilder.prototype.containsOnlyAlphaOrWhitespace = function containsOnlyAlphaOrWhitespace() { return this.passesRule(new _validationRules.AlphaOrWhitespaceValidationRule()); }; ValidationGroupBuilder.prototype.containsOnlyAlphanumerics = function containsOnlyAlphanumerics() { return this.passesRule(new _validationRules.AlphaNumericValidationRule()); }; ValidationGroupBuilder.prototype.containsOnlyAlphanumericsOrWhitespace = function containsOnlyAlphanumericsOrWhitespace() { return this.passesRule(new _validationRules.AlphaNumericOrWhitespaceValidationRule()); }; ValidationGroupBuilder.prototype.isStrongPassword = function isStrongPassword(minimumComplexityLevel) { if (minimumComplexityLevel === 4) { return this.passesRule(new _validationRules.StrongPasswordValidationRule()); } return this.passesRule(new _validationRules.MediumPasswordValidationRule(minimumComplexityLevel)); }; ValidationGroupBuilder.prototype.containsOnly = function containsOnly(regex) { return this.passesRule(new _validationRules.ContainsOnlyValidationRule(regex)); }; ValidationGroupBuilder.prototype.matches = function matches(regex) { return this.passesRule(new _validationRules.RegexValidationRule(regex)); }; ValidationGroupBuilder.prototype.passes = function passes(customFunction, threshold) { return this.passesRule(new _validationRules.CustomFunctionValidationRule(customFunction, threshold)); }; ValidationGroupBuilder.prototype.passesRule = function passesRule(validationRule) { this.validationRuleCollections[0].addValidationRule(validationRule); this.checkLast(); return this.validationGroup; }; ValidationGroupBuilder.prototype.checkLast = function checkLast() { var validationProperty = this.validationGroup.validationProperties[this.validationGroup.validationProperties.length - 1]; validationProperty.validateCurrentValue(false); }; ValidationGroupBuilder.prototype.withMessage = function withMessage(message) { this.validationRuleCollections[0].withMessage(message); this.checkLast(); return this.validationGroup; }; ValidationGroupBuilder.prototype['if'] = function _if(conditionExpression) { var conditionalCollection = new _validationRulesCollection.SwitchCaseValidationRulesCollection(conditionExpression); conditionalCollection['case'](true); this.validationRuleCollections[0].addValidationRuleCollection(conditionalCollection); this.validationRuleCollections.unshift(conditionalCollection); return this.validationGroup; }; ValidationGroupBuilder.prototype['else'] = function _else() { if (!this.validationRuleCollections[0]['default']) { throw Error('Invalid statement: \'else\''); } this.validationRuleCollections[0]['default'](); return this.validationGroup; }; ValidationGroupBuilder.prototype.endIf = function endIf() { if (!this.validationRuleCollections[0]['default']) { throw Error('Invalid statement: \'endIf\''); } this.validationRuleCollections.shift(); this.checkLast(); return this.validationGroup; }; ValidationGroupBuilder.prototype['switch'] = function _switch(conditionExpression) { var _this = this; var condition = conditionExpression; if (condition === undefined) { (function () { var observer = _this.validationGroup.validationProperties[_this.validationGroup.validationProperties.length - 1].observer; condition = function () { return observer.getValue(); }; })(); } var conditionalCollection = new _validationRulesCollection.SwitchCaseValidationRulesCollection(condition); this.validationRuleCollections[0].addValidationRuleCollection(conditionalCollection); this.validationRuleCollections.unshift(conditionalCollection); return this.validationGroup; }; ValidationGroupBuilder.prototype['case'] = function _case(caseLabel) { if (!this.validationRuleCollections[0]['default']) { throw Error('Invalid statement: \'case\''); } this.validationRuleCollections[0]['case'](caseLabel); return this.validationGroup; }; ValidationGroupBuilder.prototype['default'] = function _default() { if (!this.validationRuleCollections[0]['default']) { throw Error('Invalid statement: \'case\''); } this.validationRuleCollections[0]['default'](); return this.validationGroup; }; ValidationGroupBuilder.prototype.endSwitch = function endSwitch() { if (!this.validationRuleCollections[0]['default']) { throw Error('Invalid statement: \'endIf\''); } this.validationRuleCollections.shift(); this.checkLast(); return this.validationGroup; }; return ValidationGroupBuilder; })(); exports.ValidationGroupBuilder = ValidationGroupBuilder; }); define('aurelia-validation/validation-result',['exports'], function (exports) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationResult = (function () { function ValidationResult() { _classCallCheck(this, ValidationResult); this.isValid = true; this.properties = {}; } ValidationResult.prototype.addProperty = function addProperty(name) { if (!this.properties[name]) { this.properties[name] = new ValidationResultProperty(this); } return this.properties[name]; }; ValidationResult.prototype.checkValidity = function checkValidity() { for (var propertyName in this.properties) { if (!this.properties[propertyName].isValid) { this.isValid = false; return; } } this.isValid = true; }; ValidationResult.prototype.clear = function clear() { this.isValid = true; }; return ValidationResult; })(); exports.ValidationResult = ValidationResult; var ValidationResultProperty = (function () { function ValidationResultProperty(group) { _classCallCheck(this, ValidationResultProperty); this.group = group; this.onValidateCallbacks = []; this.clear(); } ValidationResultProperty.prototype.clear = function clear() { this.isValid = true; this.isDirty = false; this.message = ''; this.failingRule = null; this.latestValue = null; this.notifyObserversOfChange(); }; ValidationResultProperty.prototype.onValidate = function onValidate(onValidateCallback) { this.onValidateCallbacks.push(onValidateCallback); }; ValidationResultProperty.prototype.notifyObserversOfChange = function notifyObserversOfChange() { for (var i = 0; i < this.onValidateCallbacks.length; i++) { var callback = this.onValidateCallbacks[i]; callback(this); } }; ValidationResultProperty.prototype.setValidity = function setValidity(validationResponse, shouldBeDirty) { var notifyObservers = !this.isDirty && shouldBeDirty || this.isValid !== validationResponse.isValid || this.message !== validationResponse.message; if (shouldBeDirty) { this.isDirty = true; } this.message = validationResponse.message; this.failingRule = validationResponse.failingRule; this.isValid = validationResponse.isValid; this.latestValue = validationResponse.latestValue; if (this.isValid !== this.group.isValid) { this.group.checkValidity(); } if (notifyObservers) { this.notifyObserversOfChange(); } }; return ValidationResultProperty; })(); exports.ValidationResultProperty = ValidationResultProperty; }); define('aurelia-validation/decorators',['exports', 'aurelia-metadata'], function (exports, _aureliaMetadata) { exports.__esModule = true; 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; }; })(); exports.ensure = ensure; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationMetadata = (function () { _createClass(ValidationMetadata, null, [{ key: 'metadataKey', value: 'aurelia:validation', enumerable: true }]); function ValidationMetadata() { _classCallCheck(this, ValidationMetadata); this.properties = []; } ValidationMetadata.prototype.getOrCreateProperty = function getOrCreateProperty(propertyName) { var property = this.properties.find(function (x) { return x.propertyName === propertyName; }); if (property === undefined) { property = new ValidationPropertyMetadata(propertyName); this.properties.push(property); } return property; }; ValidationMetadata.prototype.setup = function setup(validation) { this.properties.forEach(function (property) { property.setup(validation); }); }; return ValidationMetadata; })(); exports.ValidationMetadata = ValidationMetadata; var ValidationPropertyMetadata = (function () { function ValidationPropertyMetadata(propertyName) { _classCallCheck(this, ValidationPropertyMetadata); this.propertyName = propertyName; this.setupSteps = []; } ValidationPropertyMetadata.prototype.addSetupStep = function addSetupStep(setupStep) { this.setupSteps.push(setupStep); }; ValidationPropertyMetadata.prototype.setup = function setup(validation) { validation.ensure(this.propertyName); this.setupSteps.forEach(function (setupStep) { setupStep(validation); }); }; return ValidationPropertyMetadata; })(); function ensure(setupStep) { return function (target, propertyName) { var validationMetadata = _aureliaMetadata.metadata.getOrCreateOwn(ValidationMetadata.metadataKey, ValidationMetadata, target); var property = validationMetadata.getOrCreateProperty(propertyName); property.addSetupStep(setupStep); }; } }); define('aurelia-validation/validation-group',['exports', 'aurelia-metadata', './validation-group-builder', './validation-result', './decorators'], function (exports, _aureliaMetadata, _validationGroupBuilder, _validationResult, _decorators) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidationGroup = (function () { function ValidationGroup(subject, observerLocator, config) { var _this = this; _classCallCheck(this, ValidationGroup); var validationMetadata = undefined; this.result = new _validationResult.ValidationResult(); this.subject = subject; this.validationProperties = []; this.config = config; this.builder = new _validationGroupBuilder.ValidationGroupBuilder(observerLocator, this); this.onValidateCallbacks = []; this.onPropertyValidationCallbacks = []; this.isValidating = false; this.onDestroy = config.onLocaleChanged(function () { _this.validate(false, true); }); validationMetadata = _aureliaMetadata.metadata.getOwn(_decorators.ValidationMetadata.metadataKey, this.subject); if (validationMetadata) { validationMetadata.setup(this); } } ValidationGroup.prototype.destroy = function destroy() { this.validationProperties.forEach(function (prop) { prop.destroy(); }); this.onDestroy(); }; ValidationGroup.prototype.clear = function clear() { this.validationProperties.forEach(function (prop) { prop.clear(); }); this.result.clear(); }; ValidationGroup.prototype.onBreezeEntity = function onBreezeEntity() { var _this2 = this; var breezeEntity = this.subject; var me = this; var errors = undefined; this.onPropertyValidate(function (propertyBindingPath) { _this2.passes(function () { breezeEntity.entityAspect.validateProperty(propertyBindingPath); errors = breezeEntity.entityAspect.getValidationErrors(propertyBindingPath); if (errors.length === 0) { return true; } return errors[0].errorMessage; }); }); this.onValidate(function () { breezeEntity.entityAspect.validateEntity(); return {}; }); breezeEntity.entityAspect.validationErrorsChanged.subscribe(function () { breezeEntity.entityAspect.getValidationErrors().forEach(function (validationError) { var propertyName = validationError.propertyName; var currentResultProp = undefined; if (!me.result.properties[propertyName]) { me.ensure(propertyName); } currentResultProp = me.result.addProperty(propertyName); if (currentResultProp.isValid) { currentResultProp.setValidity({ isValid: false, message: validationError.errorMessage, failingRule: 'breeze', latestValue: currentResultProp.latestValue }, true); } }); }); }; ValidationGroup.prototype.validate = function validate() { var _this3 = this; var forceDirty = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; var forceExecution = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; this.isValidating = true; var promise = Promise.resolve(true); var _loop = function (i) { var validatorProperty = _this3.validationProperties[i]; promise = promise.then(function () { return validatorProperty.validateCurrentValue(forceDirty, forceExecution); }); }; for (var i = this.validationProperties.length - 1; i >= 0; i--) { _loop(i); } promise = promise['catch'](function () { throw Error('Should never get here: a validation property should always resolve to true/false!'); }); this.onValidateCallbacks.forEach(function (onValidateCallback) { promise = promise.then(function () { return _this3.config.locale(); }).then(function (locale) { return Promise.resolve(onValidateCallback.validationFunction()).then(function (callbackResult) { for (var prop in callbackResult) { var resultProp = undefined; var result = undefined; var newPropResult = undefined; if (!_this3.result.properties[prop]) { _this3.ensure(prop); } resultProp = _this3.result.addProperty(prop); result = callbackResult[prop]; newPropResult = { latestValue: resultProp.latestValue }; if (result === true || result === null || result === '') { if (!resultProp.isValid && resultProp.failingRule === 'onValidateCallback') { newPropResult.failingRule = null; newPropResult.message = ''; newPropResult.isValid = true; resultProp.setValidity(newPropResult, true); } } else { if (resultProp.isValid) { newPropResult.failingRule = 'onValidateCallback'; newPropResult.isValid = false; if (typeof result === 'string') { newPropResult.message = result; } else { newPropResult.message = locale.translate(newPropResult.failingRule); } resultProp.setValidity(newPropResult, true); } } } _this3.result.checkValidity(); }, function (a, b, c, d, e) { _this3.result.isValid = false; if (onValidateCallback.validationFunctionFailedCallback) { onValidateCallback.validationFunctionFailedCallback(a, b, c, d, e); } }); }); }); promise = promise.then(function () { _this3.isValidating = false; if (_this3.result.isValid) { return Promise.resolve(_this3.result); } return Promise.reject(_this3.result); }); return promise; }; ValidationGroup.prototype.onValidate = function onValidate(validationFunction, validationFunctionFailedCallback) { this.onValidateCallbacks.push({ validationFunction: validationFunction, validationFunctionFailedCallback: validationFunctionFailedCallback }); return this; }; ValidationGroup.prototype.onPropertyValidate = function onPropertyValidate(validationFunction) { this.onPropertyValidationCallbacks.push(validationFunction); return this; }; ValidationGroup.prototype.ensure = function ensure(bindingPath, configCallback) { this.builder.ensure(bindingPath, configCallback); this.onPropertyValidationCallbacks.forEach(function (callback) { callback(bindingPath); }); return this; }; ValidationGroup.prototype.isNotEmpty = function isNotEmpty() { return this.builder.isNotEmpty(); }; ValidationGroup.prototype.canBeEmpty = function canBeEmpty() { return this.builder.canBeEmpty(); }; ValidationGroup.prototype.isGreaterThanOrEqualTo = function isGreaterThanOrEqualTo(minimumValue) { return this.builder.isGreaterThanOrEqualTo(minimumValue); }; ValidationGroup.prototype.isGreaterThan = function isGreaterThan(minimumValue) { return this.builder.isGreaterThan(minimumValue); }; ValidationGroup.prototype.isBetween = function isBetween(minimumValue, maximumValue) { return this.builder.isBetween(minimumValue, maximumValue); }; ValidationGroup.prototype.isLessThanOrEqualTo = function isLessThanOrEqualTo(maximumValue) { return this.builder.isLessThanOrEqualTo(maximumValue); }; ValidationGroup.prototype.isLessThan = function isLessThan(maximumValue) { return this.builder.isLessThan(maximumValue); }; ValidationGroup.prototype.isEqualTo = function isEqualTo(otherValue, otherValueLabel) { return this.builder.isEqualTo(otherValue, otherValueLabel); }; ValidationGroup.prototype.isNotEqualTo = function isNotEqualTo(otherValue, otherValueLabel) { return this.builder.isNotEqualTo(otherValue, otherValueLabel); }; ValidationGroup.prototype.isEmail = function isEmail() { return this.builder.isEmail(); }; ValidationGroup.prototype.isURL = function isURL() { return this.builder.isURL(); }; ValidationGroup.prototype.isIn = function isIn(collection) { return this.builder.isIn(collection); }; ValidationGroup.prototype.hasMinLength = function hasMinLength(minimumValue) { return this.builder.hasMinLength(minimumValue); }; ValidationGroup.prototype.hasMaxLength = function hasMaxLength(maximumValue) { return this.builder.hasMaxLength(maximumValue); }; ValidationGroup.prototype.hasLengthBetween = function hasLengthBetween(minimumValue, maximumValue) { return this.builder.hasLengthBetween(minimumValue, maximumValue); }; ValidationGroup.prototype.isNumber = function isNumber() { return this.builder.isNumber(); }; ValidationGroup.prototype.containsNoSpaces = function containsNoSpaces() { return this.builder.containsNoSpaces(); }; ValidationGroup.prototype.containsOnlyDigits = function containsOnlyDigits() { return this.builder.containsOnlyDigits(); }; ValidationGroup.prototype.containsOnly = function containsOnly(regex) { return this.builder.containsOnly(regex); }; ValidationGroup.prototype.containsOnlyAlpha = function containsOnlyAlpha() { return this.builder.containsOnlyAlpha(); }; ValidationGroup.prototype.containsOnlyAlphaOrWhitespace = function containsOnlyAlphaOrWhitespace() { return this.builder.containsOnlyAlphaOrWhitespace(); }; ValidationGroup.prototype.containsOnlyLetters = function containsOnlyLetters() { return this.builder.containsOnlyAlpha(); }; ValidationGroup.prototype.containsOnlyLettersOrWhitespace = function containsOnlyLettersOrWhitespace() { return this.builder.containsOnlyAlphaOrWhitespace(); }; ValidationGroup.prototype.containsOnlyAlphanumerics = function containsOnlyAlphanumerics() { return this.builder.containsOnlyAlphanumerics(); }; ValidationGroup.prototype.containsOnlyAlphanumericsOrWhitespace = function containsOnlyAlphanumericsOrWhitespace() { return this.builder.containsOnlyAlphanumericsOrWhitespace(); }; ValidationGroup.prototype.isStrongPassword = function isStrongPassword(minimumComplexityLevel) { return this.builder.isStrongPassword(minimumComplexityLevel); }; ValidationGroup.prototype.matches = function matches(regex) { return this.builder.matches(regex); }; ValidationGroup.prototype.passes = function passes(customFunction, threshold) { return this.builder.passes(customFunction, threshold); }; ValidationGroup.prototype.passesRule = function passesRule(validationRule) { return this.builder.passesRule(validationRule); }; ValidationGroup.prototype['if'] = function _if(conditionExpression, threshold) { return this.builder['if'](conditionExpression, threshold); }; ValidationGroup.prototype['else'] = function _else() { return this.builder['else'](); }; ValidationGroup.prototype.endIf = function endIf() { return this.builder.endIf(); }; ValidationGroup.prototype['switch'] = function _switch(conditionExpression) { return this.builder['switch'](conditionExpression); }; ValidationGroup.prototype['case'] = function _case(caseLabel) { return this.builder['case'](caseLabel); }; ValidationGroup.prototype['default'] = function _default() { return this.builder['default'](); }; ValidationGroup.prototype.endSwitch = function endSwitch() { return this.builder.endSwitch(); }; ValidationGroup.prototype.withMessage = function withMessage(message) { return this.builder.withMessage(message); }; return ValidationGroup; })(); exports.ValidationGroup = ValidationGroup; }); define('aurelia-validation/validation',['exports', 'aurelia-binding', './validation-group', 'aurelia-dependency-injection', './validation-config'], function (exports, _aureliaBinding, _validationGroup, _aureliaDependencyInjection, _validationConfig) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Validation = (function () { function Validation(observerLocator, validationConfig) { _classCallCheck(this, _Validation); this.observerLocator = observerLocator; this.config = validationConfig ? validationConfig : Validation.defaults; } Validation.prototype.on = function on(subject, configCallback) { var conf = new _validationConfig.ValidationConfig(this.config); if (configCallback !== null && configCallback !== undefined && typeof configCallback === 'function') { configCallback(conf); } return new _validationGroup.ValidationGroup(subject, this.observerLocator, conf); }; Validation.prototype.onBreezeEntity = function onBreezeEntity(breezeEntity, configCallback) { var validation = this.on(breezeEntity, configCallback); validation.onBreezeEntity(); return validation; }; var _Validation = Validation; Validation = _aureliaDependencyInjection.inject(_aureliaBinding.ObserverLocator)(Validation) || Validation; return Validation; })(); exports.Validation = Validation; Validation.defaults = new _validationConfig.ValidationConfig(); }); define('aurelia-validation/validate-custom-attribute',['exports', 'aurelia-dependency-injection', 'aurelia-templating'], function (exports, _aureliaDependencyInjection, _aureliaTemplating) { exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ValidateCustomAttribute = (function () { function ValidateCustomAttribute(element) { _classCallCheck(this, _ValidateCustomAttribute); this.element = element; this.processedValidation = null; this.viewStrategy = null; } ValidateCustomAttribute.prototype.valueChanged = function valueChanged(newValue) { if (this.value === null || this.value === undefined) { return; } this.processedValidation = this.value; if (typeof this.value !== 'string') { this.subscribeChangedHandlers(this.element); } return; }; ValidateCustomAttribute.prototype.subscribeChangedHandlers = function subscribeChangedHandlers(currentElement) { var _this = this; var viewStrategy = this.value.config.getViewStrategy(); var validationProperty = viewStrategy.getValidationProperty(this.value, currentElement); var children = currentElement.children; this.viewStrategy = viewStrategy; if (validationProperty !== null && validationProperty !== undefined) { this.viewStrategy.prepareElement(validationProperty, currentElement); validationProperty.onValidate(function (vp) { _this.viewStrategy.updateElement(vp, currentElement); }); } for (var i = 0; i < children.length; i++) { this.subscribeChangedHandlers(children[i]); } }; ValidateCustomAttribute.prototype.attached = function attached() { if (this.processedValidation === null || this.processedValidation === undefined) { this.valueChanged(this.value); } }; var _ValidateCustomAttribute = ValidateCustomAttribute; ValidateCustomAttribute = _aureliaDependencyInjection.inject(Element)(ValidateCustomAttribute) || ValidateCustomAttribute; ValidateCustomAttribute = _aureliaTemplating.customAttribute('validate')(ValidateCustomAttribute) || ValidateCustomAttribute; return ValidateCustomAttribute; })(); exports.ValidateCustomAttribute = ValidateCustomAttribute; }); define('aurelia-validation/index',['exports', './validation-config', './validation', './utilities', './validation-locale', './validation-result', './validation-rules', './validation-group', './validate-custom-attribute', './validation-view-strategy', './strategies/twbootstrap-view-strategy', './decorators'], function (exports, _validationConfig, _validation, _utilities, _validationLocale, _validationResult, _validationRules, _validationGroup, _validateCustomAttribute, _validationViewStrategy, _strategiesTwbootstrapViewStrategy, _decorators) { exports.__esModule = true; exports.configure = configure; function _interopExportWildcard(obj, defaults) { var newObj = defaults({}, obj); delete newObj['default']; return newObj; } function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } exports.Utilities = _utilities.Utilities; exports.ValidationConfig = _validationConfig.ValidationConfig; exports.ValidationLocale = _validationLocale.ValidationLocale; _defaults(exports, _interopExportWildcard(_validationResult, _defaults)); _defaults(exports, _interopExportWildcard(_validationRules, _defaults)); exports.Validation = _validation.Validation; exports.ValidationGroup = _validationGroup.ValidationGroup; exports.ValidateCustomAttribute = _validateCustomAttribute.ValidateCustomAttribute; exports.ValidationViewStrategy = _validationViewStrategy.ValidationViewStrategy; exports.TWBootstrapViewStrategy = _strategiesTwbootstrapViewStrategy.TWBootstrapViewStrategy; exports.ensure = _decorators.ensure; function configure(aurelia, configCallback) { aurelia.globalResources('./validate-custom-attribute'); if (configCallback !== undefined && typeof configCallback === 'function') { configCallback(_validation.Validation.defaults); } aurelia.singleton(_validationConfig.ValidationConfig, _validation.Validation.defaults); return _validation.Validation.defaults.locale(); } }); define('aurelia-validation', ['aurelia-validation/index'], function (main) { return main; }); define('aurelia-animator-css',['exports', 'aurelia-templating', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaPal) { exports.__esModule = true; exports.configure = configure; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var CssAnimator = (function () { function CssAnimator() { _classCallCheck(this, CssAnimator); this.animationStack = []; this.useAnimationDoneClasses = false; this.animationEnteredClass = 'au-entered'; this.animationLeftClass = 'au-left'; this.isAnimating = false; this.animationTimeout = 50; } CssAnimator.prototype._addMultipleEventListener = function _addMultipleEventListener(el, s, fn) { var evts = s.split(' '); for (var i = 0, ii = evts.length; i < ii; ++i) { el.addEventListener(evts[i], fn, false); } }; CssAnimator.prototype._addAnimationToStack = function _addAnimationToStack(animId) { if (this.animationStack.indexOf(animId) < 0) { this.animationStack.push(animId); } }; CssAnimator.prototype._removeAnimationFromStack = function _removeAnimationFromStack(animId) { var idx = this.animationStack.indexOf(animId); if (idx > -1) { this.animationStack.splice(idx, 1); } }; CssAnimator.prototype._getElementAnimationDelay = function _getElementAnimationDelay(element) { var styl = _aureliaPal.DOM.getComputedStyle(element); var prop = undefined; var delay = undefined; if (styl.getPropertyValue('animation-delay')) { prop = 'animation-delay'; } else if (styl.getPropertyValue('-webkit-animation-delay')) { prop = '-webkit-animation-delay'; } else if (styl.getPropertyValue('-moz-animation-delay')) { prop = '-moz-animation-delay'; } else { return 0; } delay = styl.getPropertyValue(prop); delay = Number(delay.replace(/[^\d\.]/g, '')); return delay * 1000; }; CssAnimator.prototype._performSingleAnimate = function _performSingleAnimate(element, className) { var _this = this; this._triggerDOMEvent(_aureliaTemplating.animationEvent.animateBegin, element); return this.addClass(element, className, true).then(function (result) { _this._triggerDOMEvent(_aureliaTemplating.animationEvent.animateActive, element); if (result !== false) { return _this.removeClass(element, className, true).then(function () { _this._triggerDOMEvent(_aureliaTemplating.animationEvent.animateDone, element); }); } return false; })['catch'](function () { _this._triggerDOMEvent(_aureliaTemplating.animationEvent.animateTimeout, element); }); }; CssAnimator.prototype._triggerDOMEvent = function _triggerDOMEvent(eventType, element) { var evt = _aureliaPal.DOM.createCustomEvent(eventType, { bubbles: true, cancelable: true, detail: element }); _aureliaPal.DOM.dispatchEvent(evt); }; CssAnimator.prototype.animate = function animate(element, className) { var _this2 = this; if (Array.isArray(element)) { return Promise.all(element.map(function (el) { return _this2._performSingleAnimate(el, className); })); } return this._performSingleAnimate(element, className); }; CssAnimator.prototype.runSequence = function runSequence(animations) { var _this3 = this; this._triggerDOMEvent(_aureliaTemplating.animationEvent.sequenceBegin, null); return animations.reduce(function (p, anim) { return p.then(function () { return _this3.animate(anim.element, anim.className); }); }, Promise.resolve(true)).then(function () { _this3._triggerDOMEvent(_aureliaTemplating.animationEvent.sequenceDone, null); }); }; CssAnimator.prototype.enter = function enter(element) { var _this4 = this; return new Promise(function (resolve, reject) { var animId = element.toString() + Math.random(); var classList = element.classList; _this4._triggerDOMEvent(_aureliaTemplating.animationEvent.enterBegin, element); if (_this4.useAnimationDoneClasses) { classList.remove(_this4.animationEnteredClass); classList.remove(_this4.animationLeftClass); } classList.add('au-enter'); var animStart = undefined; _this4._addMultipleEventListener(element, 'webkitAnimationStart animationstart', animStart = function (evAnimStart) { _this4.isAnimating = true; _this4._triggerDOMEvent(_aureliaTemplating.animationEvent.enterActive, element); evAnimStart.stopPropagation(); _this4._addAnimationToStack(animId); var animEnd = undefined; _this4._addMultipleEventListener(element, 'webkitAnimationEnd animationend', animEnd = function (evAnimEnd) { evAnimEnd.stopPropagation(); classList.remove('au-enter-active'); classList.remove('au-enter'); _this4._removeAnimationFromStack(animId); evAnimEnd.target.removeEventListener(evAnimEnd.type, animEnd); if (_this4.useAnimationDoneClasses && _this4.animationEnteredClass !== undefined && _this4.animationEnteredClass !== null) { classList.add(_this4.animationEnteredClass); } _this4.isAnimating = false; _this4._triggerDOMEvent(_aureliaTemplating.animationEvent.enterDone, element); resolve(true); }, false); evAnimStart.target.removeEventListener(evAnimStart.type, animStart); }, false); var parent = element.parentElement; var delay = 0; if (parent !== null && parent !== undefined && (parent.classList.contains('au-stagger') || parent.classList.contains('au-stagger-enter'))) { var elemPos = Array.prototype.indexOf.call(parent.childNodes, element); delay = _this4._getElementAnimationDelay(parent) * elemPos; _this4._triggerDOMEvent(_aureliaTemplating.animationEvent.staggerNext, element); setTimeout(function () { classList.add('au-enter-active'); }, delay); } else { classList.add('au-enter-active'); } setTimeout(function () { if (_this4.animationStack.indexOf(animId) < 0) { classList.remove('au-enter-active'); classList.remove('au-enter'); _this4._triggerDOMEvent(_aureliaTemplating.animationEvent.enterTimeout, element); resolve(false); } }, _this4._getElementAnimationDelay(element) + _this4.animationTimeout + delay); }); }; CssAnimator.prototype.leave = function leave(element) { var _this5 = this; return new Promise(function (resolve, reject) { var animId = element.toString() + Math.random(); var classList = element.classList; _this5._triggerDOMEvent(_aureliaTemplating.animationEvent.leaveBegin, element); if (_this5.useAnimationDoneClasses) { classList.remove(_this5.animationEnteredClass); classList.remove(_this5.animationLeftClass); } classList.add('au-leave'); var animStart = undefined; _this5._addMultipleEventListener(element, 'webkitAnimationStart animationstart', animStart = function (evAnimStart) { _this5.isAnimating = true; _this5._triggerDOMEvent(_aureliaTemplating.animationEvent.leaveActive, element); evAnimStart.stopPropagation(); _this5._addAnimationToStack(animId); var animEnd = undefined; _this5._addMultipleEventListener(element, 'webkitAnimationEnd animationend', animEnd = function (evAnimEnd) { evAnimEnd.stopPropagation(); classList.remove('au-leave-active'); classList.remove('au-leave'); _this5._removeAnimationFromStack(animId); evAnimEnd.target.removeEventListener(evAnimEnd.type, animEnd); if (_this5.useAnimationDoneClasses && _this5.animationLeftClass !== undefined && _this5.animationLeftClass !== null) { classList.add(_this5.animationLeftClass); } _this5.isAnimating = false; _this5._triggerDOMEvent(_aureliaTemplating.animationEvent.leaveDone, element); resolve(true); }, false); evAnimStart.target.removeEventListener(evAnimStart.type, animStart); }, false); var parent = element.parentElement; var delay = 0; if (parent !== null && parent !== undefined && (parent.classList.contains('au-stagger') || parent.classList.contains('au-stagger-leave'))) { var elemPos = Array.prototype.indexOf.call(parent.childNodes, element); delay = _this5._getElementAnimationDelay(parent) * elemPos; _this5._triggerDOMEvent(_aureliaTemplating.animationEvent.staggerNext, element); setTimeout(function () { classList.add('au-leave-active'); }, delay); } else { classList.add('au-leave-active'); } setTimeout(function () { if (_this5.animationStack.indexOf(animId) < 0) { classList.remove('au-leave-active'); classList.remove('au-leave'); _this5._triggerDOMEvent(_aureliaTemplating.animationEvent.leaveTimeout, element); resolve(false); } }, _this5._getElementAnimationDelay(element) + _this5.animationTimeout + delay); }); }; CssAnimator.prototype.removeClass = function removeClass(element, className) { var _this6 = this; var suppressEvents = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; return new Promise(function (resolve, reject) { var classList = element.classList; if (!classList.contains(className) && !classList.contains(className + '-add')) { resolve(false); return; } if (suppressEvents !== true) { _this6._triggerDOMEvent(_aureliaTemplating.animationEvent.removeClassBegin, element); } var animId = element.toString() + className + Math.random(); classList.remove(className); var animStart = undefined; _this6._addMultipleEventListener(element, 'webkitAnimationStart animationstart', animStart = function (evAnimStart) { _this6.isAnimating = true; if (suppressEvents !== true) { _this6._triggerDOMEvent(_aureliaTemplating.animationEvent.removeClassActive, element); } evAnimStart.stopPropagation(); _this6._addAnimationToStack(animId); var animEnd = undefined; _this6._addMultipleEventListener(element, 'webkitAnimationEnd animationend', animEnd = function (evAnimEnd) { evAnimEnd.stopPropagation(); classList.remove(className + '-remove'); _this6._removeAnimationFromStack(animId); evAnimEnd.target.removeEventListener(evAnimEnd.type, animEnd); _this6.isAnimating = false; if (suppressEvents !== true) { _this6._triggerDOMEvent(_aureliaTemplating.animationEvent.removeClassDone, element); } resolve(true); }, false); evAnimStart.target.removeEventListener(evAnimStart.type, animStart); }, false); classList.add(className + '-remove'); setTimeout(function () { if (_this6.animationStack.indexOf(animId) < 0) { classList.remove(className + '-remove'); classList.remove(className); if (suppressEvents !== true) { _this6._triggerDOMEvent(_aureliaTemplating.animationEvent.removeClassTimeout, element); } resolve(false); } }, _this6._getElementAnimationDelay(element) + _this6.animationTimeout); }); }; CssAnimator.prototype.addClass = function addClass(element, className) { var _this7 = this; var suppressEvents = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; return new Promise(function (resolve, reject) { var animId = element.toString() + className + Math.random(); var classList = element.classList; if (suppressEvents !== true) { _this7._triggerDOMEvent(_aureliaTemplating.animationEvent.addClassBegin, element); } var animStart = undefined; _this7._addMultipleEventListener(element, 'webkitAnimationStart animationstart', animStart = function (evAnimStart) { _this7.isAnimating = true; if (suppressEvents !== true) { _this7._triggerDOMEvent(_aureliaTemplating.animationEvent.addClassActive, element); } evAnimStart.stopPropagation(); _this7._addAnimationToStack(animId); var animEnd = undefined; _this7._addMultipleEventListener(element, 'webkitAnimationEnd animationend', animEnd = function (evAnimEnd) { evAnimEnd.stopPropagation(); classList.add(className); classList.remove(className + '-add'); _this7._removeAnimationFromStack(animId); evAnimEnd.target.removeEventListener(evAnimEnd.type, animEnd); _this7.isAnimating = false; if (suppressEvents !== true) { _this7._triggerDOMEvent(_aureliaTemplating.animationEvent.addClassDone, element); } resolve(true); }, false); evAnimStart.target.removeEventListener(evAnimStart.type, animStart); }, false); classList.add(className + '-add'); setTimeout(function () { if (_this7.animationStack.indexOf(animId) < 0) { classList.remove(className + '-add'); classList.add(className); if (suppressEvents !== true) { _this7._triggerDOMEvent(_aureliaTemplating.animationEvent.addClassTimeout, element); } resolve(false); } }, _this7._getElementAnimationDelay(element) + _this7.animationTimeout); }); }; return CssAnimator; })(); exports.CssAnimator = CssAnimator; function configure(config, callback) { var animator = config.container.get(CssAnimator); config.container.get(_aureliaTemplating.TemplatingEngine).configureAnimator(animator); if (typeof callback === 'function') { callback(animator); } } }); /*! VelocityJS.org (1.2.3). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */ /*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */ !function(a){function b(a){var b=a.length,d=c.type(a);return"function"===d||c.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===d||0===b||"number"==typeof b&&b>0&&b-1 in a}if(!a.jQuery){var c=function(a,b){return new c.fn.init(a,b)};c.isWindow=function(a){return null!=a&&a==a.window},c.type=function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?e[g.call(a)]||"object":typeof a},c.isArray=Array.isArray||function(a){return"array"===c.type(a)},c.isPlainObject=function(a){var b;if(!a||"object"!==c.type(a)||a.nodeType||c.isWindow(a))return!1;try{if(a.constructor&&!f.call(a,"constructor")&&!f.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(d){return!1}for(b in a);return void 0===b||f.call(a,b)},c.each=function(a,c,d){var e,f=0,g=a.length,h=b(a);if(d){if(h)for(;g>f&&(e=c.apply(a[f],d),e!==!1);f++);else for(f in a)if(e=c.apply(a[f],d),e===!1)break}else if(h)for(;g>f&&(e=c.call(a[f],f,a[f]),e!==!1);f++);else for(f in a)if(e=c.call(a[f],f,a[f]),e===!1)break;return a},c.data=function(a,b,e){if(void 0===e){var f=a[c.expando],g=f&&d[f];if(void 0===b)return g;if(g&&b in g)return g[b]}else if(void 0!==b){var f=a[c.expando]||(a[c.expando]=++c.uuid);return d[f]=d[f]||{},d[f][b]=e,e}},c.removeData=function(a,b){var e=a[c.expando],f=e&&d[e];f&&c.each(b,function(a,b){delete f[b]})},c.extend=function(){var a,b,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;for("boolean"==typeof h&&(k=h,h=arguments[i]||{},i++),"object"!=typeof h&&"function"!==c.type(h)&&(h={}),i===j&&(h=this,i--);j>i;i++)if(null!=(f=arguments[i]))for(e in f)a=h[e],d=f[e],h!==d&&(k&&d&&(c.isPlainObject(d)||(b=c.isArray(d)))?(b?(b=!1,g=a&&c.isArray(a)?a:[]):g=a&&c.isPlainObject(a)?a:{},h[e]=c.extend(k,g,d)):void 0!==d&&(h[e]=d));return h},c.queue=function(a,d,e){function f(a,c){var d=c||[];return null!=a&&(b(Object(a))?!function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;)a[e++]=b[d++];if(c!==c)for(;void 0!==b[d];)a[e++]=b[d++];return a.length=e,a}(d,"string"==typeof a?[a]:a):[].push.call(d,a)),d}if(a){d=(d||"fx")+"queue";var g=c.data(a,d);return e?(!g||c.isArray(e)?g=c.data(a,d,f(e)):g.push(e),g):g||[]}},c.dequeue=function(a,b){c.each(a.nodeType?[a]:a,function(a,d){b=b||"fx";var e=c.queue(d,b),f=e.shift();"inprogress"===f&&(f=e.shift()),f&&("fx"===b&&e.unshift("inprogress"),f.call(d,function(){c.dequeue(d,b)}))})},c.fn=c.prototype={init:function(a){if(a.nodeType)return this[0]=a,this;throw new Error("Not a DOM node.")},offset:function(){var b=this[0].getBoundingClientRect?this[0].getBoundingClientRect():{top:0,left:0};return{top:b.top+(a.pageYOffset||document.scrollTop||0)-(document.clientTop||0),left:b.left+(a.pageXOffset||document.scrollLeft||0)-(document.clientLeft||0)}},position:function(){function a(){for(var a=this.offsetParent||document;a&&"html"===!a.nodeType.toLowerCase&&"static"===a.style.position;)a=a.offsetParent;return a||document}var b=this[0],a=a.apply(b),d=this.offset(),e=/^(?:body|html)$/i.test(a.nodeName)?{top:0,left:0}:c(a).offset();return d.top-=parseFloat(b.style.marginTop)||0,d.left-=parseFloat(b.style.marginLeft)||0,a.style&&(e.top+=parseFloat(a.style.borderTopWidth)||0,e.left+=parseFloat(a.style.borderLeftWidth)||0),{top:d.top-e.top,left:d.left-e.left}}};var d={};c.expando="velocity"+(new Date).getTime(),c.uuid=0;for(var e={},f=e.hasOwnProperty,g=e.toString,h="Boolean Number String Function Array Date RegExp Object Error".split(" "),i=0;i<h.length;i++)e["[object "+h[i]+"]"]=h[i].toLowerCase();c.fn.init.prototype=c.fn,a.Velocity={Utilities:c}}}(window),function(a){"object"==typeof module&&"object"==typeof module.exports?module.exports=a():"function"==typeof define&&define.amd?define('velocity/velocity.min',a):a()}(function(){return function(a,b,c,d){function e(a){for(var b=-1,c=a?a.length:0,d=[];++b<c;){var e=a[b];e&&d.push(e)}return d}function f(a){return p.isWrapped(a)?a=[].slice.call(a):p.isNode(a)&&(a=[a]),a}function g(a){var b=m.data(a,"velocity");return null===b?d:b}function h(a){return function(b){return Math.round(b*a)*(1/a)}}function i(a,c,d,e){function f(a,b){return 1-3*b+3*a}function g(a,b){return 3*b-6*a}function h(a){return 3*a}function i(a,b,c){return((f(b,c)*a+g(b,c))*a+h(b))*a}function j(a,b,c){return 3*f(b,c)*a*a+2*g(b,c)*a+h(b)}function k(b,c){for(var e=0;p>e;++e){var f=j(c,a,d);if(0===f)return c;var g=i(c,a,d)-b;c-=g/f}return c}function l(){for(var b=0;t>b;++b)x[b]=i(b*u,a,d)}function m(b,c,e){var f,g,h=0;do g=c+(e-c)/2,f=i(g,a,d)-b,f>0?e=g:c=g;while(Math.abs(f)>r&&++h<s);return g}function n(b){for(var c=0,e=1,f=t-1;e!=f&&x[e]<=b;++e)c+=u;--e;var g=(b-x[e])/(x[e+1]-x[e]),h=c+g*u,i=j(h,a,d);return i>=q?k(b,h):0==i?h:m(b,c,c+u)}function o(){y=!0,(a!=c||d!=e)&&l()}var p=4,q=.001,r=1e-7,s=10,t=11,u=1/(t-1),v="Float32Array"in b;if(4!==arguments.length)return!1;for(var w=0;4>w;++w)if("number"!=typeof arguments[w]||isNaN(arguments[w])||!isFinite(arguments[w]))return!1;a=Math.min(a,1),d=Math.min(d,1),a=Math.max(a,0),d=Math.max(d,0);var x=v?new Float32Array(t):new Array(t),y=!1,z=function(b){return y||o(),a===c&&d===e?b:0===b?0:1===b?1:i(n(b),c,e)};z.getControlPoints=function(){return[{x:a,y:c},{x:d,y:e}]};var A="generateBezier("+[a,c,d,e]+")";return z.toString=function(){return A},z}function j(a,b){var c=a;return p.isString(a)?t.Easings[a]||(c=!1):c=p.isArray(a)&&1===a.length?h.apply(null,a):p.isArray(a)&&2===a.length?u.apply(null,a.concat([b])):p.isArray(a)&&4===a.length?i.apply(null,a):!1,c===!1&&(c=t.Easings[t.defaults.easing]?t.defaults.easing:s),c}function k(a){if(a){var b=(new Date).getTime(),c=t.State.calls.length;c>1e4&&(t.State.calls=e(t.State.calls));for(var f=0;c>f;f++)if(t.State.calls[f]){var h=t.State.calls[f],i=h[0],j=h[2],n=h[3],o=!!n,q=null;n||(n=t.State.calls[f][3]=b-16);for(var r=Math.min((b-n)/j.duration,1),s=0,u=i.length;u>s;s++){var w=i[s],y=w.element;if(g(y)){var z=!1;if(j.display!==d&&null!==j.display&&"none"!==j.display){if("flex"===j.display){var A=["-webkit-box","-moz-box","-ms-flexbox","-webkit-flex"];m.each(A,function(a,b){v.setPropertyValue(y,"display",b)})}v.setPropertyValue(y,"display",j.display)}j.visibility!==d&&"hidden"!==j.visibility&&v.setPropertyValue(y,"visibility",j.visibility);for(var B in w)if("element"!==B){var C,D=w[B],E=p.isString(D.easing)?t.Easings[D.easing]:D.easing;if(1===r)C=D.endValue;else{var F=D.endValue-D.startValue;if(C=D.startValue+F*E(r,j,F),!o&&C===D.currentValue)continue}if(D.currentValue=C,"tween"===B)q=C;else{if(v.Hooks.registered[B]){var G=v.Hooks.getRoot(B),H=g(y).rootPropertyValueCache[G];H&&(D.rootPropertyValue=H)}var I=v.setPropertyValue(y,B,D.currentValue+(0===parseFloat(C)?"":D.unitType),D.rootPropertyValue,D.scrollData);v.Hooks.registered[B]&&(g(y).rootPropertyValueCache[G]=v.Normalizations.registered[G]?v.Normalizations.registered[G]("extract",null,I[1]):I[1]),"transform"===I[0]&&(z=!0)}}j.mobileHA&&g(y).transformCache.translate3d===d&&(g(y).transformCache.translate3d="(0px, 0px, 0px)",z=!0),z&&v.flushTransformCache(y)}}j.display!==d&&"none"!==j.display&&(t.State.calls[f][2].display=!1),j.visibility!==d&&"hidden"!==j.visibility&&(t.State.calls[f][2].visibility=!1),j.progress&&j.progress.call(h[1],h[1],r,Math.max(0,n+j.duration-b),n,q),1===r&&l(f)}}t.State.isTicking&&x(k)}function l(a,b){if(!t.State.calls[a])return!1;for(var c=t.State.calls[a][0],e=t.State.calls[a][1],f=t.State.calls[a][2],h=t.State.calls[a][4],i=!1,j=0,k=c.length;k>j;j++){var l=c[j].element;if(b||f.loop||("none"===f.display&&v.setPropertyValue(l,"display",f.display),"hidden"===f.visibility&&v.setPropertyValue(l,"visibility",f.visibility)),f.loop!==!0&&(m.queue(l)[1]===d||!/\.velocityQueueEntryFlag/i.test(m.queue(l)[1]))&&g(l)){g(l).isAnimating=!1,g(l).rootPropertyValueCache={};var n=!1;m.each(v.Lists.transforms3D,function(a,b){var c=/^scale/.test(b)?1:0,e=g(l).transformCache[b];g(l).transformCache[b]!==d&&new RegExp("^\\("+c+"[^.]").test(e)&&(n=!0,delete g(l).transformCache[b])}),f.mobileHA&&(n=!0,delete g(l).transformCache.translate3d),n&&v.flushTransformCache(l),v.Values.removeClass(l,"velocity-animating")}if(!b&&f.complete&&!f.loop&&j===k-1)try{f.complete.call(e,e)}catch(o){setTimeout(function(){throw o},1)}h&&f.loop!==!0&&h(e),g(l)&&f.loop===!0&&!b&&(m.each(g(l).tweensContainer,function(a,b){/^rotate/.test(a)&&360===parseFloat(b.endValue)&&(b.endValue=0,b.startValue=360),/^backgroundPosition/.test(a)&&100===parseFloat(b.endValue)&&"%"===b.unitType&&(b.endValue=0,b.startValue=100)}),t(l,"reverse",{loop:!0,delay:f.delay})),f.queue!==!1&&m.dequeue(l,f.queue)}t.State.calls[a]=!1;for(var p=0,q=t.State.calls.length;q>p;p++)if(t.State.calls[p]!==!1){i=!0;break}i===!1&&(t.State.isTicking=!1,delete t.State.calls,t.State.calls=[])}var m,n=function(){if(c.documentMode)return c.documentMode;for(var a=7;a>4;a--){var b=c.createElement("div");if(b.innerHTML="<!--[if IE "+a+"]><span></span><![endif]-->",b.getElementsByTagName("span").length)return b=null,a}return d}(),o=function(){var a=0;return b.webkitRequestAnimationFrame||b.mozRequestAnimationFrame||function(b){var c,d=(new Date).getTime();return c=Math.max(0,16-(d-a)),a=d+c,setTimeout(function(){b(d+c)},c)}}(),p={isString:function(a){return"string"==typeof a},isArray:Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},isFunction:function(a){return"[object Function]"===Object.prototype.toString.call(a)},isNode:function(a){return a&&a.nodeType},isNodeList:function(a){return"object"==typeof a&&/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(a))&&a.length!==d&&(0===a.length||"object"==typeof a[0]&&a[0].nodeType>0)},isWrapped:function(a){return a&&(a.jquery||b.Zepto&&b.Zepto.zepto.isZ(a))},isSVG:function(a){return b.SVGElement&&a instanceof b.SVGElement},isEmptyObject:function(a){for(var b in a)return!1;return!0}},q=!1;if(a.fn&&a.fn.jquery?(m=a,q=!0):m=b.Velocity.Utilities,8>=n&&!q)throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity.");if(7>=n)return void(jQuery.fn.velocity=jQuery.fn.animate);var r=400,s="swing",t={State:{isMobile:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),isAndroid:/Android/i.test(navigator.userAgent),isGingerbread:/Android 2\.3\.[3-7]/i.test(navigator.userAgent),isChrome:b.chrome,isFirefox:/Firefox/i.test(navigator.userAgent),prefixElement:c.createElement("div"),prefixMatches:{},scrollAnchor:null,scrollPropertyLeft:null,scrollPropertyTop:null,isTicking:!1,calls:[]},CSS:{},Utilities:m,Redirects:{},Easings:{},Promise:b.Promise,defaults:{queue:"",duration:r,easing:s,begin:d,complete:d,progress:d,display:d,visibility:d,loop:!1,delay:!1,mobileHA:!0,_cacheValues:!0},init:function(a){m.data(a,"velocity",{isSVG:p.isSVG(a),isAnimating:!1,computedStyle:null,tweensContainer:null,rootPropertyValueCache:{},transformCache:{}})},hook:null,mock:!1,version:{major:1,minor:2,patch:2},debug:!1};b.pageYOffset!==d?(t.State.scrollAnchor=b,t.State.scrollPropertyLeft="pageXOffset",t.State.scrollPropertyTop="pageYOffset"):(t.State.scrollAnchor=c.documentElement||c.body.parentNode||c.body,t.State.scrollPropertyLeft="scrollLeft",t.State.scrollPropertyTop="scrollTop");var u=function(){function a(a){return-a.tension*a.x-a.friction*a.v}function b(b,c,d){var e={x:b.x+d.dx*c,v:b.v+d.dv*c,tension:b.tension,friction:b.friction};return{dx:e.v,dv:a(e)}}function c(c,d){var e={dx:c.v,dv:a(c)},f=b(c,.5*d,e),g=b(c,.5*d,f),h=b(c,d,g),i=1/6*(e.dx+2*(f.dx+g.dx)+h.dx),j=1/6*(e.dv+2*(f.dv+g.dv)+h.dv);return c.x=c.x+i*d,c.v=c.v+j*d,c}return function d(a,b,e){var f,g,h,i={x:-1,v:0,tension:null,friction:null},j=[0],k=0,l=1e-4,m=.016;for(a=parseFloat(a)||500,b=parseFloat(b)||20,e=e||null,i.tension=a,i.friction=b,f=null!==e,f?(k=d(a,b),g=k/e*m):g=m;;)if(h=c(h||i,g),j.push(1+h.x),k+=16,!(Math.abs(h.x)>l&&Math.abs(h.v)>l))break;return f?function(a){return j[a*(j.length-1)|0]}:k}}();t.Easings={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},spring:function(a){return 1-Math.cos(4.5*a*Math.PI)*Math.exp(6*-a)}},m.each([["ease",[.25,.1,.25,1]],["ease-in",[.42,0,1,1]],["ease-out",[0,0,.58,1]],["ease-in-out",[.42,0,.58,1]],["easeInSine",[.47,0,.745,.715]],["easeOutSine",[.39,.575,.565,1]],["easeInOutSine",[.445,.05,.55,.95]],["easeInQuad",[.55,.085,.68,.53]],["easeOutQuad",[.25,.46,.45,.94]],["easeInOutQuad",[.455,.03,.515,.955]],["easeInCubic",[.55,.055,.675,.19]],["easeOutCubic",[.215,.61,.355,1]],["easeInOutCubic",[.645,.045,.355,1]],["easeInQuart",[.895,.03,.685,.22]],["easeOutQuart",[.165,.84,.44,1]],["easeInOutQuart",[.77,0,.175,1]],["easeInQuint",[.755,.05,.855,.06]],["easeOutQuint",[.23,1,.32,1]],["easeInOutQuint",[.86,0,.07,1]],["easeInExpo",[.95,.05,.795,.035]],["easeOutExpo",[.19,1,.22,1]],["easeInOutExpo",[1,0,0,1]],["easeInCirc",[.6,.04,.98,.335]],["easeOutCirc",[.075,.82,.165,1]],["easeInOutCirc",[.785,.135,.15,.86]]],function(a,b){t.Easings[b[0]]=i.apply(null,b[1])});var v=t.CSS={RegEx:{isHex:/^#([A-f\d]{3}){1,2}$/i,valueUnwrap:/^[A-z]+\((.*)\)$/i,wrappedValueAlreadyExtracted:/[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,valueSplit:/([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/gi},Lists:{colors:["fill","stroke","stopColor","color","backgroundColor","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor","outlineColor"],transformsBase:["translateX","translateY","scale","scaleX","scaleY","skewX","skewY","rotateZ"],transforms3D:["transformPerspective","translateZ","scaleZ","rotateX","rotateY"]},Hooks:{templates:{textShadow:["Color X Y Blur","black 0px 0px 0px"],boxShadow:["Color X Y Blur Spread","black 0px 0px 0px 0px"],clip:["Top Right Bottom Left","0px 0px 0px 0px"],backgroundPosition:["X Y","0% 0%"],transformOrigin:["X Y Z","50% 50% 0px"],perspectiveOrigin:["X Y","50% 50%"]},registered:{},register:function(){for(var a=0;a<v.Lists.colors.length;a++){var b="color"===v.Lists.colors[a]?"0 0 0 1":"255 255 255 1";v.Hooks.templates[v.Lists.colors[a]]=["Red Green Blue Alpha",b]}var c,d,e;if(n)for(c in v.Hooks.templates){d=v.Hooks.templates[c],e=d[0].split(" ");var f=d[1].match(v.RegEx.valueSplit);"Color"===e[0]&&(e.push(e.shift()),f.push(f.shift()),v.Hooks.templates[c]=[e.join(" "),f.join(" ")])}for(c in v.Hooks.templates){d=v.Hooks.templates[c],e=d[0].split(" ");for(var a in e){var g=c+e[a],h=a;v.Hooks.registered[g]=[c,h]}}},getRoot:function(a){var b=v.Hooks.registered[a];return b?b[0]:a},cleanRootPropertyValue:function(a,b){return v.RegEx.valueUnwrap.test(b)&&(b=b.match(v.RegEx.valueUnwrap)[1]),v.Values.isCSSNullValue(b)&&(b=v.Hooks.templates[a][1]),b},extractValue:function(a,b){var c=v.Hooks.registered[a];if(c){var d=c[0],e=c[1];return b=v.Hooks.cleanRootPropertyValue(d,b),b.toString().match(v.RegEx.valueSplit)[e]}return b},injectValue:function(a,b,c){var d=v.Hooks.registered[a];if(d){var e,f,g=d[0],h=d[1];return c=v.Hooks.cleanRootPropertyValue(g,c),e=c.toString().match(v.RegEx.valueSplit),e[h]=b,f=e.join(" ")}return c}},Normalizations:{registered:{clip:function(a,b,c){switch(a){case"name":return"clip";case"extract":var d;return v.RegEx.wrappedValueAlreadyExtracted.test(c)?d=c:(d=c.toString().match(v.RegEx.valueUnwrap),d=d?d[1].replace(/,(\s+)?/g," "):c),d;case"inject":return"rect("+c+")"}},blur:function(a,b,c){switch(a){case"name":return t.State.isFirefox?"filter":"-webkit-filter";case"extract":var d=parseFloat(c);if(!d&&0!==d){var e=c.toString().match(/blur\(([0-9]+[A-z]+)\)/i);d=e?e[1]:0}return d;case"inject":return parseFloat(c)?"blur("+c+")":"none"}},opacity:function(a,b,c){if(8>=n)switch(a){case"name":return"filter";case"extract":var d=c.toString().match(/alpha\(opacity=(.*)\)/i);return c=d?d[1]/100:1;case"inject":return b.style.zoom=1,parseFloat(c)>=1?"":"alpha(opacity="+parseInt(100*parseFloat(c),10)+")"}else switch(a){case"name":return"opacity";case"extract":return c;case"inject":return c}}},register:function(){9>=n||t.State.isGingerbread||(v.Lists.transformsBase=v.Lists.transformsBase.concat(v.Lists.transforms3D));for(var a=0;a<v.Lists.transformsBase.length;a++)!function(){var b=v.Lists.transformsBase[a];v.Normalizations.registered[b]=function(a,c,e){switch(a){case"name":return"transform";case"extract":return g(c)===d||g(c).transformCache[b]===d?/^scale/i.test(b)?1:0:g(c).transformCache[b].replace(/[()]/g,"");case"inject":var f=!1;switch(b.substr(0,b.length-1)){case"translate":f=!/(%|px|em|rem|vw|vh|\d)$/i.test(e);break;case"scal":case"scale":t.State.isAndroid&&g(c).transformCache[b]===d&&1>e&&(e=1),f=!/(\d)$/i.test(e);break;case"skew":f=!/(deg|\d)$/i.test(e);break;case"rotate":f=!/(deg|\d)$/i.test(e)}return f||(g(c).transformCache[b]="("+e+")"),g(c).transformCache[b]}}}();for(var a=0;a<v.Lists.colors.length;a++)!function(){var b=v.Lists.colors[a];v.Normalizations.registered[b]=function(a,c,e){switch(a){case"name":return b;case"extract":var f;if(v.RegEx.wrappedValueAlreadyExtracted.test(e))f=e;else{var g,h={black:"rgb(0, 0, 0)",blue:"rgb(0, 0, 255)",gray:"rgb(128, 128, 128)",green:"rgb(0, 128, 0)",red:"rgb(255, 0, 0)",white:"rgb(255, 255, 255)"};/^[A-z]+$/i.test(e)?g=h[e]!==d?h[e]:h.black:v.RegEx.isHex.test(e)?g="rgb("+v.Values.hexToRgb(e).join(" ")+")":/^rgba?\(/i.test(e)||(g=h.black),f=(g||e).toString().match(v.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g," ")}return 8>=n||3!==f.split(" ").length||(f+=" 1"),f;case"inject":return 8>=n?4===e.split(" ").length&&(e=e.split(/\s+/).slice(0,3).join(" ")):3===e.split(" ").length&&(e+=" 1"),(8>=n?"rgb":"rgba")+"("+e.replace(/\s+/g,",").replace(/\.(\d)+(?=,)/g,"")+")"}}}()}},Names:{camelCase:function(a){return a.replace(/-(\w)/g,function(a,b){return b.toUpperCase()})},SVGAttribute:function(a){var b="width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2";return(n||t.State.isAndroid&&!t.State.isChrome)&&(b+="|transform"),new RegExp("^("+b+")$","i").test(a)},prefixCheck:function(a){if(t.State.prefixMatches[a])return[t.State.prefixMatches[a],!0];for(var b=["","Webkit","Moz","ms","O"],c=0,d=b.length;d>c;c++){var e;if(e=0===c?a:b[c]+a.replace(/^\w/,function(a){return a.toUpperCase()}),p.isString(t.State.prefixElement.style[e]))return t.State.prefixMatches[a]=e,[e,!0]}return[a,!1]}},Values:{hexToRgb:function(a){var b,c=/^#?([a-f\d])([a-f\d])([a-f\d])$/i,d=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;return a=a.replace(c,function(a,b,c,d){return b+b+c+c+d+d}),b=d.exec(a),b?[parseInt(b[1],16),parseInt(b[2],16),parseInt(b[3],16)]:[0,0,0]},isCSSNullValue:function(a){return 0==a||/^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(a)},getUnitType:function(a){return/^(rotate|skew)/i.test(a)?"deg":/(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(a)?"":"px"},getDisplayType:function(a){var b=a&&a.tagName.toString().toLowerCase();return/^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(b)?"inline":/^(li)$/i.test(b)?"list-item":/^(tr)$/i.test(b)?"table-row":/^(table)$/i.test(b)?"table":/^(tbody)$/i.test(b)?"table-row-group":"block"},addClass:function(a,b){a.classList?a.classList.add(b):a.className+=(a.className.length?" ":"")+b},removeClass:function(a,b){a.classList?a.classList.remove(b):a.className=a.className.toString().replace(new RegExp("(^|\\s)"+b.split(" ").join("|")+"(\\s|$)","gi")," ")}},getPropertyValue:function(a,c,e,f){function h(a,c){function e(){j&&v.setPropertyValue(a,"display","none")}var i=0;if(8>=n)i=m.css(a,c);else{var j=!1;if(/^(width|height)$/.test(c)&&0===v.getPropertyValue(a,"display")&&(j=!0,v.setPropertyValue(a,"display",v.Values.getDisplayType(a))),!f){if("height"===c&&"border-box"!==v.getPropertyValue(a,"boxSizing").toString().toLowerCase()){var k=a.offsetHeight-(parseFloat(v.getPropertyValue(a,"borderTopWidth"))||0)-(parseFloat(v.getPropertyValue(a,"borderBottomWidth"))||0)-(parseFloat(v.getPropertyValue(a,"paddingTop"))||0)-(parseFloat(v.getPropertyValue(a,"paddingBottom"))||0);return e(),k}if("width"===c&&"border-box"!==v.getPropertyValue(a,"boxSizing").toString().toLowerCase()){var l=a.offsetWidth-(parseFloat(v.getPropertyValue(a,"borderLeftWidth"))||0)-(parseFloat(v.getPropertyValue(a,"borderRightWidth"))||0)-(parseFloat(v.getPropertyValue(a,"paddingLeft"))||0)-(parseFloat(v.getPropertyValue(a,"paddingRight"))||0);return e(),l}}var o;o=g(a)===d?b.getComputedStyle(a,null):g(a).computedStyle?g(a).computedStyle:g(a).computedStyle=b.getComputedStyle(a,null),"borderColor"===c&&(c="borderTopColor"),i=9===n&&"filter"===c?o.getPropertyValue(c):o[c],(""===i||null===i)&&(i=a.style[c]),e()}if("auto"===i&&/^(top|right|bottom|left)$/i.test(c)){var p=h(a,"position");("fixed"===p||"absolute"===p&&/top|left/i.test(c))&&(i=m(a).position()[c]+"px")}return i}var i;if(v.Hooks.registered[c]){var j=c,k=v.Hooks.getRoot(j);e===d&&(e=v.getPropertyValue(a,v.Names.prefixCheck(k)[0])),v.Normalizations.registered[k]&&(e=v.Normalizations.registered[k]("extract",a,e)),i=v.Hooks.extractValue(j,e)}else if(v.Normalizations.registered[c]){var l,o;l=v.Normalizations.registered[c]("name",a),"transform"!==l&&(o=h(a,v.Names.prefixCheck(l)[0]),v.Values.isCSSNullValue(o)&&v.Hooks.templates[c]&&(o=v.Hooks.templates[c][1])),i=v.Normalizations.registered[c]("extract",a,o)}if(!/^[\d-]/.test(i))if(g(a)&&g(a).isSVG&&v.Names.SVGAttribute(c))if(/^(height|width)$/i.test(c))try{i=a.getBBox()[c]}catch(p){i=0}else i=a.getAttribute(c);else i=h(a,v.Names.prefixCheck(c)[0]);return v.Values.isCSSNullValue(i)&&(i=0),t.debug>=2&&console.log("Get "+c+": "+i),i},setPropertyValue:function(a,c,d,e,f){var h=c;if("scroll"===c)f.container?f.container["scroll"+f.direction]=d:"Left"===f.direction?b.scrollTo(d,f.alternateValue):b.scrollTo(f.alternateValue,d);else if(v.Normalizations.registered[c]&&"transform"===v.Normalizations.registered[c]("name",a))v.Normalizations.registered[c]("inject",a,d),h="transform",d=g(a).transformCache[c];else{if(v.Hooks.registered[c]){var i=c,j=v.Hooks.getRoot(c);e=e||v.getPropertyValue(a,j),d=v.Hooks.injectValue(i,d,e),c=j}if(v.Normalizations.registered[c]&&(d=v.Normalizations.registered[c]("inject",a,d),c=v.Normalizations.registered[c]("name",a)),h=v.Names.prefixCheck(c)[0],8>=n)try{a.style[h]=d}catch(k){t.debug&&console.log("Browser does not support ["+d+"] for ["+h+"]")}else g(a)&&g(a).isSVG&&v.Names.SVGAttribute(c)?a.setAttribute(c,d):a.style[h]=d;t.debug>=2&&console.log("Set "+c+" ("+h+"): "+d)}return[h,d]},flushTransformCache:function(a){function b(b){return parseFloat(v.getPropertyValue(a,b))}var c="";if((n||t.State.isAndroid&&!t.State.isChrome)&&g(a).isSVG){var d={translate:[b("translateX"),b("translateY")],skewX:[b("skewX")],skewY:[b("skewY")],scale:1!==b("scale")?[b("scale"),b("scale")]:[b("scaleX"),b("scaleY")],rotate:[b("rotateZ"),0,0]};m.each(g(a).transformCache,function(a){/^translate/i.test(a)?a="translate":/^scale/i.test(a)?a="scale":/^rotate/i.test(a)&&(a="rotate"),d[a]&&(c+=a+"("+d[a].join(" ")+") ",delete d[a])})}else{var e,f;m.each(g(a).transformCache,function(b){return e=g(a).transformCache[b],"transformPerspective"===b?(f=e,!0):(9===n&&"rotateZ"===b&&(b="rotate"),void(c+=b+e+" "))}),f&&(c="perspective"+f+" "+c)}v.setPropertyValue(a,"transform",c)}};v.Hooks.register(),v.Normalizations.register(),t.hook=function(a,b,c){var e=d;return a=f(a),m.each(a,function(a,f){if(g(f)===d&&t.init(f),c===d)e===d&&(e=t.CSS.getPropertyValue(f,b));else{var h=t.CSS.setPropertyValue(f,b,c);"transform"===h[0]&&t.CSS.flushTransformCache(f),e=h}}),e};var w=function(){function a(){return h?B.promise||null:i}function e(){function a(){function a(a,b){var c=d,e=d,g=d;return p.isArray(a)?(c=a[0],!p.isArray(a[1])&&/^[\d-]/.test(a[1])||p.isFunction(a[1])||v.RegEx.isHex.test(a[1])?g=a[1]:(p.isString(a[1])&&!v.RegEx.isHex.test(a[1])||p.isArray(a[1]))&&(e=b?a[1]:j(a[1],h.duration),a[2]!==d&&(g=a[2]))):c=a,b||(e=e||h.easing),p.isFunction(c)&&(c=c.call(f,y,x)),p.isFunction(g)&&(g=g.call(f,y,x)),[c||0,e,g]}function l(a,b){var c,d;return d=(b||"0").toString().toLowerCase().replace(/[%A-z]+$/,function(a){return c=a,""}),c||(c=v.Values.getUnitType(a)),[d,c]}function n(){var a={myParent:f.parentNode||c.body,position:v.getPropertyValue(f,"position"),fontSize:v.getPropertyValue(f,"fontSize")},d=a.position===I.lastPosition&&a.myParent===I.lastParent,e=a.fontSize===I.lastFontSize;I.lastParent=a.myParent,I.lastPosition=a.position,I.lastFontSize=a.fontSize;var h=100,i={};if(e&&d)i.emToPx=I.lastEmToPx,i.percentToPxWidth=I.lastPercentToPxWidth,i.percentToPxHeight=I.lastPercentToPxHeight;else{var j=g(f).isSVG?c.createElementNS("http://www.w3.org/2000/svg","rect"):c.createElement("div");t.init(j),a.myParent.appendChild(j),m.each(["overflow","overflowX","overflowY"],function(a,b){t.CSS.setPropertyValue(j,b,"hidden")}),t.CSS.setPropertyValue(j,"position",a.position),t.CSS.setPropertyValue(j,"fontSize",a.fontSize),t.CSS.setPropertyValue(j,"boxSizing","content-box"),m.each(["minWidth","maxWidth","width","minHeight","maxHeight","height"],function(a,b){t.CSS.setPropertyValue(j,b,h+"%")}),t.CSS.setPropertyValue(j,"paddingLeft",h+"em"),i.percentToPxWidth=I.lastPercentToPxWidth=(parseFloat(v.getPropertyValue(j,"width",null,!0))||1)/h,i.percentToPxHeight=I.lastPercentToPxHeight=(parseFloat(v.getPropertyValue(j,"height",null,!0))||1)/h,i.emToPx=I.lastEmToPx=(parseFloat(v.getPropertyValue(j,"paddingLeft"))||1)/h,a.myParent.removeChild(j)}return null===I.remToPx&&(I.remToPx=parseFloat(v.getPropertyValue(c.body,"fontSize"))||16),null===I.vwToPx&&(I.vwToPx=parseFloat(b.innerWidth)/100,I.vhToPx=parseFloat(b.innerHeight)/100),i.remToPx=I.remToPx,i.vwToPx=I.vwToPx,i.vhToPx=I.vhToPx,t.debug>=1&&console.log("Unit ratios: "+JSON.stringify(i),f),i}if(h.begin&&0===y)try{h.begin.call(o,o)}catch(r){setTimeout(function(){throw r},1)}if("scroll"===C){var u,w,z,A=/^x$/i.test(h.axis)?"Left":"Top",D=parseFloat(h.offset)||0;h.container?p.isWrapped(h.container)||p.isNode(h.container)?(h.container=h.container[0]||h.container,u=h.container["scroll"+A],z=u+m(f).position()[A.toLowerCase()]+D):h.container=null:(u=t.State.scrollAnchor[t.State["scrollProperty"+A]],w=t.State.scrollAnchor[t.State["scrollProperty"+("Left"===A?"Top":"Left")]],z=m(f).offset()[A.toLowerCase()]+D),i={scroll:{rootPropertyValue:!1,startValue:u,currentValue:u,endValue:z,unitType:"",easing:h.easing,scrollData:{container:h.container,direction:A,alternateValue:w}},element:f},t.debug&&console.log("tweensContainer (scroll): ",i.scroll,f)}else if("reverse"===C){if(!g(f).tweensContainer)return void m.dequeue(f,h.queue);"none"===g(f).opts.display&&(g(f).opts.display="auto"),"hidden"===g(f).opts.visibility&&(g(f).opts.visibility="visible"),g(f).opts.loop=!1,g(f).opts.begin=null,g(f).opts.complete=null,s.easing||delete h.easing,s.duration||delete h.duration,h=m.extend({},g(f).opts,h);var E=m.extend(!0,{},g(f).tweensContainer);for(var F in E)if("element"!==F){var G=E[F].startValue;E[F].startValue=E[F].currentValue=E[F].endValue,E[F].endValue=G,p.isEmptyObject(s)||(E[F].easing=h.easing),t.debug&&console.log("reverse tweensContainer ("+F+"): "+JSON.stringify(E[F]),f)}i=E}else if("start"===C){var E;g(f).tweensContainer&&g(f).isAnimating===!0&&(E=g(f).tweensContainer),m.each(q,function(b,c){if(RegExp("^"+v.Lists.colors.join("$|^")+"$").test(b)){var e=a(c,!0),f=e[0],g=e[1],h=e[2];if(v.RegEx.isHex.test(f)){for(var i=["Red","Green","Blue"],j=v.Values.hexToRgb(f),k=h?v.Values.hexToRgb(h):d,l=0;l<i.length;l++){var m=[j[l]];g&&m.push(g),k!==d&&m.push(k[l]),q[b+i[l]]=m}delete q[b]}}});for(var H in q){var K=a(q[H]),L=K[0],M=K[1],N=K[2];H=v.Names.camelCase(H);var O=v.Hooks.getRoot(H),P=!1;if(g(f).isSVG||"tween"===O||v.Names.prefixCheck(O)[1]!==!1||v.Normalizations.registered[O]!==d){(h.display!==d&&null!==h.display&&"none"!==h.display||h.visibility!==d&&"hidden"!==h.visibility)&&/opacity|filter/.test(H)&&!N&&0!==L&&(N=0),h._cacheValues&&E&&E[H]?(N===d&&(N=E[H].endValue+E[H].unitType),P=g(f).rootPropertyValueCache[O]):v.Hooks.registered[H]?N===d?(P=v.getPropertyValue(f,O),N=v.getPropertyValue(f,H,P)):P=v.Hooks.templates[O][1]:N===d&&(N=v.getPropertyValue(f,H));var Q,R,S,T=!1;if(Q=l(H,N),N=Q[0],S=Q[1],Q=l(H,L),L=Q[0].replace(/^([+-\/*])=/,function(a,b){return T=b,""}),R=Q[1],N=parseFloat(N)||0,L=parseFloat(L)||0,"%"===R&&(/^(fontSize|lineHeight)$/.test(H)?(L/=100,R="em"):/^scale/.test(H)?(L/=100,R=""):/(Red|Green|Blue)$/i.test(H)&&(L=L/100*255,R="")),/[\/*]/.test(T))R=S;else if(S!==R&&0!==N)if(0===L)R=S;else{e=e||n();var U=/margin|padding|left|right|width|text|word|letter/i.test(H)||/X$/.test(H)||"x"===H?"x":"y";switch(S){case"%":N*="x"===U?e.percentToPxWidth:e.percentToPxHeight;break;case"px":break;default:N*=e[S+"ToPx"]}switch(R){case"%":N*=1/("x"===U?e.percentToPxWidth:e.percentToPxHeight);break;case"px":break;default:N*=1/e[R+"ToPx"]}}switch(T){case"+":L=N+L;break;case"-":L=N-L;break;case"*":L=N*L;break;case"/":L=N/L}i[H]={rootPropertyValue:P,startValue:N,currentValue:N,endValue:L,unitType:R,easing:M},t.debug&&console.log("tweensContainer ("+H+"): "+JSON.stringify(i[H]),f)}else t.debug&&console.log("Skipping ["+O+"] due to a lack of browser support.")}i.element=f}i.element&&(v.Values.addClass(f,"velocity-animating"),J.push(i),""===h.queue&&(g(f).tweensContainer=i,g(f).opts=h),g(f).isAnimating=!0,y===x-1?(t.State.calls.push([J,o,h,null,B.resolver]),t.State.isTicking===!1&&(t.State.isTicking=!0,k())):y++)}var e,f=this,h=m.extend({},t.defaults,s),i={};switch(g(f)===d&&t.init(f),parseFloat(h.delay)&&h.queue!==!1&&m.queue(f,h.queue,function(a){t.velocityQueueEntryFlag=!0,g(f).delayTimer={setTimeout:setTimeout(a,parseFloat(h.delay)),next:a}}),h.duration.toString().toLowerCase()){case"fast":h.duration=200;break;case"normal":h.duration=r;break;case"slow":h.duration=600;break;default:h.duration=parseFloat(h.duration)||1}t.mock!==!1&&(t.mock===!0?h.duration=h.delay=1:(h.duration*=parseFloat(t.mock)||1,h.delay*=parseFloat(t.mock)||1)),h.easing=j(h.easing,h.duration),h.begin&&!p.isFunction(h.begin)&&(h.begin=null),h.progress&&!p.isFunction(h.progress)&&(h.progress=null),h.complete&&!p.isFunction(h.complete)&&(h.complete=null),h.display!==d&&null!==h.display&&(h.display=h.display.toString().toLowerCase(),"auto"===h.display&&(h.display=t.CSS.Values.getDisplayType(f))),h.visibility!==d&&null!==h.visibility&&(h.visibility=h.visibility.toString().toLowerCase()),h.mobileHA=h.mobileHA&&t.State.isMobile&&!t.State.isGingerbread,h.queue===!1?h.delay?setTimeout(a,h.delay):a():m.queue(f,h.queue,function(b,c){return c===!0?(B.promise&&B.resolver(o),!0):(t.velocityQueueEntryFlag=!0,void a(b))}),""!==h.queue&&"fx"!==h.queue||"inprogress"===m.queue(f)[0]||m.dequeue(f)}var h,i,n,o,q,s,u=arguments[0]&&(arguments[0].p||m.isPlainObject(arguments[0].properties)&&!arguments[0].properties.names||p.isString(arguments[0].properties));if(p.isWrapped(this)?(h=!1,n=0,o=this,i=this):(h=!0,n=1,o=u?arguments[0].elements||arguments[0].e:arguments[0]),o=f(o)){u?(q=arguments[0].properties||arguments[0].p,s=arguments[0].options||arguments[0].o):(q=arguments[n],s=arguments[n+1]);var x=o.length,y=0;if(!/^(stop|finish|finishAll)$/i.test(q)&&!m.isPlainObject(s)){var z=n+1;s={};for(var A=z;A<arguments.length;A++)p.isArray(arguments[A])||!/^(fast|normal|slow)$/i.test(arguments[A])&&!/^\d/.test(arguments[A])?p.isString(arguments[A])||p.isArray(arguments[A])?s.easing=arguments[A]:p.isFunction(arguments[A])&&(s.complete=arguments[A]):s.duration=arguments[A]}var B={promise:null,resolver:null,rejecter:null};h&&t.Promise&&(B.promise=new t.Promise(function(a,b){B.resolver=a,B.rejecter=b}));var C;switch(q){case"scroll":C="scroll";break;case"reverse":C="reverse";break;case"finish":case"finishAll":case"stop":m.each(o,function(a,b){g(b)&&g(b).delayTimer&&(clearTimeout(g(b).delayTimer.setTimeout),g(b).delayTimer.next&&g(b).delayTimer.next(),delete g(b).delayTimer),"finishAll"!==q||s!==!0&&!p.isString(s)||(m.each(m.queue(b,p.isString(s)?s:""),function(a,b){p.isFunction(b)&&b()}),m.queue(b,p.isString(s)?s:"",[]))});var D=[];return m.each(t.State.calls,function(a,b){b&&m.each(b[1],function(c,e){var f=s===d?"":s;return f===!0||b[2].queue===f||s===d&&b[2].queue===!1?void m.each(o,function(c,d){d===e&&((s===!0||p.isString(s))&&(m.each(m.queue(d,p.isString(s)?s:""),function(a,b){p.isFunction(b)&&b(null,!0) }),m.queue(d,p.isString(s)?s:"",[])),"stop"===q?(g(d)&&g(d).tweensContainer&&f!==!1&&m.each(g(d).tweensContainer,function(a,b){b.endValue=b.currentValue}),D.push(a)):("finish"===q||"finishAll"===q)&&(b[2].duration=1))}):!0})}),"stop"===q&&(m.each(D,function(a,b){l(b,!0)}),B.promise&&B.resolver(o)),a();default:if(!m.isPlainObject(q)||p.isEmptyObject(q)){if(p.isString(q)&&t.Redirects[q]){var E=m.extend({},s),F=E.duration,G=E.delay||0;return E.backwards===!0&&(o=m.extend(!0,[],o).reverse()),m.each(o,function(a,b){parseFloat(E.stagger)?E.delay=G+parseFloat(E.stagger)*a:p.isFunction(E.stagger)&&(E.delay=G+E.stagger.call(b,a,x)),E.drag&&(E.duration=parseFloat(F)||(/^(callout|transition)/.test(q)?1e3:r),E.duration=Math.max(E.duration*(E.backwards?1-a/x:(a+1)/x),.75*E.duration,200)),t.Redirects[q].call(b,b,E||{},a,x,o,B.promise?B:d)}),a()}var H="Velocity: First argument ("+q+") was not a property map, a known action, or a registered redirect. Aborting.";return B.promise?B.rejecter(new Error(H)):console.log(H),a()}C="start"}var I={lastParent:null,lastPosition:null,lastFontSize:null,lastPercentToPxWidth:null,lastPercentToPxHeight:null,lastEmToPx:null,remToPx:null,vwToPx:null,vhToPx:null},J=[];m.each(o,function(a,b){p.isNode(b)&&e.call(b)});var K,E=m.extend({},t.defaults,s);if(E.loop=parseInt(E.loop),K=2*E.loop-1,E.loop)for(var L=0;K>L;L++){var M={delay:E.delay,progress:E.progress};L===K-1&&(M.display=E.display,M.visibility=E.visibility,M.complete=E.complete),w(o,"reverse",M)}return a()}};t=m.extend(w,t),t.animate=w;var x=b.requestAnimationFrame||o;return t.State.isMobile||c.hidden===d||c.addEventListener("visibilitychange",function(){c.hidden?(x=function(a){return setTimeout(function(){a(!0)},16)},k()):x=b.requestAnimationFrame||o}),a.Velocity=t,a!==b&&(a.fn.velocity=w,a.fn.velocity.defaults=t.defaults),m.each(["Down","Up"],function(a,b){t.Redirects["slide"+b]=function(a,c,e,f,g,h){var i=m.extend({},c),j=i.begin,k=i.complete,l={height:"",marginTop:"",marginBottom:"",paddingTop:"",paddingBottom:""},n={};i.display===d&&(i.display="Down"===b?"inline"===t.CSS.Values.getDisplayType(a)?"inline-block":"block":"none"),i.begin=function(){j&&j.call(g,g);for(var c in l){n[c]=a.style[c];var d=t.CSS.getPropertyValue(a,c);l[c]="Down"===b?[d,0]:[0,d]}n.overflow=a.style.overflow,a.style.overflow="hidden"},i.complete=function(){for(var b in n)a.style[b]=n[b];k&&k.call(g,g),h&&h.resolver(g)},t(a,l,i)}}),m.each(["In","Out"],function(a,b){t.Redirects["fade"+b]=function(a,c,e,f,g,h){var i=m.extend({},c),j={opacity:"In"===b?1:0},k=i.complete;i.complete=e!==f-1?i.begin=null:function(){k&&k.call(g,g),h&&h.resolver(g)},i.display===d&&(i.display="In"===b?"auto":"none"),t(this,j,i)}}),t}(window.jQuery||window.Zepto||window,window,document)}); define('velocity', ['velocity/velocity.min'], function (main) { return main; }); /********************** Velocity UI Pack **********************/ /* VelocityJS.org UI Pack (5.0.4). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License. Portions copyright Daniel Eden, Christian Pucci. */ ;(function (factory) { /* CommonJS module. */ if (typeof require === "function" && typeof exports === "object" ) { module.exports = factory(); /* AMD module. */ } else if (typeof define === "function" && define.amd) { define('velocity/velocity.ui',[ "velocity" ], factory); /* Browser globals. */ } else { factory(); } }(function() { return function (global, window, document, undefined) { /************* Checks *************/ if (!global.Velocity || !global.Velocity.Utilities) { window.console && console.log("Velocity UI Pack: Velocity must be loaded first. Aborting."); return; } else { var Velocity = global.Velocity, $ = Velocity.Utilities; } var velocityVersion = Velocity.version, requiredVersion = { major: 1, minor: 1, patch: 0 }; function greaterSemver (primary, secondary) { var versionInts = []; if (!primary || !secondary) { return false; } $.each([ primary, secondary ], function(i, versionObject) { var versionIntsComponents = []; $.each(versionObject, function(component, value) { while (value.toString().length < 5) { value = "0" + value; } versionIntsComponents.push(value); }); versionInts.push(versionIntsComponents.join("")) }); return (parseFloat(versionInts[0]) > parseFloat(versionInts[1])); } if (greaterSemver(requiredVersion, velocityVersion)){ var abortError = "Velocity UI Pack: You need to update Velocity (jquery.velocity.js) to a newer version. Visit http://github.com/julianshapiro/velocity."; alert(abortError); throw new Error(abortError); } /************************ Effect Registration ************************/ /* Note: RegisterUI is a legacy name. */ Velocity.RegisterEffect = Velocity.RegisterUI = function (effectName, properties) { /* Animate the expansion/contraction of the elements' parent's height for In/Out effects. */ function animateParentHeight (elements, direction, totalDuration, stagger) { var totalHeightDelta = 0, parentNode; /* Sum the total height (including padding and margin) of all targeted elements. */ $.each(elements.nodeType ? [ elements ] : elements, function(i, element) { if (stagger) { /* Increase the totalDuration by the successive delay amounts produced by the stagger option. */ totalDuration += i * stagger; } parentNode = element.parentNode; $.each([ "height", "paddingTop", "paddingBottom", "marginTop", "marginBottom"], function(i, property) { totalHeightDelta += parseFloat(Velocity.CSS.getPropertyValue(element, property)); }); }); /* Animate the parent element's height adjustment (with a varying duration multiplier for aesthetic benefits). */ Velocity.animate( parentNode, { height: (direction === "In" ? "+" : "-") + "=" + totalHeightDelta }, { queue: false, easing: "ease-in-out", duration: totalDuration * (direction === "In" ? 0.6 : 1) } ); } /* Register a custom redirect for each effect. */ Velocity.Redirects[effectName] = function (element, redirectOptions, elementsIndex, elementsSize, elements, promiseData) { var finalElement = (elementsIndex === elementsSize - 1); if (typeof properties.defaultDuration === "function") { properties.defaultDuration = properties.defaultDuration.call(elements, elements); } else { properties.defaultDuration = parseFloat(properties.defaultDuration); } /* Iterate through each effect's call array. */ for (var callIndex = 0; callIndex < properties.calls.length; callIndex++) { var call = properties.calls[callIndex], propertyMap = call[0], redirectDuration = (redirectOptions.duration || properties.defaultDuration || 1000), durationPercentage = call[1], callOptions = call[2] || {}, opts = {}; /* Assign the whitelisted per-call options. */ opts.duration = redirectDuration * (durationPercentage || 1); opts.queue = redirectOptions.queue || ""; opts.easing = callOptions.easing || "ease"; opts.delay = parseFloat(callOptions.delay) || 0; opts._cacheValues = callOptions._cacheValues || true; /* Special processing for the first effect call. */ if (callIndex === 0) { /* If a delay was passed into the redirect, combine it with the first call's delay. */ opts.delay += (parseFloat(redirectOptions.delay) || 0); if (elementsIndex === 0) { opts.begin = function() { /* Only trigger a begin callback on the first effect call with the first element in the set. */ redirectOptions.begin && redirectOptions.begin.call(elements, elements); var direction = effectName.match(/(In|Out)$/); /* Make "in" transitioning elements invisible immediately so that there's no FOUC between now and the first RAF tick. */ if ((direction && direction[0] === "In") && propertyMap.opacity !== undefined) { $.each(elements.nodeType ? [ elements ] : elements, function(i, element) { Velocity.CSS.setPropertyValue(element, "opacity", 0); }); } /* Only trigger animateParentHeight() if we're using an In/Out transition. */ if (redirectOptions.animateParentHeight && direction) { animateParentHeight(elements, direction[0], redirectDuration + opts.delay, redirectOptions.stagger); } } } /* If the user isn't overriding the display option, default to "auto" for "In"-suffixed transitions. */ if (redirectOptions.display !== null) { if (redirectOptions.display !== undefined && redirectOptions.display !== "none") { opts.display = redirectOptions.display; } else if (/In$/.test(effectName)) { /* Inline elements cannot be subjected to transforms, so we switch them to inline-block. */ var defaultDisplay = Velocity.CSS.Values.getDisplayType(element); opts.display = (defaultDisplay === "inline") ? "inline-block" : defaultDisplay; } } if (redirectOptions.visibility && redirectOptions.visibility !== "hidden") { opts.visibility = redirectOptions.visibility; } } /* Special processing for the last effect call. */ if (callIndex === properties.calls.length - 1) { /* Append promise resolving onto the user's redirect callback. */ function injectFinalCallbacks () { if ((redirectOptions.display === undefined || redirectOptions.display === "none") && /Out$/.test(effectName)) { $.each(elements.nodeType ? [ elements ] : elements, function(i, element) { Velocity.CSS.setPropertyValue(element, "display", "none"); }); } redirectOptions.complete && redirectOptions.complete.call(elements, elements); if (promiseData) { promiseData.resolver(elements || element); } } opts.complete = function() { if (properties.reset) { for (var resetProperty in properties.reset) { var resetValue = properties.reset[resetProperty]; /* Format each non-array value in the reset property map to [ value, value ] so that changes apply immediately and DOM querying is avoided (via forcefeeding). */ /* Note: Don't forcefeed hooks, otherwise their hook roots will be defaulted to their null values. */ if (Velocity.CSS.Hooks.registered[resetProperty] === undefined && (typeof resetValue === "string" || typeof resetValue === "number")) { properties.reset[resetProperty] = [ properties.reset[resetProperty], properties.reset[resetProperty] ]; } } /* So that the reset values are applied instantly upon the next rAF tick, use a zero duration and parallel queueing. */ var resetOptions = { duration: 0, queue: false }; /* Since the reset option uses up the complete callback, we trigger the user's complete callback at the end of ours. */ if (finalElement) { resetOptions.complete = injectFinalCallbacks; } Velocity.animate(element, properties.reset, resetOptions); /* Only trigger the user's complete callback on the last effect call with the last element in the set. */ } else if (finalElement) { injectFinalCallbacks(); } }; if (redirectOptions.visibility === "hidden") { opts.visibility = redirectOptions.visibility; } } Velocity.animate(element, propertyMap, opts); } }; /* Return the Velocity object so that RegisterUI calls can be chained. */ return Velocity; }; /********************* Packaged Effects *********************/ /* Externalize the packagedEffects data so that they can optionally be modified and re-registered. */ /* Support: <=IE8: Callouts will have no effect, and transitions will simply fade in/out. IE9/Android 2.3: Most effects are fully supported, the rest fade in/out. All other browsers: full support. */ Velocity.RegisterEffect.packagedEffects = { /* Animate.css */ "callout.bounce": { defaultDuration: 550, calls: [ [ { translateY: -30 }, 0.25 ], [ { translateY: 0 }, 0.125 ], [ { translateY: -15 }, 0.125 ], [ { translateY: 0 }, 0.25 ] ] }, /* Animate.css */ "callout.shake": { defaultDuration: 800, calls: [ [ { translateX: -11 }, 0.125 ], [ { translateX: 11 }, 0.125 ], [ { translateX: -11 }, 0.125 ], [ { translateX: 11 }, 0.125 ], [ { translateX: -11 }, 0.125 ], [ { translateX: 11 }, 0.125 ], [ { translateX: -11 }, 0.125 ], [ { translateX: 0 }, 0.125 ] ] }, /* Animate.css */ "callout.flash": { defaultDuration: 1100, calls: [ [ { opacity: [ 0, "easeInOutQuad", 1 ] }, 0.25 ], [ { opacity: [ 1, "easeInOutQuad" ] }, 0.25 ], [ { opacity: [ 0, "easeInOutQuad" ] }, 0.25 ], [ { opacity: [ 1, "easeInOutQuad" ] }, 0.25 ] ] }, /* Animate.css */ "callout.pulse": { defaultDuration: 825, calls: [ [ { scaleX: 1.1, scaleY: 1.1 }, 0.50, { easing: "easeInExpo" } ], [ { scaleX: 1, scaleY: 1 }, 0.50 ] ] }, /* Animate.css */ "callout.swing": { defaultDuration: 950, calls: [ [ { rotateZ: 15 }, 0.20 ], [ { rotateZ: -10 }, 0.20 ], [ { rotateZ: 5 }, 0.20 ], [ { rotateZ: -5 }, 0.20 ], [ { rotateZ: 0 }, 0.20 ] ] }, /* Animate.css */ "callout.tada": { defaultDuration: 1000, calls: [ [ { scaleX: 0.9, scaleY: 0.9, rotateZ: -3 }, 0.10 ], [ { scaleX: 1.1, scaleY: 1.1, rotateZ: 3 }, 0.10 ], [ { scaleX: 1.1, scaleY: 1.1, rotateZ: -3 }, 0.10 ], [ "reverse", 0.125 ], [ "reverse", 0.125 ], [ "reverse", 0.125 ], [ "reverse", 0.125 ], [ "reverse", 0.125 ], [ { scaleX: 1, scaleY: 1, rotateZ: 0 }, 0.20 ] ] }, "transition.fadeIn": { defaultDuration: 500, calls: [ [ { opacity: [ 1, 0 ] } ] ] }, "transition.fadeOut": { defaultDuration: 500, calls: [ [ { opacity: [ 0, 1 ] } ] ] }, /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipXIn": { defaultDuration: 700, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 800, 800 ], rotateY: [ 0, -55 ] } ] ], reset: { transformPerspective: 0 } }, /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipXOut": { defaultDuration: 700, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 800, 800 ], rotateY: 55 } ] ], reset: { transformPerspective: 0, rotateY: 0 } }, /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipYIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 800, 800 ], rotateX: [ 0, -45 ] } ] ], reset: { transformPerspective: 0 } }, /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipYOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 800, 800 ], rotateX: 25 } ] ], reset: { transformPerspective: 0, rotateX: 0 } }, /* Animate.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipBounceXIn": { defaultDuration: 900, calls: [ [ { opacity: [ 0.725, 0 ], transformPerspective: [ 400, 400 ], rotateY: [ -10, 90 ] }, 0.50 ], [ { opacity: 0.80, rotateY: 10 }, 0.25 ], [ { opacity: 1, rotateY: 0 }, 0.25 ] ], reset: { transformPerspective: 0 } }, /* Animate.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipBounceXOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0.9, 1 ], transformPerspective: [ 400, 400 ], rotateY: -10 }, 0.50 ], [ { opacity: 0, rotateY: 90 }, 0.50 ] ], reset: { transformPerspective: 0, rotateY: 0 } }, /* Animate.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipBounceYIn": { defaultDuration: 850, calls: [ [ { opacity: [ 0.725, 0 ], transformPerspective: [ 400, 400 ], rotateX: [ -10, 90 ] }, 0.50 ], [ { opacity: 0.80, rotateX: 10 }, 0.25 ], [ { opacity: 1, rotateX: 0 }, 0.25 ] ], reset: { transformPerspective: 0 } }, /* Animate.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.flipBounceYOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0.9, 1 ], transformPerspective: [ 400, 400 ], rotateX: -15 }, 0.50 ], [ { opacity: 0, rotateX: 90 }, 0.50 ] ], reset: { transformPerspective: 0, rotateX: 0 } }, /* Magic.css */ "transition.swoopIn": { defaultDuration: 850, calls: [ [ { opacity: [ 1, 0 ], transformOriginX: [ "100%", "50%" ], transformOriginY: [ "100%", "100%" ], scaleX: [ 1, 0 ], scaleY: [ 1, 0 ], translateX: [ 0, -700 ], translateZ: 0 } ] ], reset: { transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ "transition.swoopOut": { defaultDuration: 850, calls: [ [ { opacity: [ 0, 1 ], transformOriginX: [ "50%", "100%" ], transformOriginY: [ "100%", "100%" ], scaleX: 0, scaleY: 0, translateX: -700, translateZ: 0 } ] ], reset: { transformOriginX: "50%", transformOriginY: "50%", scaleX: 1, scaleY: 1, translateX: 0 } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3. (Fades and scales only.) */ "transition.whirlIn": { defaultDuration: 850, calls: [ [ { opacity: [ 1, 0 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: [ 1, 0 ], scaleY: [ 1, 0 ], rotateY: [ 0, 160 ] }, 1, { easing: "easeInOutSine" } ] ] }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3. (Fades and scales only.) */ "transition.whirlOut": { defaultDuration: 750, calls: [ [ { opacity: [ 0, "easeInOutQuint", 1 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: 0, scaleY: 0, rotateY: 160 }, 1, { easing: "swing" } ] ], reset: { scaleX: 1, scaleY: 1, rotateY: 0 } }, "transition.shrinkIn": { defaultDuration: 750, calls: [ [ { opacity: [ 1, 0 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: [ 1, 1.5 ], scaleY: [ 1, 1.5 ], translateZ: 0 } ] ] }, "transition.shrinkOut": { defaultDuration: 600, calls: [ [ { opacity: [ 0, 1 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: 1.3, scaleY: 1.3, translateZ: 0 } ] ], reset: { scaleX: 1, scaleY: 1 } }, "transition.expandIn": { defaultDuration: 700, calls: [ [ { opacity: [ 1, 0 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: [ 1, 0.625 ], scaleY: [ 1, 0.625 ], translateZ: 0 } ] ] }, "transition.expandOut": { defaultDuration: 700, calls: [ [ { opacity: [ 0, 1 ], transformOriginX: [ "50%", "50%" ], transformOriginY: [ "50%", "50%" ], scaleX: 0.5, scaleY: 0.5, translateZ: 0 } ] ], reset: { scaleX: 1, scaleY: 1 } }, /* Animate.css */ "transition.bounceIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], scaleX: [ 1.05, 0.3 ], scaleY: [ 1.05, 0.3 ] }, 0.40 ], [ { scaleX: 0.9, scaleY: 0.9, translateZ: 0 }, 0.20 ], [ { scaleX: 1, scaleY: 1 }, 0.50 ] ] }, /* Animate.css */ "transition.bounceOut": { defaultDuration: 800, calls: [ [ { scaleX: 0.95, scaleY: 0.95 }, 0.35 ], [ { scaleX: 1.1, scaleY: 1.1, translateZ: 0 }, 0.35 ], [ { opacity: [ 0, 1 ], scaleX: 0.3, scaleY: 0.3 }, 0.30 ] ], reset: { scaleX: 1, scaleY: 1 } }, /* Animate.css */ "transition.bounceUpIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], translateY: [ -30, 1000 ] }, 0.60, { easing: "easeOutCirc" } ], [ { translateY: 10 }, 0.20 ], [ { translateY: 0 }, 0.20 ] ] }, /* Animate.css */ "transition.bounceUpOut": { defaultDuration: 1000, calls: [ [ { translateY: 20 }, 0.20 ], [ { opacity: [ 0, "easeInCirc", 1 ], translateY: -1000 }, 0.80 ] ], reset: { translateY: 0 } }, /* Animate.css */ "transition.bounceDownIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 30, -1000 ] }, 0.60, { easing: "easeOutCirc" } ], [ { translateY: -10 }, 0.20 ], [ { translateY: 0 }, 0.20 ] ] }, /* Animate.css */ "transition.bounceDownOut": { defaultDuration: 1000, calls: [ [ { translateY: -20 }, 0.20 ], [ { opacity: [ 0, "easeInCirc", 1 ], translateY: 1000 }, 0.80 ] ], reset: { translateY: 0 } }, /* Animate.css */ "transition.bounceLeftIn": { defaultDuration: 750, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 30, -1250 ] }, 0.60, { easing: "easeOutCirc" } ], [ { translateX: -10 }, 0.20 ], [ { translateX: 0 }, 0.20 ] ] }, /* Animate.css */ "transition.bounceLeftOut": { defaultDuration: 750, calls: [ [ { translateX: 30 }, 0.20 ], [ { opacity: [ 0, "easeInCirc", 1 ], translateX: -1250 }, 0.80 ] ], reset: { translateX: 0 } }, /* Animate.css */ "transition.bounceRightIn": { defaultDuration: 750, calls: [ [ { opacity: [ 1, 0 ], translateX: [ -30, 1250 ] }, 0.60, { easing: "easeOutCirc" } ], [ { translateX: 10 }, 0.20 ], [ { translateX: 0 }, 0.20 ] ] }, /* Animate.css */ "transition.bounceRightOut": { defaultDuration: 750, calls: [ [ { translateX: -30 }, 0.20 ], [ { opacity: [ 0, "easeInCirc", 1 ], translateX: 1250 }, 0.80 ] ], reset: { translateX: 0 } }, "transition.slideUpIn": { defaultDuration: 900, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 0, 20 ], translateZ: 0 } ] ] }, "transition.slideUpOut": { defaultDuration: 900, calls: [ [ { opacity: [ 0, 1 ], translateY: -20, translateZ: 0 } ] ], reset: { translateY: 0 } }, "transition.slideDownIn": { defaultDuration: 900, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 0, -20 ], translateZ: 0 } ] ] }, "transition.slideDownOut": { defaultDuration: 900, calls: [ [ { opacity: [ 0, 1 ], translateY: 20, translateZ: 0 } ] ], reset: { translateY: 0 } }, "transition.slideLeftIn": { defaultDuration: 1000, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 0, -20 ], translateZ: 0 } ] ] }, "transition.slideLeftOut": { defaultDuration: 1050, calls: [ [ { opacity: [ 0, 1 ], translateX: -20, translateZ: 0 } ] ], reset: { translateX: 0 } }, "transition.slideRightIn": { defaultDuration: 1000, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 0, 20 ], translateZ: 0 } ] ] }, "transition.slideRightOut": { defaultDuration: 1050, calls: [ [ { opacity: [ 0, 1 ], translateX: 20, translateZ: 0 } ] ], reset: { translateX: 0 } }, "transition.slideUpBigIn": { defaultDuration: 850, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 0, 75 ], translateZ: 0 } ] ] }, "transition.slideUpBigOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0, 1 ], translateY: -75, translateZ: 0 } ] ], reset: { translateY: 0 } }, "transition.slideDownBigIn": { defaultDuration: 850, calls: [ [ { opacity: [ 1, 0 ], translateY: [ 0, -75 ], translateZ: 0 } ] ] }, "transition.slideDownBigOut": { defaultDuration: 800, calls: [ [ { opacity: [ 0, 1 ], translateY: 75, translateZ: 0 } ] ], reset: { translateY: 0 } }, "transition.slideLeftBigIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 0, -75 ], translateZ: 0 } ] ] }, "transition.slideLeftBigOut": { defaultDuration: 750, calls: [ [ { opacity: [ 0, 1 ], translateX: -75, translateZ: 0 } ] ], reset: { translateX: 0 } }, "transition.slideRightBigIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], translateX: [ 0, 75 ], translateZ: 0 } ] ] }, "transition.slideRightBigOut": { defaultDuration: 750, calls: [ [ { opacity: [ 0, 1 ], translateX: 75, translateZ: 0 } ] ], reset: { translateX: 0 } }, /* Magic.css */ "transition.perspectiveUpIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 800, 800 ], transformOriginX: [ 0, 0 ], transformOriginY: [ "100%", "100%" ], rotateX: [ 0, -180 ] } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveUpOut": { defaultDuration: 850, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 800, 800 ], transformOriginX: [ 0, 0 ], transformOriginY: [ "100%", "100%" ], rotateX: -180 } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateX: 0 } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveDownIn": { defaultDuration: 800, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 800, 800 ], transformOriginX: [ 0, 0 ], transformOriginY: [ 0, 0 ], rotateX: [ 0, 180 ] } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveDownOut": { defaultDuration: 850, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 800, 800 ], transformOriginX: [ 0, 0 ], transformOriginY: [ 0, 0 ], rotateX: 180 } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateX: 0 } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveLeftIn": { defaultDuration: 950, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 2000, 2000 ], transformOriginX: [ 0, 0 ], transformOriginY: [ 0, 0 ], rotateY: [ 0, -180 ] } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveLeftOut": { defaultDuration: 950, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 2000, 2000 ], transformOriginX: [ 0, 0 ], transformOriginY: [ 0, 0 ], rotateY: -180 } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateY: 0 } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveRightIn": { defaultDuration: 950, calls: [ [ { opacity: [ 1, 0 ], transformPerspective: [ 2000, 2000 ], transformOriginX: [ "100%", "100%" ], transformOriginY: [ 0, 0 ], rotateY: [ 0, 180 ] } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%" } }, /* Magic.css */ /* Support: Loses rotation in IE9/Android 2.3 (fades only). */ "transition.perspectiveRightOut": { defaultDuration: 950, calls: [ [ { opacity: [ 0, 1 ], transformPerspective: [ 2000, 2000 ], transformOriginX: [ "100%", "100%" ], transformOriginY: [ 0, 0 ], rotateY: 180 } ] ], reset: { transformPerspective: 0, transformOriginX: "50%", transformOriginY: "50%", rotateY: 0 } } }; /* Register the packaged effects. */ for (var effectName in Velocity.RegisterEffect.packagedEffects) { Velocity.RegisterEffect(effectName, Velocity.RegisterEffect.packagedEffects[effectName]); } /********************* Sequence Running **********************/ /* Note: Sequence calls must use Velocity's single-object arguments syntax. */ Velocity.RunSequence = function (originalSequence) { var sequence = $.extend(true, [], originalSequence); if (sequence.length > 1) { $.each(sequence.reverse(), function(i, currentCall) { var nextCall = sequence[i + 1]; if (nextCall) { /* Parallel sequence calls (indicated via sequenceQueue:false) are triggered in the previous call's begin callback. Otherwise, chained calls are normally triggered in the previous call's complete callback. */ var currentCallOptions = currentCall.o || currentCall.options, nextCallOptions = nextCall.o || nextCall.options; var timing = (currentCallOptions && currentCallOptions.sequenceQueue === false) ? "begin" : "complete", callbackOriginal = nextCallOptions && nextCallOptions[timing], options = {}; options[timing] = function() { var nextCallElements = nextCall.e || nextCall.elements; var elements = nextCallElements.nodeType ? [ nextCallElements ] : nextCallElements; callbackOriginal && callbackOriginal.call(elements, elements); Velocity(currentCall); } if (nextCall.o) { nextCall.o = $.extend({}, nextCallOptions, options); } else { nextCall.options = $.extend({}, nextCallOptions, options); } } }); sequence.reverse(); } Velocity(sequence[0]); }; }((window.jQuery || window.Zepto || window), window, document); })); /* * Copyright 2010, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ ;(function(self) { /** JSOL stands for JavaScript Object Literal which is a string representing an object in JavaScript syntax. For example: {foo:"bar"} is equivalent to {"foo":"bar"} in JavaScript. Both are valid JSOL. Note that {"foo":"bar"} is proper JSON[1] therefore you can use one of the many JSON parsers out there like json2.js[2] or even the native browser's JSON parser, if available. However, {foo:"bar"} is NOT proper JSON but valid Javascript syntax for representing an object with one key, "foo" and its value, "bar". Using a JSON parser is not an option since this is NOT proper JSON. You can use JSOL.parse to safely parse any string that reprsents a JavaScript Object Literal. JSOL.parse will throw an Invalid JSOL exception on function calls, function declarations and variable references. Examples: JSOL.parse('{foo:"bar"}'); // valid JSOL.parse('{evil:(function(){alert("I\'m evil");})()}'); // invalid function calls JSOL.parse('{fn:function() { }}'); // invalid function declarations var bar = "bar"; JSOL.parse('{foo:bar}'); // invalid variable references [1] http://www.json.org [2] http://www.json.org/json2.js */ if (!self.JSOL) { self.JSOL = {}; } // Used for trimming whitespace var trim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g; if (typeof self.JSOL.parse !== "function") { self.JSOL.parse = function(text) { // make sure text is a "string" if (typeof text !== "string" || !text) { return null; } // Make sure leading/trailing whitespace is removed text = text.replace(trim, ""); // Make sure the incoming text is actual JSOL (or Javascript Object Literal) // Logic borrowed from http://json.org/json2.js 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, ":") /** everything up to this point is json2.js **/ /** this is the 5th stage where it accepts unquoted keys **/ .replace(/\w*\s*\:/g, ":")) ) { return (new Function("return " + text))(); } else { throw("Invalid JSOL: " + text); } }; } })(window); define("jsol", function(){}); define('gooy-aurelia-animator-velocity/animator',['exports', 'velocity', 'velocity/velocity.ui', 'jsol', 'aurelia-templating'], function (exports, _velocity, _velocityVelocityUi, _jsol, _aureliaTemplating) { Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _Velocity = _interopRequireDefault(_velocity); var _JSOL = _interopRequireDefault(_jsol); var VelocityAnimator = (function () { function VelocityAnimator(container) { _classCallCheck(this, VelocityAnimator); this.options = { duration: 400, easing: 'linear' }; this.isAnimating = false; this.enterAnimation = { properties: ":enter", options: { easing: "ease-in", duration: 200 } }; this.leaveAnimation = { properties: ":leave", options: { easing: "ease-in", duration: 200 } }; this.easings = []; this.effects = { ":enter": "fadeIn", ":leave": "fadeOut" }; this.container = container || window.document; this.easings = Object.assign(_Velocity['default'].Easings, this.easings); this.effects = Object.assign(_Velocity['default'].Redirects, this.effects); } _createClass(VelocityAnimator, [{ key: 'animate', value: function animate(element, nameOrProps, options, silent) { this.isAnimating = true; var _this = this; var overrides = { complete: function complete(el) { _this.isAnimating = false; if (!silent) dispatch(el, "animateDone"); if (options && options.complete) options.complete.apply(this, arguments); } }; if (!element) return Promise.reject(new Error("invalid first argument")); if (typeof element === "string") element = this.container.querySelectorAll(element); if (!element || element.length === 0) return Promise.resolve(element); if (!silent) dispatch(element, "animateBegin"); if (typeof nameOrProps === "string") { nameOrProps = this.resolveEffectAlias(nameOrProps); } var opts = Object.assign({}, this.options, options, overrides); var p = (0, _Velocity['default'])(element, nameOrProps, opts); if (!p) return Promise.reject(new Error("invalid element used for animator.animate")); return p; } }, { key: 'stop', value: function stop(element, clearQueue) { (0, _Velocity['default'])(element, 'stop', clearQueue); this.isAnimating = false; return this; } }, { key: 'reverse', value: function reverse(element) { (0, _Velocity['default'])(element, 'reverse'); return this; } }, { key: 'rewind', value: function rewind(element) { (0, _Velocity['default'])(name, 'rewind'); return this; } }, { key: 'registerEffect', value: function registerEffect(name, props) { if (name[0] === ":") { if (typeof props === "string") { this.effects[name] = props; } else { throw new Error("second parameter must be a string when registering aliases"); } } else { _Velocity['default'].RegisterEffect(name, props); } return this; } }, { key: 'unregisterEffect', value: function unregisterEffect(name) { delete this.effects[name]; return this; } }, { key: 'runSequence', value: function runSequence(sequence) { var _this2 = this; dispatch(window, "sequenceBegin"); return new Promise(function (resolve, reject) { _this2.sequenceReject = resolve; var last = sequence[sequence.length - 1]; last.options = last.options || last.o || {}; last.options.complete = function () { if (!_this2.sequenceReject) return; _this2.sequenceReject = undefined; dispatch(window, "sequenceDone"); resolve(); }; try { _Velocity['default'].RunSequence(sequence); } catch (e) { _this2.stopSequence(sequence); _this2.sequenceReject(e); } }); } }, { key: 'stopSequence', value: function stopSequence(sequence) { var _this3 = this; sequence.map(function (item) { var el = item.e || item.element || item.elements; _this3.stop(el, true); }); if (this.sequenceReject) { this.sequenceReject(); this.sequenceReject = undefined; } dispatch(window, "sequenceDone"); return this; } }, { key: 'resolveEffectAlias', value: function resolveEffectAlias(alias) { if (typeof alias === "string" && alias[0] === ":") { return this.effects[alias]; } return alias; } }, { key: 'enter', value: function enter(element, effectName, options) { return this.stop(element, true)._runElementAnimation(element, effectName || ':enter', options, 'enter'); } }, { key: 'leave', value: function leave(element, effectName, options) { return this.stop(element, true)._runElementAnimation(element, effectName || ':leave', options, 'leave').then(function (elements) {}); } }, { key: '_runElements', value: function _runElements(element, name) { var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; if (!element) return Promise.reject(new Error("invalid first argument")); if (typeof element === "string") element = this.container.querySelectorAll(element); if (!element || element.length === 0) return Promise.resolve(element); for (var i = 0; i < element.length; i++) { this._runElementAnimation(element[i], name, options); } } }, { key: '_runElementAnimation', value: function _runElementAnimation(element, name) { var _this4 = this, _arguments = arguments; var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var eventName = arguments.length <= 3 || arguments[3] === undefined ? undefined : arguments[3]; if (!element) return Promise.reject(new Error("invalid first argument")); if (typeof element === "string") element = this.container.querySelectorAll(element); if (!element || element.length === 0) return Promise.resolve(element); if (!element.animations) this.parseAttributes(element); if (eventName) dispatch(element, eventName + "Begin"); var overrides = { complete: function complete(elements) { _this4.isAnimating = false; if (eventName) dispatch(element, eventName + "Done"); if (options && options.complete) options.complete.apply(_this4, _arguments); } }; var opts = Object.assign({}, this.options, options, overrides); return this.animate(element, name, opts, true); } }, { key: 'parseAttributes', value: function parseAttributes(element) { var el = undefined, i = undefined, l = undefined; element = this.ensureList(element); for (i = 0, l = element.length; i < l; i++) { el = element[i]; el.animations = {}; el.animations.enter = this.parseAttributeValue(el.getAttribute('anim-enter')) || this.enterAnimation; el.animations.leave = this.parseAttributeValue(el.getAttribute('anim-leave')) || this.leaveAnimation; } } }, { key: 'parseAttributeValue', value: function parseAttributeValue(value) { if (!value) return value; var p = value.split(';'); var properties = p[0]; var options = {}; if (properties[0] == '{' && properties[properties.length - 1] == '}') properties = _JSOL['default'].parse(properties); if (p.length > 1) { options = p[1]; options = _JSOL['default'].parse(options); } return { properties: properties, options: options }; } }, { key: 'ensureList', value: function ensureList(element) { if (!Array.isArray(element) && !(element instanceof NodeList)) element = [element]; return element; } }]); return VelocityAnimator; })(); exports.VelocityAnimator = VelocityAnimator; function dispatch(element, name) { var evt = new CustomEvent(_aureliaTemplating.animationEvent[name], { bubbles: true, cancelable: true, detail: element }); document.dispatchEvent(evt); } }); //# sourceMappingURL=animator.js.map ; define('gooy-aurelia-animator-velocity/index',['exports', 'aurelia-templating', './animator'], function (exports, _aureliaTemplating, _animator) { Object.defineProperty(exports, '__esModule', { value: true }); exports.configure = configure; Object.defineProperty(exports, 'VelocityAnimator', { enumerable: true, get: function get() { return _animator.VelocityAnimator; } }); function configure(aurelia, cb) { var animator = aurelia.container.get(_animator.VelocityAnimator); _aureliaTemplating.Animator.configureDefault(aurelia.container, animator); if (cb !== undefined && typeof cb === 'function') cb(animator); } }); //# sourceMappingURL=index.js.map ; define('gooy-aurelia-animator-velocity', ['gooy-aurelia-animator-velocity/index'], function (main) { return main; }); /** * @license RequireJS text 2.0.14 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/requirejs/text for details */ /*jslint regexp: true */ /*global require, XMLHttpRequest, ActiveXObject, define, window, process, Packages, java, location, Components, FileUtils */ define('text',['module'], function (module) { var text, fs, Cc, Ci, xpcIsWindows, progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im, hasLocation = typeof location !== 'undefined' && location.href, defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''), defaultHostName = hasLocation && location.hostname, defaultPort = hasLocation && (location.port || undefined), buildMap = {}, masterConfig = (module.config && module.config()) || {}; text = { version: '2.0.14', strip: function (content) { //Strips <?xml ...?> declarations so that external SVG and XML //documents can be added to a document without worry. Also, if the string //is an HTML document, only the part inside the body tag is returned. if (content) { content = content.replace(xmlRegExp, ""); var matches = content.match(bodyRegExp); if (matches) { content = matches[1]; } } else { content = ""; } return content; }, jsEscape: function (content) { return content.replace(/(['\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r") .replace(/[\u2028]/g, "\\u2028") .replace(/[\u2029]/g, "\\u2029"); }, createXhr: masterConfig.createXhr || function () { //Would love to dump the ActiveX crap in here. Need IE 6 to die first. var xhr, i, progId; if (typeof XMLHttpRequest !== "undefined") { return new XMLHttpRequest(); } else if (typeof ActiveXObject !== "undefined") { for (i = 0; i < 3; i += 1) { progId = progIds[i]; try { xhr = new ActiveXObject(progId); } catch (e) {} if (xhr) { progIds = [progId]; // so faster next time break; } } } return xhr; }, /** * Parses a resource name into its component parts. Resource names * look like: module/name.ext!strip, where the !strip part is * optional. * @param {String} name the resource name * @returns {Object} with properties "moduleName", "ext" and "strip" * where strip is a boolean. */ parseName: function (name) { var modName, ext, temp, strip = false, index = name.lastIndexOf("."), isRelative = name.indexOf('./') === 0 || name.indexOf('../') === 0; if (index !== -1 && (!isRelative || index > 1)) { modName = name.substring(0, index); ext = name.substring(index + 1); } else { modName = name; } temp = ext || modName; index = temp.indexOf("!"); if (index !== -1) { //Pull off the strip arg. strip = temp.substring(index + 1) === "strip"; temp = temp.substring(0, index); if (ext) { ext = temp; } else { modName = temp; } } return { moduleName: modName, ext: ext, strip: strip }; }, xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/, /** * Is an URL on another domain. Only works for browser use, returns * false in non-browser environments. Only used to know if an * optimized .js version of a text resource should be loaded * instead. * @param {String} url * @returns Boolean */ useXhr: function (url, protocol, hostname, port) { var uProtocol, uHostName, uPort, match = text.xdRegExp.exec(url); if (!match) { return true; } uProtocol = match[2]; uHostName = match[3]; uHostName = uHostName.split(':'); uPort = uHostName[1]; uHostName = uHostName[0]; return (!uProtocol || uProtocol === protocol) && (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) && ((!uPort && !uHostName) || uPort === port); }, finishLoad: function (name, strip, content, onLoad) { content = strip ? text.strip(content) : content; if (masterConfig.isBuild) { buildMap[name] = content; } onLoad(content); }, load: function (name, req, onLoad, config) { //Name has format: some.module.filext!strip //The strip part is optional. //if strip is present, then that means only get the string contents //inside a body tag in an HTML string. For XML/SVG content it means //removing the <?xml ...?> declarations so the content can be inserted //into the current doc without problems. // Do not bother with the work if a build and text will // not be inlined. if (config && config.isBuild && !config.inlineText) { onLoad(); return; } masterConfig.isBuild = config && config.isBuild; var parsed = text.parseName(name), nonStripName = parsed.moduleName + (parsed.ext ? '.' + parsed.ext : ''), url = req.toUrl(nonStripName), useXhr = (masterConfig.useXhr) || text.useXhr; // Do not load if it is an empty: url if (url.indexOf('empty:') === 0) { onLoad(); return; } //Load the text. Use XHR if possible and in a browser. if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) { text.get(url, function (content) { text.finishLoad(name, parsed.strip, content, onLoad); }, function (err) { if (onLoad.error) { onLoad.error(err); } }); } else { //Need to fetch the resource across domains. Assume //the resource has been optimized into a JS module. Fetch //by the module name + extension, but do not include the //!strip part to avoid file system issues. req([nonStripName], function (content) { text.finishLoad(parsed.moduleName + '.' + parsed.ext, parsed.strip, content, onLoad); }); } }, write: function (pluginName, moduleName, write, config) { if (buildMap.hasOwnProperty(moduleName)) { var content = text.jsEscape(buildMap[moduleName]); write.asModule(pluginName + "!" + moduleName, "define(function () { return '" + content + "';});\n"); } }, writeFile: function (pluginName, moduleName, req, write, config) { var parsed = text.parseName(moduleName), extPart = parsed.ext ? '.' + parsed.ext : '', nonStripName = parsed.moduleName + extPart, //Use a '.js' file name so that it indicates it is a //script that can be loaded across domains. fileName = req.toUrl(parsed.moduleName + extPart) + '.js'; //Leverage own load() method to load plugin value, but only //write out values that do not have the strip argument, //to avoid any potential issues with ! in file names. text.load(nonStripName, req, function (value) { //Use own write() method to construct full module value. //But need to create shell that translates writeFile's //write() to the right interface. var textWrite = function (contents) { return write(fileName, contents); }; textWrite.asModule = function (moduleName, contents) { return write.asModule(moduleName, fileName, contents); }; text.write(pluginName, nonStripName, textWrite, config); }, config); } }; if (masterConfig.env === 'node' || (!masterConfig.env && typeof process !== "undefined" && process.versions && !!process.versions.node && !process.versions['node-webkit'] && !process.versions['atom-shell'])) { //Using special require.nodeRequire, something added by r.js. fs = require.nodeRequire('fs'); text.get = function (url, callback, errback) { try { var file = fs.readFileSync(url, 'utf8'); //Remove BOM (Byte Mark Order) from utf8 files if it is there. if (file[0] === '\uFEFF') { file = file.substring(1); } callback(file); } catch (e) { if (errback) { errback(e); } } }; } else if (masterConfig.env === 'xhr' || (!masterConfig.env && text.createXhr())) { text.get = function (url, callback, errback, headers) { var xhr = text.createXhr(), header; xhr.open('GET', url, true); //Allow plugins direct access to xhr headers if (headers) { for (header in headers) { if (headers.hasOwnProperty(header)) { xhr.setRequestHeader(header.toLowerCase(), headers[header]); } } } //Allow overrides specified in config if (masterConfig.onXhr) { masterConfig.onXhr(xhr, url); } xhr.onreadystatechange = function (evt) { var status, err; //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { status = xhr.status || 0; if (status > 399 && status < 600) { //An http 4xx or 5xx error. Signal an error. err = new Error(url + ' HTTP status: ' + status); err.xhr = xhr; if (errback) { errback(err); } } else { callback(xhr.responseText); } if (masterConfig.onXhrComplete) { masterConfig.onXhrComplete(xhr, url); } } }; xhr.send(null); }; } else if (masterConfig.env === 'rhino' || (!masterConfig.env && typeof Packages !== 'undefined' && typeof java !== 'undefined')) { //Why Java, why is this so awkward? text.get = function (url, callback) { var stringBuffer, line, encoding = "utf-8", file = new java.io.File(url), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), content = ''; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 // http://www.unicode.org/faq/utf_bom.html // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 if (line && line.length() && line.charAt(0) === 0xfeff) { // Eat the BOM, since we've already found the encoding on this file, // and we plan to concatenating this buffer with others; the BOM should // only appear at the top of a file. line = line.substring(1); } if (line !== null) { stringBuffer.append(line); } while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator); stringBuffer.append(line); } //Make sure we return a JavaScript string and not a Java string. content = String(stringBuffer.toString()); //String } finally { input.close(); } callback(content); }; } else if (masterConfig.env === 'xpconnect' || (!masterConfig.env && typeof Components !== 'undefined' && Components.classes && Components.interfaces)) { //Avert your gaze! Cc = Components.classes; Ci = Components.interfaces; Components.utils['import']('resource://gre/modules/FileUtils.jsm'); xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc); text.get = function (url, callback) { var inStream, convertStream, fileObj, readData = {}; if (xpcIsWindows) { url = url.replace(/\//g, '\\'); } fileObj = new FileUtils.File(url); //XPCOM, you so crazy try { inStream = Cc['@mozilla.org/network/file-input-stream;1'] .createInstance(Ci.nsIFileInputStream); inStream.init(fileObj, 1, 0, false); convertStream = Cc['@mozilla.org/intl/converter-input-stream;1'] .createInstance(Ci.nsIConverterInputStream); convertStream.init(inStream, "utf-8", inStream.available(), Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); convertStream.readString(inStream.available(), readData); convertStream.close(); inStream.close(); callback(readData.value); } catch (e) { throw new Error((fileObj && fileObj.path || '') + ': ' + e); } }; } return text; }); define("aurelia-bundle-manifest", [ 'aurelia-path', // 'aurelia-dialog', // 'aurelia-dialog/ai-dialog-body', // 'text!aurelia-dialog/ai-dialog-body.html', // 'aurelia-dialog/ai-dialog-footer', // 'text!aurelia-dialog/ai-dialog-footer.html', // 'aurelia-dialog/ai-dialog', // 'text!aurelia-dialog/ai-dialog.html', // 'text!aurelia-dialog/dialog.css', 'aurelia-loader', 'aurelia-loader-default', 'aurelia-task-queue', 'aurelia-logging', 'aurelia-logging-console', 'aurelia-history', 'aurelia-history-browser', 'aurelia-event-aggregator', 'aurelia-framework', 'aurelia-metadata', 'aurelia-binding', 'aurelia-templating', 'aurelia-dependency-injection', 'aurelia-router', 'aurelia-templating-binding', 'aurelia-templating-resources', 'aurelia-templating-router', 'aurelia-route-recognizer', 'aurelia-http-client', 'aurelia-fetch-client', 'aurelia-pal', 'aurelia-pal-browser', 'fetch', 'aurelia-bootstrapper', 'aurelia-html-template-element', 'aurelia-validation', 'aurelia-animator-css', 'gooy-aurelia-animator-velocity', 'jsol', 'velocity', 'text' ], function(_path, _loader, _loader_default, _task_queue, _logging, _logging_console, _history, _history_browser, _event_aggregator, _framework, _metadata, _binding, _templating, _dependency_injection, _router, _templating_binding, _templating_resources, _templating_router, _route_recognizer, _http_client, _bootstrapper, _html_template_element, _validation ){ // alert(_dependency_injection.inject) });
require("../index"); function withObject(published) { let testObject = { name: "Awesome App", type: "App" }.whatIf( published, ctx => { //perform complex computations here //and change the object based on that. ctx["output"] = "The app is published."; } ); return testObject; } function withBuilder(published) { let builder = "I am a string builder." .trim() .slice(2) .whatIf(published, ctx => { return ctx.toLowerCase(); }) .toUpperCase(); return builder; } function withArrays(addSix) { return [0, 1, 2, 3, 4, 5].whatIf(addSix, ctx => { return ctx.concat(6); }); } function withFunctions(doMultiplication, doDivision) { function add(...params) { return params.reduce((p, c) => p + c); } function multiply(...params) { return params.reduce((p, c) => p * c); } function divide(...params) { return params.reduce((p, c) => p / c); } let paramaters = [21, 23, 41, 51, 5, 1]; let result = add .whatIf(doMultiplication, multiply) .whatIf(doDivision, divide) .call(this, ...paramaters); return result; } //let's get a little bit complex function DMAS(input) { function add(...params) { let ret = params.reduce((p, c) => parseInt(p) + parseInt(c)); return ret; } function multiply(...params) { return params.reduce((p, c) => p * c); } function divide(...params) { return params.reduce((p, c) => p / c); } function subtract(...params) { return params.reduce((p, c) => p - c); } input = input.split(" "); let output = [...input]; const get = operator => output .filter( (v, i) => i % 2 === 0 && (output[i + 1] === operator || output[i - 1] === operator) ) .slice(0, 2); const perform = (operator, operation, output) => { let values = get(operator); if (values.length <= 0) return output; output.splice(output.indexOf(values[0]), 3, operation(...values)); return output; }; const hasOperator = operator => get(operator).length > 0; while (output.length !== 1) { output = perform .bind(this, "/", divide, output) .whatIf(hasOperator("*"), perform.bind(this, "*", multiply)) .whatIf(hasOperator("+"), perform.bind(this, "+", add)) .whatIf(hasOperator("-"), perform.bind(this, "-", subtract)); } return output[0]; } function withBoolean(stopWork) { //direct usage with boolean stopWork.whatIf(function() { console.log("Stop working man!"); }); } function bookBuilder(published) { let book = " I am a book. " .trim() //whatIf can be used anywhere .whatIf(published, function() { console.log(this); return this.concat(" And I am published."); }) .toUpperCase(); return book; // -> I AM A BOOK. AND I AM PUBLISHED. } function differentReturnType(getLength) { let stringLength = "i am a string".whatIf(getLength, function() { return this.length; }); console.log(stringLength, typeof stringLength); } function whatIfNotUsage(result) { result.whatIfNotNull( function() { console.log(result + " is not null."); }, function() { console.log(result + " is null"); } ); }
"use strict"; const events_1 = require("events"); const buffer_1 = require("buffer"); const dgram = require("dgram"); const debug = require("debug"); debug("trackerClient"); const writeUInt64BE = require("writeUInt64BE"), ACTION_CONNECT = 0, ACTION_ANNOUNCE = 1, ACTION_SCRAPE = 2, ACTION_ERROR = 3; let connectionIdHigh = 0x417, connectionIdLow = 0x27101980; class UdpTracker extends events_1.EventEmitter { constructor(type, trackerHost, port, myPort, infoHash, left, uploaded, downloaded) { super(); if (!(this instanceof UdpTracker)) return new UdpTracker(type, trackerHost, port, myPort, infoHash, left, uploaded, downloaded); const self = this; self.USER = "-EM0012-" + guidvC(); self.CASE = type; self.HOST = trackerHost; self.HASH = infoHash; self.PORT = port; self.MY_PORT = myPort; self.TRANSACTION_ID = null; // This will be our method of keeping track of new connections... self.EVENT = 0; // Avoid scraping unless it's a timed update self.SCRAPE = true; self.LEFT = left; self.UPLOADED = uploaded; self.DOWNLOADED = downloaded; self.KEY = 0; self.IP_ADDRESS = 0; // Default unless behind a proxy // Setup server self.server = dgram.createSocket("udp4"); self.server.on("listening", function () { switch (self.CASE) { case "start": self.EVENT = 2; break; case "stop": self.EVENT = 3; setTimeout(() => { // Close the server self.server.close(); }, 300); break; case "complete": self.EVENT = 1; break; case "update": self.EVENT = 0; break; case "scrape": self.scrape(); self.EVENT = 2; return; default: self.emit("error", "Bad call signature."); return; } self.announce(); }); self.server.on("message", function (msg, rinfo) { self.message(msg, rinfo); }); self.server.bind(self.MY_PORT); } sendPacket(buf) { const self = this; self.server.send(buf, 0, buf.length, self.PORT, self.HOST, (err) => { if (err) { self.emit("error", err); } }); } startConnection() { const self = this; // Prepare for the next connection: self.TRANSACTION_ID = ~~((Math.random() * 100000) + 1); // Prep a packet for delivery: let buf = new buffer_1.Buffer(16); buf.fill(0); buf.writeUInt32BE(connectionIdHigh, 0); // 0 64-bit integer connection_id 0x41727101980 buf.writeUInt32BE(connectionIdLow, 4); // 0 64-bit integer connection_id 0x41727101980 buf.writeUInt32BE(ACTION_CONNECT, 8); // 8 32-bit integer action 0 // connect buf.writeUInt32BE(self.TRANSACTION_ID, 12); // 12 32-bit integer transaction_id // Send packet self.sendPacket(buf); } scrape() { const self = this; if (!self.TRANSACTION_ID) { self.startConnection(); } else { let buf = new buffer_1.Buffer(36); buf.fill(0); buf.writeUInt32BE(connectionIdHigh, 0); // 0 64-bit integer connection_id 0x41727101980 buf.writeUInt32BE(connectionIdLow, 4); // 0 64-bit integer connection_id 0x41727101980 buf.writeUInt32BE(ACTION_SCRAPE, 8); // 8 32-bit integer action 2 // scrape buf.writeUInt32BE(self.TRANSACTION_ID, 12); // 12 32-bit integer transaction_id buf.write(self.HASH, 16, 20, "hex"); // 16 + 20 * n 20-byte string info_hash // Send Packet self.sendPacket(buf); } } announce() { // EVENT: 0: none; 1: completed; 2: started; 3: stopped const self = this; if (!self.TRANSACTION_ID) { self.startConnection(); } else { // Prepare announce packet for delivery let buf = new buffer_1.Buffer(98); buf.fill(0); buf.writeUInt32BE(connectionIdHigh, 0); // 0 64-bit integer connection_id buf.writeUInt32BE(connectionIdLow, 4); // 0 64-bit integer connection_id buf.writeUInt32BE(ACTION_ANNOUNCE, 8); // 8 32-bit integer action 1 // announce buf.writeUInt32BE(self.TRANSACTION_ID, 12); // 12 32-bit integer transaction_id buf.write(self.HASH, 16, 20, "hex"); // 16 20-byte string info_hash buf.write(self.USER, 36, 20); // 36 20-byte string peer_id writeUInt64BE(buf, self.DOWNLOADED, 56); // 56 64-bit integer downloaded writeUInt64BE(buf, self.LEFT, 64); // 64 64-bit integer left writeUInt64BE(buf, self.UPLOADED, 72); // 72 64-bit integer uploaded buf.writeUInt32BE(self.EVENT, 80); // 80 32-bit integer event 0 // 0: none; 1: completed; 2: started; 3: stopped buf.writeUInt32BE(self.IP_ADDRESS, 84); // 84 32-bit integer IP address 0 // default buf.writeUInt32BE(self.KEY, 88); // 88 32-bit integer key buf.writeInt32BE((-1), 92); // 92 32-bit integer num_want -1 // default buf.writeUInt16BE(self.MY_PORT, 96); // 96 16-bit integer port // Send Packet self.sendPacket(buf); self.TRANSACTION_ID = null; connectionIdHigh = 0x417, connectionIdLow = 0x27101980; } } message(msg, rinfo) { const self = this; let buf = new buffer_1.Buffer(msg); let action = buf.readUInt32BE(0); // 0 32-bit integer action 0 // connect 1 // announce 2 // scrape 3 // error self.TRANSACTION_ID = buf.readUInt32BE(4); // 4 32-bit integer transaction_id if (action === ACTION_CONNECT) { // Server will establish a new connection_id to talk on. // This connection_id dies after 5-10 seconds. connectionIdHigh = buf.readUInt32BE(8); // 0 64-bit integer connection_id connectionIdLow = buf.readUInt32BE(12); // 0 64-bit integer connection_id // Announce self.announce(); } else if (action === ACTION_SCRAPE) { let seeders = buf.readUInt32BE(8), // 8 32-bit integer interval completed = buf.readUInt32BE(12), // 12 32-bit integer completed leechers = buf.readUInt32BE(16); // 16 32-bit integer leechers self.emit("scrape", seeders, completed, leechers); self.announce(); } else if (action === ACTION_ANNOUNCE) { let interval = buf.readUInt32BE(8), // 8 32-bit integer interval leechers = buf.readUInt32BE(12), // 12 32-bit integer leechers seeders = buf.readUInt32BE(16), // 16 32-bit integer seeders bufLength = buf.length, // 20 + 6 * n 32-bit integer IP address addresses = []; // 24 + 6 * n 16-bit integer TCP port for (let i = 20; i < bufLength; i += 6) { let address = `${buf.readUInt8(i)}.${buf.readUInt8(i + 1)}.${buf.readUInt8(i + 2)}.${buf.readUInt8(i + 3)}:${buf.readUInt16BE(i + 4)}`; addresses.push(address); } // Send up self.emit("announce", interval, leechers, seeders, addresses); // Close the server self.server.close(); } else if (action === ACTION_ERROR) { let errorResponce = buf.slice(8).toString(); self.emit("error", errorResponce); // Close the server self.server.close(); } } } exports.UdpTracker = UdpTracker; class WssTracker extends events_1.EventEmitter { constructor() { super(); if (!(this instanceof WssTracker)) return new WssTracker(); const self = this; } } exports.WssTracker = WssTracker; function guidvC() { return Math.floor((1 + Math.random()) * 0x1000000000000) .toString(16) .substring(1); } //# sourceMappingURL=/Users/connor/Desktop/2017/PeerTracker/node/ts-node/353b28c3f89e3a261f0cbb6f237ac05d54f482d5/d19c293277f737dbaf39e2827ecd4ce799b43dd6.js.map
/** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ define([ 'Magento_Paypal/js/rules/simple/disable', 'underscore' ], function (disable, _) { 'use strict'; return function ($target, $owner, data) { var isDisabled = true; _.every(data.argument, function (name) { if (data.solutionsElements[name] && data.solutionsElements[name].find(data.enableButton).val() === '1' ) { isDisabled = false; return isDisabled; } return isDisabled; }, this); if (isDisabled) { disable($target, $owner, data); } }; });
"use strict"; class PageFilterEquipment extends PageFilter { constructor ({filterOpts = null} = {}) { super(); this._typeFilter = new Filter({ header: "Type", deselFn: (it) => PageFilterItems._DEFAULT_HIDDEN_TYPES.has(it), displayFn: StrUtil.toTitleCase, }); this._propertyFilter = new Filter({header: "Property", displayFn: StrUtil.uppercaseFirst}); this._categoryFilter = new Filter({ header: "Category", items: ["Basic", "Generic Variant", "Specific Variant", "Other"], deselFn: (it) => it === "Specific Variant", itemSortFn: null, ...(filterOpts?.["Category"] || {}), }); this._costFilter = new RangeFilter({ header: "Cost", isLabelled: true, isAllowGreater: true, labelSortFn: null, labels: [ 0, ...[...new Array(9)].map((_, i) => i + 1), ...[...new Array(9)].map((_, i) => 10 * (i + 1)), ...[...new Array(100)].map((_, i) => 100 * (i + 1)), ], labelDisplayFn: it => !it ? "None" : Parser.getDisplayCurrency(CurrencyUtil.doSimplifyCoins({cp: it})), }); this._weightFilter = new RangeFilter({header: "Weight", min: 0, max: 100, isAllowGreater: true, suffix: " lb."}); this._focusFilter = new Filter({header: "Spellcasting Focus", items: [...Parser.ITEM_SPELLCASTING_FOCUS_CLASSES]}); this._damageTypeFilter = new Filter({header: "Weapon Damage Type", displayFn: it => Parser.dmgTypeToFull(it).uppercaseFirst(), itemSortFn: (a, b) => SortUtil.ascSortLower(Parser.dmgTypeToFull(a), Parser.dmgTypeToFull(b))}); this._miscFilter = new Filter({header: "Miscellaneous", items: ["Item Group", "SRD", "Basic Rules", "Has Images", "Has Info"], isMiscFilter: true}); this._poisonTypeFilter = new Filter({header: "Poison Type", items: ["ingested", "injury", "inhaled", "contact"], displayFn: StrUtil.toTitleCase}); } static mutateForFilters (item) { item._fSources = SourceFilter.getCompleteFilterSources(item); item._fProperties = item.property ? item.property.map(p => Renderer.item.propertyMap[p].name).filter(n => n) : []; item._fMisc = []; if (item._isItemGroup) item._fMisc.push("Item Group"); if (item.srd) item._fMisc.push("SRD"); if (item.basicRules) item._fMisc.push("Basic Rules"); if (item.hasFluff) item._fMisc.push("Has Info"); if (item.hasFluffImages) item._fMisc.push("Has Images"); if (item.miscTags) item._fMisc.push(...item.miscTags.map(Parser.itemMiscTagToFull)); if (item.focus || item.name === "Thieves' Tools" || item.type === "INS" || item.type === "SCF" || item.type === "AT") { item._fFocus = item.focus ? item.focus === true ? [...Parser.ITEM_SPELLCASTING_FOCUS_CLASSES] : [...item.focus] : []; if ((item.name === "Thieves' Tools" || item.type === "AT") && !item._fFocus.includes("Artificer")) item._fFocus.push("Artificer"); if (item.type === "INS" && !item._fFocus.includes("Bard")) item._fFocus.push("Bard"); if (item.type === "SCF") { switch (item.scfType) { case "arcane": { if (!item._fFocus.includes("Sorcerer")) item._fFocus.push("Sorcerer"); if (!item._fFocus.includes("Warlock")) item._fFocus.push("Warlock"); if (!item._fFocus.includes("Wizard")) item._fFocus.push("Wizard"); break; } case "druid": { if (!item._fFocus.includes("Druid")) item._fFocus.push("Druid"); break; } case "holy": if (!item._fFocus.includes("Cleric")) item._fFocus.push("Cleric"); if (!item._fFocus.includes("Paladin")) item._fFocus.push("Paladin"); break; } } } item._fValue = item.value || 0; } addToFilters (item, isExcluded) { if (isExcluded) return; this._sourceFilter.addItem(item._fSources); this._typeFilter.addItem(item._typeListText); this._propertyFilter.addItem(item._fProperties); this._damageTypeFilter.addItem(item.dmgType); this._poisonTypeFilter.addItem(item.poisonTypes); this._miscFilter.addItem(item._fMisc); } async _pPopulateBoxOptions (opts) { opts.filters = [ this._sourceFilter, this._typeFilter, this._propertyFilter, this._categoryFilter, this._costFilter, this._weightFilter, this._focusFilter, this._damageTypeFilter, this._miscFilter, this._poisonTypeFilter, ]; } toDisplay (values, it) { return this._filterBox.toDisplay( values, it._fSources, it._typeListText, it._fProperties, it._category, it._fValue, it.weight, it._fFocus, it.dmgType, it._fMisc, it.poisonTypes, ); } } class PageFilterItems extends PageFilterEquipment { // region static static sortItems (a, b, o) { if (o.sortBy === "name") return SortUtil.compareListNames(a, b); else if (o.sortBy === "type") return SortUtil.ascSortLower(a.values.type, b.values.type) || SortUtil.compareListNames(a, b); else if (o.sortBy === "source") return SortUtil.ascSortLower(a.values.source, b.values.source) || SortUtil.compareListNames(a, b); else if (o.sortBy === "rarity") return SortUtil.ascSortItemRarity(a.values.rarity, b.values.rarity) || SortUtil.compareListNames(a, b); else if (o.sortBy === "attunement") return SortUtil.ascSort(a.values.attunement, b.values.attunement) || SortUtil.compareListNames(a, b); else if (o.sortBy === "count") return SortUtil.ascSort(a.data.count, b.data.count) || SortUtil.compareListNames(a, b); else if (o.sortBy === "weight") return SortUtil.ascSort(a.values.weight, b.values.weight) || SortUtil.compareListNames(a, b); else if (o.sortBy === "cost") return SortUtil.ascSort(a.values.cost, b.values.cost) || SortUtil.compareListNames(a, b); else return 0; } static _getBaseItemDisplay (baseItem) { if (!baseItem) return null; let [name, source] = baseItem.split("|"); name = name.toTitleCase(); source = source || SRC_DMG; if (source.toLowerCase() === SRC_PHB.toLowerCase()) return name; return `${name} (${Parser.sourceJsonToAbv(source)})`; } static _sortAttunementFilter (a, b) { const ixA = PageFilterItems._FILTER_BASE_ITEMS_ATTUNEMENT.indexOf(a.item); const ixB = PageFilterItems._FILTER_BASE_ITEMS_ATTUNEMENT.indexOf(b.item); if (~ixA && ~ixB) return ixA - ixB; if (~ixA) return -1; if (~ixB) return 1; return SortUtil.ascSortLower(a, b); } static _getAttunementFilterItems (item) { const out = item._attunementCategory ? [item._attunementCategory] : []; if (!item.reqAttuneTags && !item.reqAttuneAltTags) return out; [...item.reqAttuneTags || [], ...item.reqAttuneAltTags || []].forEach(tagSet => { Object.entries(tagSet) .forEach(([prop, val]) => { switch (prop) { case "background": out.push(`Background: ${val.split("|")[0].toTitleCase()}`); break; case "languageProficiency": out.push(`Language Proficiency: ${val.toTitleCase()}`); break; case "skillProficiency": out.push(`Skill Proficiency: ${val.toTitleCase()}`); break; case "race": out.push(`Race: ${val.split("|")[0].toTitleCase()}`); break; case "creatureType": out.push(`Creature Type: ${val.toTitleCase()}`); break; case "size": out.push(`Size: ${Parser.sizeAbvToFull(val)}`.toTitleCase()); break; case "class": out.push(`Class: ${val.split("|")[0].toTitleCase()}`); break; case "alignment": out.push(`Alignment: ${Parser.alignmentListToFull(val).toTitleCase()}`); break; case "str": case "dex": case "con": case "int": case "wis": case "cha": out.push(`${Parser.attAbvToFull(prop)}: ${val} or Higher`); break; case "spellcasting": out.push("Spellcaster"); break; case "psionics": out.push("Psionics"); break; } }); }); return out; } // endregion constructor (opts) { super(opts); this._tierFilter = new Filter({header: "Tier", items: ["none", "minor", "major"], itemSortFn: null, displayFn: StrUtil.toTitleCase}); this._attachedSpellsFilter = new Filter({header: "Attached Spells", displayFn: (it) => it.split("|")[0].toTitleCase(), itemSortFn: SortUtil.ascSortLower}); this._lootTableFilter = new Filter({ header: "Found On", items: ["Magic Item Table A", "Magic Item Table B", "Magic Item Table C", "Magic Item Table D", "Magic Item Table E", "Magic Item Table F", "Magic Item Table G", "Magic Item Table H", "Magic Item Table I"], displayFn: it => { const [name, sourceJson] = it.split("|"); return `${name}${sourceJson ? ` (${Parser.sourceJsonToAbv(sourceJson)})` : ""}`; }, }); this._rarityFilter = new Filter({ header: "Rarity", items: [...Parser.ITEM_RARITIES], itemSortFn: null, displayFn: StrUtil.toTitleCase, }); this._attunementFilter = new Filter({header: "Attunement", items: [...PageFilterItems._FILTER_BASE_ITEMS_ATTUNEMENT], itemSortFn: PageFilterItems._sortAttunementFilter}); this._bonusFilter = new Filter({header: "Bonus", items: ["Armor Class", "Proficiency Bonus", "Spell Attacks", "Spell Save DC", "Saving Throws", "Weapon Attack and Damage Rolls", "Weapon Attack Rolls", "Weapon Damage Rolls"]}); this._rechargeTypeFilter = new Filter({header: "Recharge Type", displayFn: Parser.itemRechargeToFull}); this._miscFilter = new Filter({header: "Miscellaneous", items: ["Ability Score Adjustment", "Charges", "Cursed", "Grants Proficiency", "Has Images", "Has Info", "Item Group", "Magic", "Mundane", "Sentient", "Speed Adjustment", "SRD", "Basic Rules"], isMiscFilter: true}); this._baseSourceFilter = new SourceFilter({header: "Base Source", selFn: null}); this._baseItemFilter = new Filter({header: "Base Item", displayFn: this.constructor._getBaseItemDisplay.bind(this.constructor)}); } static mutateForFilters (item) { super.mutateForFilters(item); item._fTier = [item.tier ? item.tier : "none"]; if (item.curse) item._fMisc.push("Cursed"); const isMundane = Renderer.item.isMundane(item); item._fMisc.push(isMundane ? "Mundane" : "Magic"); item._fIsMundane = isMundane; if (item.ability) item._fMisc.push("Ability Score Adjustment"); if (item.modifySpeed) item._fMisc.push("Speed Adjustment"); if (item.charges) item._fMisc.push("Charges"); if (item.sentient) item._fMisc.push("Sentient"); if (item.grantsProficiency) item._fMisc.push("Grants Proficiency"); if (item.critThreshold) item._fMisc.push("Expanded Critical Range"); item._fBaseItemSelf = item._isBaseItem ? `${item.name}|${item.source}`.toLowerCase() : null; item._fBaseItem = [ item.baseItem ? (item.baseItem.includes("|") ? item.baseItem : `${item.baseItem}|${SRC_DMG}`).toLowerCase() : null, item._baseName ? `${item._baseName}|${item._baseSource || item.source}`.toLowerCase() : null, ].filter(Boolean); item._fBaseItemAll = item._fBaseItemSelf ? [item._fBaseItemSelf, ...item._fBaseItem] : item._fBaseItem; item._fBonus = []; if (item.bonusAc) item._fBonus.push("Armor Class"); if (item.bonusWeapon) item._fBonus.push("Weapon Attack and Damage Rolls"); if (item.bonusWeaponAttack) item._fBonus.push("Weapon Attack Rolls"); if (item.bonusWeaponDamage) item._fBonus.push("Weapon Damage Rolls"); if (item.bonusWeaponCritDamage) item._fBonus.push("Weapon Critical Damage"); if (item.bonusSpellAttack) item._fBonus.push("Spell Attacks"); if (item.bonusSpellSaveDc) item._fBonus.push("Spell Save DC"); if (item.bonusSavingThrow) item._fBonus.push("Saving Throws"); if (item.bonusProficiencyBonus) item._fBonus.push("Proficiency Bonus"); item._fAttunement = this._getAttunementFilterItems(item); } addToFilters (item, isExcluded) { if (isExcluded) return; super.addToFilters(item, isExcluded); this._sourceFilter.addItem(item.source); this._tierFilter.addItem(item._fTier); this._attachedSpellsFilter.addItem(item.attachedSpells); this._lootTableFilter.addItem(item.lootTables); this._baseItemFilter.addItem(item._fBaseItem); this._baseSourceFilter.addItem(item._baseSource); this._attunementFilter.addItem(item._fAttunement); this._rechargeTypeFilter.addItem(item.recharge); } async _pPopulateBoxOptions (opts) { await super._pPopulateBoxOptions(opts); opts.filters = [ this._sourceFilter, this._typeFilter, this._tierFilter, this._rarityFilter, this._propertyFilter, this._attunementFilter, this._categoryFilter, this._costFilter, this._weightFilter, this._focusFilter, this._damageTypeFilter, this._bonusFilter, this._miscFilter, this._rechargeTypeFilter, this._poisonTypeFilter, this._lootTableFilter, this._baseItemFilter, this._baseSourceFilter, this._attachedSpellsFilter, ]; } toDisplay (values, it) { return this._filterBox.toDisplay( values, it._fSources, it._typeListText, it._fTier, it.rarity, it._fProperties, it._fAttunement, it._category, it._fValue, it.weight, it._fFocus, it.dmgType, it._fBonus, it._fMisc, it.recharge, it.poisonTypes, it.lootTables, it._fBaseItemAll, it._baseSource, it.attachedSpells, ); } } PageFilterItems._DEFAULT_HIDDEN_TYPES = new Set(["treasure", "futuristic", "modern", "renaissance"]); PageFilterItems._FILTER_BASE_ITEMS_ATTUNEMENT = ["Requires Attunement", "Requires Attunement By...", "Attunement Optional", VeCt.STR_NO_ATTUNEMENT]; class ModalFilterItems extends ModalFilter { /** * @param opts * @param opts.namespace * @param [opts.isRadio] * @param [opts.allData] * @param [opts.pageFilterOpts] Options to be passed to the underlying items page filter. */ constructor (opts) { opts = opts || {}; super({ ...opts, modalTitle: `Item${opts.isRadio ? "" : "s"}`, pageFilter: new PageFilterItems(opts?.pageFilterOpts), }); } _$getColumnHeaders () { const btnMeta = [ {sort: "name", text: "Name", width: "4"}, {sort: "type", text: "Type", width: "6"}, {sort: "source", text: "Source", width: "1"}, ]; return ModalFilter._$getFilterColumnHeaders(btnMeta); } async _pInit () { await Renderer.item.populatePropertyAndTypeReference(); } async _pLoadAllData () { const brew = await BrewUtil.pAddBrewData(); const fromData = await Renderer.item.pBuildList({isAddGroups: true}); const fromBrew = await Renderer.item.pGetItemsFromHomebrew(brew); return [...fromData, ...fromBrew]; } _getListItem (pageFilter, item, itI) { if (item.noDisplay) return null; Renderer.item.enhanceItem(item); pageFilter.mutateAndAddToFilters(item); const eleRow = document.createElement("div"); eleRow.className = "px-0 w-100 ve-flex-col no-shrink"; const hash = UrlUtil.URL_TO_HASH_BUILDER[UrlUtil.PG_ITEMS](item); const source = Parser.sourceJsonToAbv(item.source); const type = item._typeListText.join(", "); eleRow.innerHTML = `<div class="w-100 ve-flex-vh-center lst--border no-select lst__wrp-cells"> <div class="col-0-5 pl-0 ve-flex-vh-center">${this._isRadio ? `<input type="radio" name="radio" class="no-events">` : `<input type="checkbox" class="no-events">`}</div> <div class="col-0-5 px-1 ve-flex-vh-center"> <div class="ui-list__btn-inline px-2" title="Toggle Preview (SHIFT to Toggle Info Preview)">[+]</div> </div> <div class="col-5 ${this._getNameStyle()}">${item.name}</div> <div class="col-5">${type.uppercaseFirst()}</div> <div class="col-1 text-center ${Parser.sourceJsonToColor(item.source)} pr-0" title="${Parser.sourceJsonToFull(item.source)}" ${BrewUtil.sourceJsonToStyle(item.source)}>${source}</div> </div>`; const btnShowHidePreview = eleRow.firstElementChild.children[1].firstElementChild; const listItem = new ListItem( itI, eleRow, item.name, { hash, source, sourceJson: item.source, type, }, { cbSel: eleRow.firstElementChild.firstElementChild.firstElementChild, btnShowHidePreview, }, ); ListUiUtil.bindPreviewButton(UrlUtil.PG_ITEMS, this._allData, listItem, btnShowHidePreview); return listItem; } }
// Wait for the document to finish loading before running any logic. $( document ).ready( function () { // Load metadata right away when page is ready. ( function () { loadMetadata(); } )(); // Click event listener for gamertag search button $( "#btnSearchGamertag" ).click( function () { // Clear any old content $( "#content" ).empty(); // *** Add your source code here *** } ); // Click event listener for match ID search button $( "#btnSearchMatchID" ).click( function () { // Clear any old content $( "#content" ).empty(); // *** Add your source code here *** } ); } )
/* global artifacts web3 */ var abi = require("ethereumjs-abi"); const SafeMathLib = artifacts.require("SafeMath"); const GoodGhostingContract = artifacts.require("GoodGhosting"); const GoodGhostingPolygonContract = artifacts.require("GoodGhostingPolygon"); const GoodGhostingPolygonWhitelisted = artifacts.require("GoodGhostingPolygonWhitelisted"); const BN = web3.utils.BN; const { providers, deployConfigs } = require("../deploy.config"); /** @dev truffle may use network name as "kovan-fork", for example, so we need to get the correct name to be used in the configs */ function getNetworkName(network) { if (Object.prototype.toString.call(network) !== "[object String]") { throw new Error(`Invalid value type for parameter "${network}"`); } const name = network.toLowerCase(); if (name.includes("kovan")) return "kovan"; if (name.includes("ropsten")) return "ropsten"; if (name.includes("mainnet")) return "mainnet"; if (name.includes("polygon")) return "polygon"; if (name.includes("alfajores")) return "alfajores"; if (name.includes("celo")) return "celo"; throw new Error(`Unsupported network "${network}"`); } function printSummary( // contract's constructor parameters { inboundCurrencyAddress, lendingPoolAddressProvider, segmentCount, segmentLength, segmentPaymentWei, earlyWithdrawFee, customFee, aaveContractAddress, maxPlayersCount, incentiveToken, incentiveController, wmatic, merkleRoot, }, // additional logging info { networkName, selectedProvider, inboundCurrencySymbol, segmentPayment, owner, } ) { const isPolygon = networkName.toLowerCase() === "polygon"; const isPolygonWhitelisted = networkName.toLowerCase() === "polygon-whitelisted" || ["polygon-whitelisted"].includes(networkName.toLowerCase()); // for local network var parameterTypes = [ "address", // inboundCurrencyAddress "address", // lendingPoolAddressProvider "uint256", // segmentCount "uint256", // segmentLength "uint256", // segmentPaymentWei "uint256", // earlyWithdrawFee "uint256", // customFee "address", // dataProvider/lending pool address "uint256", // maxPlayersCount "address" // incentiveToken ]; var parameterValues = [ inboundCurrencyAddress, lendingPoolAddressProvider, segmentCount, segmentLength, segmentPaymentWei, earlyWithdrawFee, customFee, aaveContractAddress, maxPlayersCount, incentiveToken ]; if (isPolygon) { parameterTypes.push( "address", // IncentiveController "address" // wmatic token ); parameterValues.push( incentiveController, wmatic ); } if (isPolygonWhitelisted) { parameterTypes.push( "address", // IncentiveController "address", // wmatic token "bytes32" // merkle root ); parameterValues.push( incentiveController, wmatic, merkleRoot ); } var encodedParameters = abi.rawEncode(parameterTypes, parameterValues); console.log("\n\n\n----------------------------------------------------"); console.log("GoogGhosting deployed with the following arguments:"); console.log("----------------------------------------------------\n"); console.log(`Network Name: ${networkName}`); console.log(`Contract's Owner: ${owner}`); console.log(`Lending Pool: ${selectedProvider}`); console.log(`Lending Pool Address Provider: ${lendingPoolAddressProvider}`); console.log(`Inbound Currency: ${inboundCurrencySymbol} at ${inboundCurrencyAddress}`); console.log(`Segment Count: ${segmentCount}`); console.log(`Segment Length: ${segmentLength} seconds`); console.log(`Segment Payment: ${segmentPayment} ${inboundCurrencySymbol} (${segmentPaymentWei} wei)`); console.log(`Early Withdrawal Fee: ${earlyWithdrawFee}%`); console.log(`Custom Pool Fee: ${customFee}%`); console.log(`Data Provider/Lending Pool Address: ${aaveContractAddress}`); console.log(`Max Quantity of Players: ${maxPlayersCount}`); console.log(`Incentive Token: ${incentiveToken}`); if (isPolygon) { console.log(`Incentive Controller: ${incentiveController}`); console.log(`Matic Token: ${wmatic}`); } if (isPolygonWhitelisted) { console.log(`Incentive Controller: ${incentiveController}`); console.log(`Matic Token: ${wmatic}`); console.log(`Merkle Root: ${merkleRoot}`); } console.log("\n\nConstructor Arguments ABI-Encoded:"); console.log(encodedParameters.toString("hex")); console.log("\n\n\n\n"); } module.exports = function (deployer, network, accounts) { // Injects network name into process .env variable to make accessible on test suite. process.env.NETWORK = network; // Skips migration for local tests and soliditycoverage if (["test", "soliditycoverage"].includes(network)) return; deployer.then(async () => { let networkName = getNetworkName(network); const poolConfigs = providers[deployConfigs.selectedProvider.toLowerCase()][networkName]; const lendingPoolAddressProvider = poolConfigs.lendingPoolAddressProvider; const inboundCurrencyAddress = poolConfigs[deployConfigs.inboundCurrencySymbol.toLowerCase()].address; const inboundCurrencyDecimals = poolConfigs[deployConfigs.inboundCurrencySymbol.toLowerCase()].decimals; const segmentPaymentWei = (deployConfigs.segmentPayment * 10 ** inboundCurrencyDecimals).toString(); const incentiveController = poolConfigs.incentiveController; const wmatic = poolConfigs.wmatic; const maxPlayersCount = deployConfigs.maxPlayersCount; const incentiveToken = poolConfigs.incentiveToken; let aaveContractAddress = poolConfigs.dataProvider; let goodGhostingContract = GoodGhostingContract; // defaults to Ethereum version if (network.includes("polygon-whitelisted")) { networkName = "polygon-whitelisted"; } if (networkName === "polygon") { goodGhostingContract = GoodGhostingPolygonContract; } else if (networkName === "polygon-whitelisted") { goodGhostingContract = GoodGhostingPolygonWhitelisted; } // Prepares deployment arguments const deploymentArgs = [ goodGhostingContract, inboundCurrencyAddress, lendingPoolAddressProvider, deployConfigs.segmentCount, deployConfigs.segmentLength, segmentPaymentWei, deployConfigs.earlyWithdrawFee, deployConfigs.customFee, aaveContractAddress, maxPlayersCount, incentiveToken ]; if (networkName === "polygon") { deploymentArgs.push( incentiveController, wmatic ); } else if (networkName === "polygon-whitelisted") { deploymentArgs.push( incentiveController, wmatic, deployConfigs.merkleroot ); } // Deploys GoodGhosting contract based on network await deployer.deploy(SafeMathLib); await deployer.link(SafeMathLib, goodGhostingContract); await deployer.deploy(...deploymentArgs); // Prints deployment summary printSummary( { inboundCurrencyAddress, lendingPoolAddressProvider, segmentCount: deployConfigs.segmentCount, segmentLength: deployConfigs.segmentLength, segmentPaymentWei, earlyWithdrawFee: deployConfigs.earlyWithdrawFee, customFee: deployConfigs.customFee, aaveContractAddress, maxPlayersCount, incentiveToken, incentiveController, wmatic, merkleRoot: deployConfigs.merkleroot, }, { networkName, selectedProvider: deployConfigs.selectedProvider, inboundCurrencySymbol: deployConfigs.inboundCurrencySymbol, segmentPayment: deployConfigs.segmentPayment, owner: accounts[0], } ); }); };
'use strict' import 'alpinejs' console.log(`I was loaded at ${Date(Date.now()).toString()}`);
/* * ../../../..//jax/output/HTML-CSS/fonts/STIX/General/Bold/MathBold.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ /************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/Bold/MathBold.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. * */ MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXGeneral-bold"], { 0x1d400: [690, 0, 722, 9, 689], // MATHEMATICAL BOLD CAPITAL A 0x1d401: [676, 0, 667, 16, 619], // MATHEMATICAL BOLD CAPITAL B 0x1d402: [691, 19, 722, 49, 687], // MATHEMATICAL BOLD CAPITAL C 0x1d403: [676, 0, 722, 14, 690], // MATHEMATICAL BOLD CAPITAL D 0x1d404: [676, 0, 667, 16, 641], // MATHEMATICAL BOLD CAPITAL E 0x1d405: [676, 0, 611, 16, 583], // MATHEMATICAL BOLD CAPITAL F 0x1d406: [691, 19, 778, 37, 755], // MATHEMATICAL BOLD CAPITAL G 0x1d407: [676, 0, 778, 21, 759], // MATHEMATICAL BOLD CAPITAL H 0x1d408: [676, 0, 389, 20, 370], // MATHEMATICAL BOLD CAPITAL I 0x1d409: [676, 96, 500, 3, 478], // MATHEMATICAL BOLD CAPITAL J 0x1d40a: [676, 0, 778, 30, 769], // MATHEMATICAL BOLD CAPITAL K 0x1d40b: [676, 0, 667, 19, 638], // MATHEMATICAL BOLD CAPITAL L 0x1d40c: [676, 0, 944, 14, 921], // MATHEMATICAL BOLD CAPITAL M 0x1d40d: [676, 18, 722, 16, 701], // MATHEMATICAL BOLD CAPITAL N 0x1d40e: [691, 19, 778, 35, 743], // MATHEMATICAL BOLD CAPITAL O 0x1d40f: [676, 0, 611, 16, 600], // MATHEMATICAL BOLD CAPITAL P 0x1d410: [691, 176, 778, 35, 743], // MATHEMATICAL BOLD CAPITAL Q 0x1d411: [676, 0, 722, 26, 716], // MATHEMATICAL BOLD CAPITAL R 0x1d412: [692, 19, 556, 35, 513], // MATHEMATICAL BOLD CAPITAL S 0x1d413: [676, 0, 667, 31, 636], // MATHEMATICAL BOLD CAPITAL T 0x1d414: [676, 19, 722, 16, 701], // MATHEMATICAL BOLD CAPITAL U 0x1d415: [676, 18, 722, 16, 701], // MATHEMATICAL BOLD CAPITAL V 0x1d416: [676, 15, 1000, 19, 981], // MATHEMATICAL BOLD CAPITAL W 0x1d417: [676, 0, 722, 16, 699], // MATHEMATICAL BOLD CAPITAL X 0x1d418: [676, 0, 722, 15, 699], // MATHEMATICAL BOLD CAPITAL Y 0x1d419: [676, 0, 667, 28, 634], // MATHEMATICAL BOLD CAPITAL Z 0x1d41a: [473, 14, 500, 25, 488], // MATHEMATICAL BOLD SMALL A 0x1d41b: [676, 14, 556, 17, 521], // MATHEMATICAL BOLD SMALL B 0x1d41c: [473, 14, 444, 25, 430], // MATHEMATICAL BOLD SMALL C 0x1d41d: [676, 14, 556, 25, 534], // MATHEMATICAL BOLD SMALL D 0x1d41e: [473, 14, 444, 25, 427], // MATHEMATICAL BOLD SMALL E 0x1d41f: [691, 0, 333, 14, 389], // MATHEMATICAL BOLD SMALL F 0x1d420: [473, 206, 500, 28, 483], // MATHEMATICAL BOLD SMALL G 0x1d421: [676, 0, 556, 15, 534], // MATHEMATICAL BOLD SMALL H 0x1d422: [691, 0, 278, 15, 256], // MATHEMATICAL BOLD SMALL I 0x1d423: [691, 203, 333, -57, 263], // MATHEMATICAL BOLD SMALL J 0x1d424: [676, 0, 556, 22, 543], // MATHEMATICAL BOLD SMALL K 0x1d425: [676, 0, 278, 15, 256], // MATHEMATICAL BOLD SMALL L 0x1d426: [473, 0, 833, 15, 814], // MATHEMATICAL BOLD SMALL M 0x1d427: [473, 0, 556, 21, 539], // MATHEMATICAL BOLD SMALL N 0x1d428: [473, 14, 500, 25, 476], // MATHEMATICAL BOLD SMALL O 0x1d429: [473, 205, 556, 19, 524], // MATHEMATICAL BOLD SMALL P 0x1d42a: [473, 205, 556, 34, 536], // MATHEMATICAL BOLD SMALL Q 0x1d42b: [473, 0, 444, 28, 434], // MATHEMATICAL BOLD SMALL R 0x1d42c: [473, 14, 389, 25, 361], // MATHEMATICAL BOLD SMALL S 0x1d42d: [630, 12, 333, 19, 332], // MATHEMATICAL BOLD SMALL T 0x1d42e: [461, 14, 556, 16, 538], // MATHEMATICAL BOLD SMALL U 0x1d42f: [461, 14, 500, 21, 485], // MATHEMATICAL BOLD SMALL V 0x1d430: [461, 14, 722, 23, 707], // MATHEMATICAL BOLD SMALL W 0x1d431: [461, 0, 500, 12, 484], // MATHEMATICAL BOLD SMALL X 0x1d432: [461, 205, 500, 16, 482], // MATHEMATICAL BOLD SMALL Y 0x1d433: [461, 0, 444, 21, 420], // MATHEMATICAL BOLD SMALL Z 0x1d7ce: [688, 13, 500, 24, 476], // MATHEMATICAL BOLD DIGIT ZERO 0x1d7cf: [688, 0, 500, 65, 441], // MATHEMATICAL BOLD DIGIT ONE 0x1d7d0: [688, 0, 500, 17, 478], // MATHEMATICAL BOLD DIGIT TWO 0x1d7d1: [688, 14, 500, 16, 468], // MATHEMATICAL BOLD DIGIT THREE 0x1d7d2: [688, 0, 500, 19, 476], // MATHEMATICAL BOLD DIGIT FOUR 0x1d7d3: [676, 8, 500, 22, 470], // MATHEMATICAL BOLD DIGIT FIVE 0x1d7d4: [688, 13, 500, 28, 475], // MATHEMATICAL BOLD DIGIT SIX 0x1d7d5: [676, 0, 500, 17, 477], // MATHEMATICAL BOLD DIGIT SEVEN 0x1d7d6: [688, 13, 500, 28, 472], // MATHEMATICAL BOLD DIGIT EIGHT 0x1d7d7: [688, 13, 500, 26, 473] // MATHEMATICAL BOLD DIGIT NINE }); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Bold/MathBold.js");
// middlewares dépendencies import { jwtService } from '../libs'; // middlewares import AuthMiddleware from './auth_middleware'; import csrf from './csrf'; // initialize middlewares with dependencies injection const auth = new AuthMiddleware(jwtService); // export all middlewares export { auth, csrf };
import PersonalDetails from "./PersonalDetails.vue"; import Shipping from "./Shipping.vue"; import Payment from "./Payment.vue"; import ConfirmOrder from "./ConfirmOrder.vue"; import OrderSummary from "./OrderSummary.vue"; import OrderReview from "./OrderReview.vue"; export { PersonalDetails, Shipping, Payment, ConfirmOrder, OrderSummary, OrderReview, };
// Menu.js import React from 'react'; import { bool } from 'prop-types'; import { StyledMenu } from './menu.css'; const Menu = ({ open }) => { return ( <StyledMenu open={open}> <a href="/">Sobre</a> <a href="/">Novidades</a> <a href="/">Contato</a> </StyledMenu> ); }; Menu.propTypes = { open: bool.isRequired, }; export default Menu;
/* Template Name: Skote - Responsive Bootstrap 4 Admin Dashboard Author: Themesbrand Version: 2.0 Website: https://themesbrand.com/ Contact: themesbrand@gmail.com File: ico landing Init Js File */ // Sticky nav $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= 50) { $(".sticky").addClass("nav-sticky"); } else { $(".sticky").removeClass("nav-sticky"); } }); // Smoothlink $('.navbar-nav a').on('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top - 0 }, 1500, 'easeInOutExpo'); event.preventDefault(); }); // Countdown $('[data-countdown]').each(function () { var $this = $(this), finalDate = $(this).data('countdown'); $this.countdown(finalDate, function (event) { $(this).html(event.strftime('' + '<div class="coming-box">%D <span>Days</span></div> ' + '<div class="coming-box">%H <span>Hours</span></div> ' + '<div class="coming-box">%M <span>Minutes</span></div> ' + '<div class="coming-box">%S <span>Seconds</span></div> ')); }); }); // Clients carousel $('#clients-carousel, #team-carousel').owlCarousel({ items: 1, loop:false, margin:24, nav: false, dots: false, responsive:{ 576:{ items:2 }, 768:{ items:3 }, 992:{ items:4 }, } }); // Timeline carousel $('#timeline-carousel').owlCarousel({ items: 1, loop: false, margin:0, nav: true, navText : ["<i class='mdi mdi-chevron-left'></i>","<i class='mdi mdi-chevron-right'></i>"], dots: false, responsive:{ 576:{ items:2 }, 768:{ items:3 }, 992:{ items:4 }, } });
import CancelIcon from '@material-ui/icons/Cancel' export default CancelIcon
/** * Amazon Elastic Compute Cloud * <fullname>Amazon Elastic Compute Cloud</fullname> <p>Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing capacity in the AWS cloud. Using Amazon EC2 eliminates the need to invest in hardware up front, so you can develop and deploy applications faster.</p> <p>To learn more, see the following resources:</p> <ul> <li> <p>Amazon EC2: <a href=\"http://aws.amazon.com/ec2\">AmazonEC2 product page</a>, <a href=\"http://aws.amazon.com/documentation/ec2\">Amazon EC2 documentation</a> </p> </li> <li> <p>Amazon EBS: <a href=\"http://aws.amazon.com/ebs\">Amazon EBS product page</a>, <a href=\"https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html\">Amazon EBS documentation</a> </p> </li> <li> <p>Amazon VPC: <a href=\"http://aws.amazon.com/vpc\">Amazon VPC product page</a>, <a href=\"http://aws.amazon.com/documentation/vpc\">Amazon VPC documentation</a> </p> </li> <li> <p>AWS VPN: <a href=\"http://aws.amazon.com/vpn\">AWS VPN product page</a>, <a href=\"http://aws.amazon.com/documentation/vpn\">AWS VPN documentation</a> </p> </li> </ul> * * The version of the OpenAPI document: 2016-11-15 * Contact: mike.ralphson@gmail.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; import TrafficMirrorFilterRule from './TrafficMirrorFilterRule'; /** * The CreateTrafficMirrorFilterRuleResult model module. * @module model/CreateTrafficMirrorFilterRuleResult * @version 1.1.0 */ class CreateTrafficMirrorFilterRuleResult { /** * Constructs a new <code>CreateTrafficMirrorFilterRuleResult</code>. * @alias module:model/CreateTrafficMirrorFilterRuleResult */ constructor() { CreateTrafficMirrorFilterRuleResult.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>CreateTrafficMirrorFilterRuleResult</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/CreateTrafficMirrorFilterRuleResult} obj Optional instance to populate. * @return {module:model/CreateTrafficMirrorFilterRuleResult} The populated <code>CreateTrafficMirrorFilterRuleResult</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new CreateTrafficMirrorFilterRuleResult(); if (data.hasOwnProperty('ClientToken')) { obj['ClientToken'] = ApiClient.convertToType(data['ClientToken'], 'String'); } if (data.hasOwnProperty('TrafficMirrorFilterRule')) { obj['TrafficMirrorFilterRule'] = TrafficMirrorFilterRule.constructFromObject(data['TrafficMirrorFilterRule']); } } return obj; } } /** * @member {String} ClientToken */ CreateTrafficMirrorFilterRuleResult.prototype['ClientToken'] = undefined; /** * @member {module:model/TrafficMirrorFilterRule} TrafficMirrorFilterRule */ CreateTrafficMirrorFilterRuleResult.prototype['TrafficMirrorFilterRule'] = undefined; export default CreateTrafficMirrorFilterRuleResult;
// --------------------------- // Create window Scheduler.window.CreateRun = function(config) { config = config || {}; this.ident = config.ident || Ext.id(); Ext.applyIf(config,{ title: _('scheduler.run_create') ,cls: 'window-with-grid' ,url: Scheduler.config.connectorUrl ,baseParams: { action: 'mgr/runs/create' } ,width: 500 ,modal: true ,defaults: { border: false } ,fields: [{ xtype: 'scheduler-combo-tasklist' ,fieldLabel: _('scheduler.task') ,anchor: '100%' ,allowBlank: false },{ layout: 'column' ,border: false ,items: [{ layout: 'form' ,columnWidth: .5 ,items: [{ xtype: 'compositefield' ,fieldLabel: _('scheduler.timing.inabout') ,anchor: '100%' ,items: [{ xtype: 'numberfield' ,name: 'timing_number' ,allowBlank: false ,allowDecimals: false ,allowNegative: false ,value: 1 ,width: 60 },{ xtype: 'modx-combo' ,store: [ ['minute', _('scheduler.time.m')] ,['hour', _('scheduler.time.h')] ,['day', _('scheduler.time.d')] ,['month', _('scheduler.time.mnt')] ,['year', _('scheduler.time.y')] ] ,name: 'timing_interval' ,hiddenName: 'timing_interval' ,allowBlank: false ,value: 'minute' ,flex: 1 }] }] },{ layout: 'form' ,columnWidth: .5 ,items: [{ xtype: 'xdatetime' ,name: 'timing' ,fieldLabel: _('scheduler.timing') ,anchor: '99%' ,allowBlank: true }] }] },{ xtype: 'label' ,html: _('scheduler.timing.desc') ,cls: 'desc-under' ,style: 'padding-top: 5px;' },{ xtype: 'textfield' ,name: 'task_key' ,fieldLabel: _('scheduler.task_key') ,anchor: '100%' },{ xtype: 'scheduler-grid-future-run-localdata' ,id: 'scheduler-grid-future-run-localdata-'+this.ident ,preventRender: true ,record: config.record }] }); Scheduler.window.CreateRun.superclass.constructor.call(this,config); this.on('render', this.initWindow); this.on('beforeSubmit', this.beforeSubmit); }; Ext.extend(Scheduler.window.CreateRun, MODx.Window, { initWindow: function() { var grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = this.record && this.record.data ? Ext.util.JSON.decode(this.record.data) : false, store = grid.getStore(); if (data) { Ext.iterate(data, function(k, v) { var rec = new grid.propRecord({ key: k, value: v }); store.add(rec); }); } } ,beforeSubmit: function() { var f = this.fp.getForm(), dataProperties = [], grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = grid.getStore().data; data.each(function(item) { dataProperties.push(item.data); }); dataProperties = Ext.encode(dataProperties); Ext.apply(f.baseParams, { data: dataProperties }); } }); Ext.reg('scheduler-window-run-create', Scheduler.window.CreateRun); // --------------------------- // Update window Scheduler.window.UpdateRun = function(config) { config = config || {}; this.ident = config.ident || Ext.id(); Ext.applyIf(config,{ title: _('scheduler.run_update') ,cls: 'window-with-grid' ,url: Scheduler.config.connectorUrl ,baseParams: { action: 'mgr/runs/update' } ,width: 500 ,modal: true ,defaults: { border: false } ,fields: [{ xtype: 'hidden' ,name: 'id' },{ xtype: 'scheduler-combo-tasklist' ,fieldLabel: _('scheduler.task') ,anchor: '100%' ,allowBlank: false },{ xtype: 'xdatetime' ,name: 'timing' ,fieldLabel: _('scheduler.timing') ,anchor: '99%' ,allowBlank: true },{ xtype: 'textfield' ,name: 'task_key' ,fieldLabel: _('scheduler.task_key') ,anchor: '100%' },{ xtype: 'scheduler-grid-future-run-localdata' ,id: 'scheduler-grid-future-run-localdata-'+this.ident ,preventRender: true }] }); Scheduler.window.UpdateRun.superclass.constructor.call(this,config); this.on('render', this.initWindow); this.on('beforeSubmit', this.beforeSubmit); }; Ext.extend(Scheduler.window.UpdateRun, MODx.Window, { initWindow: function() { var grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = this.record && this.record.data ? Ext.util.JSON.decode(this.record.data) : false, store = grid.getStore(); if (data) { Ext.iterate(data, function(k, v) { var rec = new grid.propRecord({ key: k, value: v }); store.add(rec); }); } } ,beforeSubmit: function() { var f = this.fp.getForm(), dataProperties = [], grid = Ext.getCmp('scheduler-grid-future-run-localdata-'+this.ident), data = grid.getStore().data; data.each(function(item) { dataProperties.push(item.data); }); dataProperties = Ext.encode(dataProperties); Ext.apply(f.baseParams, { data: dataProperties }); } }); Ext.reg('scheduler-window-run-update', Scheduler.window.UpdateRun); // ----------------------- // Add/update data property windows Scheduler.window.RunDataPropertyCreate = function(config) { config = config || {}; Ext.applyIf(config,{ title: _('scheduler.data.add') ,width: 450 ,saveBtnText: _('done') ,defaults: { border: false } ,fields: [{ xtype: 'textfield' ,name: 'key' ,fieldLabel: _('scheduler.data.key') ,anchor: '100%' ,allowBlank: false },{ xtype: 'textarea' ,name: 'value' ,fieldLabel: _('scheduler.data.value') ,anchor: '100%' }] }); Scheduler.window.RunDataPropertyCreate.superclass.constructor.call(this,config); }; Ext.extend(Scheduler.window.RunDataPropertyCreate, MODx.Window, { submit: function() { var v = this.fp.getForm().getValues(); var g = this.config.grid; var opt = eval(g.encode()); Ext.apply(v,{ options: opt }); if (this.fp.getForm().isValid()) { if (this.fireEvent('success',v)) { this.fp.getForm().reset(); this.hide(); return true; } } return false; } }); Ext.reg('scheduler-window-runs-adddataproperty', Scheduler.window.RunDataPropertyCreate); Scheduler.window.RunDataPropertyUpdate = function(config) { config = config || {}; Ext.applyIf(config,{ title: _('scheduler.data.update') ,forceLayout: true }); Scheduler.window.RunDataPropertyUpdate.superclass.constructor.call(this,config); }; Ext.extend(Scheduler.window.RunDataPropertyUpdate, Scheduler.window.RunDataPropertyCreate, {}); Ext.reg('scheduler-window-runs-updatedataproperty', Scheduler.window.RunDataPropertyUpdate);
var getId = require('./getId.js').getId; var world = require('./world.js'); module.exports = function(constructor) { var worldDims; var maxSpeed = world.getMaxSpeed; var xClone = false; var yClone = false; var cornerClone = false; var pushEvents = []; var loaded = false; var objName = false; var moved = false; var newEffects = []; var effects = []; var makeClone = function(cloneType, corner) { var clone = constructor(); clone[cloneType] = true; clone.cloned = function() { clone.pos.x = obj.pos.x; clone.pos.y = obj.pos.y; clone.pos.rot = obj.pos.rot; if (cloneType.includes('right')) clone.pos.x += worldDims.x; if (cloneType.includes('left')) clone.pos.x -= worldDims.x; if (cloneType.includes('up'))clone.pos.y -= worldDims.y; if (cloneType.includes('down'))clone.pos.y += worldDims.y; }; clone.collide = function(collider) { obj.collide(collider); }; if (cloneType.includes('right') || cloneType.includes('left')) { if (yClone) yClone.unload(); yClone = clone; } if (cloneType.includes('up') || cloneType.includes('down')) { if (xClone) xClone.unload(); xClone = clone; } if (corner) { if (cornerClone) cornerClone.unload(); cornerClone = clone; } world.addItems(clone); }; var manageClones = function() { var left, right, up, down; if (worldDims.x < (obj.pos.x + obj.radius / 2)) right = true; if (0 > (obj.pos.x - obj.radius / 2)) left = true; if (worldDims.y < (obj.pos.y + obj.radius / 2)) down = true; if (0 > (obj.pos.y - obj.radius / 2)) right = true; if (left && (!yClone || yClone.left)) makeClone('right'); if (right && (!yClone || yClone.right)) makeClone('left'); if (up && (!xClone || xClone.up)) makeClone('down'); if (down && (!xClone || xClone.down)) makeClone('up'); if (right && up && (!cornerClone || !cornerClone.downleft)) makeClone('downleft', true); if (right && down && (!cornerClone || !cornerClone.upleft)) makeClone('upleft', true); if (left && up && (!cornerClone || !cornerClone.downright)) makeClone('downright', true); if (left && down && (!cornerClone || !cornerClone.upright)) makeClone('upright', true); if (!left && !right) { if (yClone) yClone.unload(); yClone = false; if (cornerClone) cornerClone.unload(); cornerClone = false; } if (!up && !down) { if (xClone) xClone.unload(); xClone = false; if (cornerClone) cornerClone.unload(); cornerClone = false; } }; var obj = { unload: function() { if (xClone) xClone.unload(); if (yClone) yClone.unload(); if (cornerClone) cornerClone.unload(); world.deleteItem(obj.id); }, id: getId(), AABB: {}, radius: 0, addEffect: function(effect) { newEffects.push(effect); }, step: function() { if (obj.cloned) { obj.cloned(); } else { worldDims = world.getDims(); effects = effects.concat(newEffects); newEffects = []; effects = effects.filter(function(item) { return item.call(obj); }); obj.processMovementEvents(); if (obj.pos.x < 0) obj.pos.x += worldDims.x; if (obj.pos.y < 0) obj.pos.y += worldDims.y; if (obj.pos.x > worldDims.x) obj.pos.x -= worldDims.x; if (obj.pos.y > worldDims.y) obj.pos.y -= worldDims.y; if (obj.pos.rot > Math.PI * 2) obj.pos.rot -= Math.PI * 2; if (obj.pos.rot < 0) obj.pos.rot += Math.PI * 2; manageClones(); } obj.AABB = { x0: obj.pos.x - obj.radius, x1: obj.pos.x + obj.radius, y0: obj.pos.y - obj.radius, y1: obj.pos.y + obj.radius }; }, processMovementEvents: function() { obj.velocity = Math.sqrt(obj.pos.vec.x * obj.pos.vec.x + obj.pos.vec.y * obj.pos.vec.y); if (obj.velocity > maxSpeed) { obj.pos.vec.x = obj.pos.vec.x / (obj.velocity / maxSpeed); obj.pos.vec.y = obj.pos.vec.y / (obj.velocity / maxSpeed); obj.velocity = maxSpeed; } obj.pos.x += obj.pos.vec.x; obj.pos.y += obj.pos.vec.y; obj.pos.rot += obj.pos.vec.rot; }, pos: { x: 0, y: 0, rot: 0, vec: { x: 0, y: 0, rot: 0 } }, push: function(vec) { if (vec.x) obj.pos.vec.x += vec.x; if (vec.y) obj.pos.vec.y += vec.y; if (vec.rot) obj.pos.vec.rot += vec.rot; }, move: function(pos) { if (pos) { if (pos.x) obj.pos.x = pos.x; if (pos.y) obj.pos.y = pos.y; if (pos.rot) obj.pos.rot = pos.rot; } } }; return obj; };
export { UserContext, UserWrapper } from "./wrappers/UserWrapper"
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var http_1 = require("@angular/http"); var Rx_1 = require("rxjs/Rx"); require("rxjs/add/operator/map"); var apiUrl = "https://hidden-wave-39973.herokuapp.com/api/todo"; var ToDoListService = (function () { function ToDoListService(http) { this.http = http; } ToDoListService.prototype.getAllToDos = function () { return this.http.get(apiUrl) .map(function (res) { return res.json(); }) .map(function (data) { var activityList = []; data.Result.forEach(function (activity) { activityList.push({ "title": activity.title }); }); console.log("about to return"); return activityList; }) .catch(this.handleErrors); }; ToDoListService.prototype.handleErrors = function (error) { console.log(JSON.stringify(error.json())); return Rx_1.Observable.throw(error); }; ToDoListService = __decorate([ core_1.Injectable(), __metadata("design:paramtypes", [http_1.Http]) ], ToDoListService); return ToDoListService; }()); exports.ToDoListService = ToDoListService; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidG9kby1saXN0LnNlcnZpY2UuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJ0b2RvLWxpc3Quc2VydmljZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHNDQUEyQztBQUMzQyxzQ0FBd0Q7QUFDeEQsOEJBQXFDO0FBQ3JDLGlDQUErQjtBQUUvQixJQUFNLE1BQU0sR0FBRyxrREFBa0QsQ0FBQztBQUdsRTtJQUNJLHlCQUFvQixJQUFVO1FBQVYsU0FBSSxHQUFKLElBQUksQ0FBTTtJQUU5QixDQUFDO0lBRUQscUNBQVcsR0FBWDtRQUNJLE1BQU0sQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxNQUFNLENBQUM7YUFDM0IsR0FBRyxDQUFDLFVBQUEsR0FBRyxJQUFJLE9BQUEsR0FBRyxDQUFDLElBQUksRUFBRSxFQUFWLENBQVUsQ0FBQzthQUN0QixHQUFHLENBQUMsVUFBQSxJQUFJO1lBQ1AsSUFBSSxZQUFZLEdBQUcsRUFBRSxDQUFDO1lBQ3RCLElBQUksQ0FBQyxNQUFNLENBQUMsT0FBTyxDQUFDLFVBQUMsUUFBUTtnQkFDM0IsWUFBWSxDQUFDLElBQUksQ0FBQyxFQUFDLE9BQU8sRUFBRSxRQUFRLENBQUMsS0FBSyxFQUFDLENBQUMsQ0FBQztZQUMvQyxDQUFDLENBQUMsQ0FBQztZQUNILE9BQU8sQ0FBQyxHQUFHLENBQUMsaUJBQWlCLENBQUMsQ0FBQztZQUMvQixNQUFNLENBQUMsWUFBWSxDQUFDO1FBQ3RCLENBQUMsQ0FBQzthQUNELEtBQUssQ0FBQyxJQUFJLENBQUMsWUFBWSxDQUFDLENBQUM7SUFDNUIsQ0FBQztJQUVELHNDQUFZLEdBQVosVUFBYSxLQUFlO1FBQzFCLE9BQU8sQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLFNBQVMsQ0FBQyxLQUFLLENBQUMsSUFBSSxFQUFFLENBQUMsQ0FBQyxDQUFDO1FBQzFDLE1BQU0sQ0FBQyxlQUFVLENBQUMsS0FBSyxDQUFDLEtBQUssQ0FBQyxDQUFDO0lBQ2pDLENBQUM7SUF0Qk0sZUFBZTtRQUQzQixpQkFBVSxFQUFFO3lDQUVpQixXQUFJO09BRHJCLGVBQWUsQ0F1QjNCO0lBQUQsc0JBQUM7Q0FBQSxBQXZCRCxJQXVCQztBQXZCWSwwQ0FBZSIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IEluamVjdGFibGUgfSBmcm9tIFwiQGFuZ3VsYXIvY29yZVwiO1xuaW1wb3J0IHsgSHR0cCwgSGVhZGVycywgUmVzcG9uc2UgfSBmcm9tIFwiQGFuZ3VsYXIvaHR0cFwiO1xuaW1wb3J0IHsgT2JzZXJ2YWJsZSB9IGZyb20gXCJyeGpzL1J4XCI7XG5pbXBvcnQgXCJyeGpzL2FkZC9vcGVyYXRvci9tYXBcIjtcblxuY29uc3QgYXBpVXJsID0gXCJodHRwczovL2hpZGRlbi13YXZlLTM5OTczLmhlcm9rdWFwcC5jb20vYXBpL3RvZG9cIjtcblxuQEluamVjdGFibGUoKVxuZXhwb3J0IGNsYXNzIFRvRG9MaXN0U2VydmljZXtcbiAgICBjb25zdHJ1Y3Rvcihwcml2YXRlIGh0dHA6IEh0dHApIHtcblxuICAgIH1cblxuICAgIGdldEFsbFRvRG9zKCkge1xuICAgICAgICByZXR1cm4gdGhpcy5odHRwLmdldChhcGlVcmwpXG4gICAgICAgIC5tYXAocmVzID0+IHJlcy5qc29uKCkpXG4gICAgICAgIC5tYXAoZGF0YSA9PiB7XG4gICAgICAgICAgbGV0IGFjdGl2aXR5TGlzdCA9IFtdO1xuICAgICAgICAgIGRhdGEuUmVzdWx0LmZvckVhY2goKGFjdGl2aXR5KSA9PiB7XG4gICAgICAgICAgICBhY3Rpdml0eUxpc3QucHVzaCh7XCJ0aXRsZVwiOiBhY3Rpdml0eS50aXRsZX0pO1xuICAgICAgICAgIH0pO1xuICAgICAgICAgIGNvbnNvbGUubG9nKFwiYWJvdXQgdG8gcmV0dXJuXCIpO1xuICAgICAgICAgIHJldHVybiBhY3Rpdml0eUxpc3Q7XG4gICAgICAgIH0pXG4gICAgICAgIC5jYXRjaCh0aGlzLmhhbmRsZUVycm9ycyk7XG4gICAgICB9XG4gICAgXG4gICAgICBoYW5kbGVFcnJvcnMoZXJyb3I6IFJlc3BvbnNlKSB7XG4gICAgICAgIGNvbnNvbGUubG9nKEpTT04uc3RyaW5naWZ5KGVycm9yLmpzb24oKSkpO1xuICAgICAgICByZXR1cm4gT2JzZXJ2YWJsZS50aHJvdyhlcnJvcik7XG4gICAgICB9XG59Il19
function jobsearch_listing_top_map(top_dataobj, is_ajax) { var map_id = top_dataobj.map_id, access_token = top_dataobj.access_token, map_zoom = top_dataobj.map_zoom, map_style = top_dataobj.map_style, latitude = top_dataobj.latitude, longitude = top_dataobj.longitude, cluster_icon = top_dataobj.cluster_icon, map_cords_list = top_dataobj.cords_list; if (latitude != '' && longitude != '' && access_token != '' && map_style != '') { mapboxgl.accessToken = access_token; if (jobsearch_plugin_vars.is_rtl) { mapboxgl.setRTLTextPlugin( 'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js', null, true // Lazy load the plugin ); } if (!is_ajax) { jobsearch_listing_map = new mapboxgl.Map({ container: 'listings-map-' + map_id, style: map_style, center: [longitude, latitude], scrollZoom: false, zoom: map_zoom }); } jobsearch_listing_map.addControl(new mapboxgl.NavigationControl({ showCompass: false }), 'top-right'); jobsearch_listing_map.on('load', function () { jobsearch_listing_map.addSource('map_source_obj', { type: 'geojson', data: { type: 'FeatureCollection', features: map_cords_list }, cluster: true, clusterMaxZoom: 14, // Max zoom to cluster points on clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50) }); jobsearch_listing_map.addLayer({ id: 'clusters', type: 'circle', source: 'map_source_obj', filter: ['has', 'point_count'], paint: { // Use step expressions (https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-step) // with three steps to implement three types of circles: // * Blue, 20px circles when point count is less than 100 // * Yellow, 30px circles when point count is between 100 and 750 // * Pink, 40px circles when point count is greater than or equal to 750 'circle-color': [ 'step', ['get', 'point_count'], '#51bbd6', 100, '#f1f075', 750, '#f28cb1' ], 'circle-radius': [ 'step', ['get', 'point_count'], 20, 100, 30, 750, 40 ] } }); jobsearch_listing_map.addLayer({ id: 'cluster-count', type: 'symbol', source: 'map_source_obj', filter: ['has', 'point_count'], layout: { 'text-field': '{point_count_abbreviated}', 'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'], 'text-size': 12 } }); jobsearch_listing_map.addLayer({ id: 'unclustered-point', type: 'circle', source: 'map_source_obj', filter: ['!', ['has', 'point_count']], paint: { 'circle-color': '#eeeeee', 'circle-radius': 4, 'circle-stroke-width': 1, 'circle-stroke-color': '#ffffff' } }); // inspect a cluster on click jobsearch_listing_map.on('click', 'clusters', function (e) { var features = jobsearch_listing_map.queryRenderedFeatures(e.point, { layers: ['clusters'] }); var clusterId = features[0].properties.cluster_id; var clusterSource = jobsearch_listing_map.getSource('map_source_obj').getClusterExpansionZoom( clusterId, function (err, zoom) { if (err) return; jobsearch_listing_map.easeTo({ center: features[0].geometry.coordinates, zoom: zoom }); } ); var clustrMarksRefrsh = setInterval(function() { updateMarkers(); }, 1000); }); jobsearch_listing_map.on('mouseenter', 'clusters', function () { jobsearch_listing_map.getCanvas().style.cursor = 'pointer'; }); jobsearch_listing_map.on('mouseleave', 'clusters', function () { jobsearch_listing_map.getCanvas().style.cursor = ''; }); var markers = {}; var markersOnScreen = {}; function updateMarkers() { var newMarkers = {}; var features = jobsearch_listing_map.querySourceFeatures('map_source_obj'); for (var i = 0; i < features.length; i++) { var coords = features[ i ].geometry.coordinates; var props = features[ i ].properties; if (props.cluster) { continue; } var id = props.id; var marker = markers[id]; if (!marker) { var el = new Image(); el.src = props.marker; el.classList.add('mapMarker'); el.dataset.type = 'point'; // you can use custom data if you have assigned it in the GeoJSON data marker = markers[id] = new mapboxgl.Marker({element: el}).setLngLat(coords); } newMarkers[id] = marker; if (!markersOnScreen[id]) { var list_logo_img_url = props.logo_img_url; var list_link = props.link; var list_title = props.title; var list_sector = props.sector; var list_address = props.address; var contentString = '\ <div class="jobsearch_map_info mapbox-info-popup">\ <div id="listing-info-' + props.id + '" class="listing-info-inner">\ <div class="info-main-container">\ ' + (list_logo_img_url != '' ? '<div class="img-con"><img src="' + list_logo_img_url + '" alt=""></div>' : '') + '\ <div class="info-txt-holder">\ <a class="info-title" href="' + list_link + '">' + list_title + '</a>\ <div class="post-secin">' + list_sector + '</div>\ ' + list_address + '\ </div>\ </div>\ </div>\ </div>'; marker.setPopup(new mapboxgl.Popup({offset: 25}) // add popups .setHTML(contentString)) .addTo(jobsearch_listing_map); } } for (id in markersOnScreen) { if (!newMarkers[id]) { markersOnScreen[id].remove(); } } markersOnScreen = newMarkers; } jobsearch_listing_map.on('data', function (e) { if (e.sourceId !== 'map_source_obj' || !e.isSourceLoaded) return; jobsearch_listing_map.on('move', updateMarkers); jobsearch_listing_map.on('moveend', updateMarkers); updateMarkers(); }); }); } }
import KataGroups from './katagroups.js'; export default class AppState { static initializeFromKataGroups(kataGroups) { let instance = new AppState(); instance.kataGroups = kataGroups; return instance; } static initializeFromRawKataData(rawKataData) { return AppState.initializeFromKataGroups(KataGroups.fromRawKataData(rawKataData)); } updateFromUrlData(urlData) { if (urlData.kataId) { this.kataGroups.selectKataById(urlData.kataId); return; } this.kataGroups.selectGroupBySlug(urlData.kataGroupSlug); } }
import React from "react"; import { render } from "react-dom"; import { makeData, Logo, Tips } from "./Utils"; import "./index.css"; // Import React Table import ReactTable from "react-table"; import "react-table/react-table.css"; class App extends React.Component { constructor() { super(); this.state = { data: makeData() }; } render() { const { data } = this.state; return ( <div> <ReactTable data={data} columns={[ { Header: "Name", columns: [ { Header: "First Name", accessor: "firstName" }, { Header: "Last Name", id: "lastName", accessor: d => d.lastName } ] }, { Header: "Info", columns: [ { Header: "Age", accessor: "age" } ] } ]} defaultPageSize={20} style={{ height: "400px" // This will force the table body to overflow and scroll, since there is not enough room }} className="-striped -highlight" /> <br /> <Tips /> <Logo /> </div> ); } } render(<App />, document.getElementById("root"));
import * as _c from '../constantes.js' export default class BalaMortero extends Phaser.GameObjects.Sprite { constructor(scene, imag, vel, pool, damage, rango) { super(scene, 0, 0, imag); this.scene.add.existing(this); //le dice a la scene Game que existe this.scene.physics.add.existing(this); //le otorga presencia fisica this.velocidadIni = vel; this.velocidad = vel; this.rebotesAcumulados = 0; this.daño = damage; this.rango = rango; this.setScale(0.5); this.setDepth(0); this.pool = pool; this.scene = scene; this.isMoving = false; this.medio = false; this.escalaInicial = 1 this.scala = this.escalaInicial; } preUpdate() { if (this.isMoving){ if (!this.medio) { this.scala = this.scala + _c.settBMortero.velocidadCrecimientoEscala; this.setScale(this.scala); if ((this.direccion[1] > 0 && this.y > this.puntoMedio[1]) || (this.direccion[1] < 0 && this.y < this.puntoMedio[1]) || (this.direccion[0] > 0 && this.x > this.puntoMedio[0]) && (this.direccion[0] < 0 && this.x < this.puntoMedio[0])) this.medio = true; } else { this.scala = this.scala - _c.settBMortero.velocidadDerecimientoEscala_; this.setScale(this.scala); if (this.scala<this.escalaInicial) { //reset de todos los valores necesarios para que esto no se mame this.isMoving = false; this.medio = false; this.velocidad = this.velocidadIni; this.scala=this.escalaInicial; this.scene.explosion(this.x, this.y); this.pool.delete(this, true); //destruirse } } } } } BalaMortero.prototype.direccion = function (x, y) { //le llega la posicion del raton y calcula su direccion this.direccion = [(x + 10 - this.x), (y + 10 - this.y)]; let modulo = Math.sqrt((this.direccion[0] * this.direccion[0]) + (this.direccion[1] * this.direccion[1])) this.direccion[0] = this.direccion[0] / modulo; this.direccion[1] = this.direccion[1] / modulo; //DESTINO this.distancia = Phaser.Math.Distance.Between(x, y, this.x, this.y); if (this.distancia > this.rango) this.distancia = this.rango; //si se sale del rango lo capa this.puntoFin = [this.x + this.direccion[0] * this.distancia, this.y + this.direccion[1] * this.distancia]; //VELOCIDAD this.velocidad = (this.distancia/(this.velocidad/1000)) this.body.setVelocityY(this.direccion[1] * this.velocidad); this.body.setVelocityX(this.direccion[0] * this.velocidad); //se le da la velocidad a la bala //ROTACION this.x = this.x + (15 * this.direccion[0]); this.y = this.y + (15 * this.direccion[1]); //pone la bala en la punta del calñon this.angle = (Phaser.Math.Angle.Between(x + 10, y + 10, this.x, this.y) - Math.PI / 2); this.rotation = this.angle; //pone la bala apuntando al raton console.log() this.puntoMedio = [(this.x + this.puntoFin[0]) / 2, (this.y + this.puntoFin[1]) / 2]; this.isMoving = true; }
import React from "react"; import {useSubheader} from "../../_themeBase/layout"; export const MyPage = () => { const suhbeader = useSubheader(); suhbeader.setTitle("My Custom title"); return (<>My Page</>); };
import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import Head from 'next/head'; import useDarkMode from 'use-dark-mode'; import { makeStyles, ThemeProvider } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import CssBaseline from '@material-ui/core/CssBaseline'; import { useStore } from '../store'; import Footer from '../components/elements/Footer'; import Navbar from '../components/elements/Navbar'; import { WEBSITE_NAME } from '../constants/constants'; import { darkTheme, lightTheme } from '../components/elements/theme'; const useStyles = makeStyles(() => ({ root: { flexGrow: 1, }, })); const App = ({Component, pageProps}) => { const store = useStore(pageProps.initialReduxState); const classes = useStyles(); const { value } = useDarkMode(true); return ( <Provider store={store}> <Head> <title>{WEBSITE_NAME}</title> <meta key="viewport" name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, viewport-fit=cover"/> <meta property="og:title" content="Next JS Starter" key="title" /> </Head> <ThemeProvider theme={ value ? darkTheme : lightTheme }> <CssBaseline /> <Grid className={classes.root} container> <Navbar /> <Component {...pageProps}/> <Footer /> </Grid> </ThemeProvider> </Provider> ); }; App.propTypes = { Component: PropTypes.any, pageProps: PropTypes.any, }; export default App;
this.primereact=this.primereact||{},this.primereact.toolbar=function(t,e,r){"use strict";function o(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=o(e);function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function l(t,e){for(var r=0;r<e.length;r++){var o=e[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}function c(t,e){return(c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&c(t,e)}function a(t){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function f(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function s(t,e){return!e||"object"!==a(e)&&"function"!=typeof e?f(t):e}function p(t){return(p=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function y(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}var b,m,h,d=function(t){u(m,t);var e,o,c,a,f,b=(e=m,o=y(),function(){var t,r=p(e);if(o){var n=p(this).constructor;t=Reflect.construct(r,arguments,n)}else t=r.apply(this,arguments);return s(this,t)});function m(){return i(this,m),b.apply(this,arguments)}return c=m,(a=[{key:"render",value:function(){var t=r.classNames("p-toolbar p-component",this.props.className),e=r.ObjectUtils.getJSXElement(this.props.left,this.props),o=r.ObjectUtils.getJSXElement(this.props.right,this.props);return n.default.createElement("div",{id:this.props.id,className:t,style:this.props.style,role:"toolbar"},n.default.createElement("div",{className:"p-toolbar-group-left"},e),n.default.createElement("div",{className:"p-toolbar-group-right"},o))}}])&&l(c.prototype,a),f&&l(c,f),m}(e.Component);return h={id:null,style:null,className:null,left:null,right:null},(m="defaultProps")in(b=d)?Object.defineProperty(b,m,{value:h,enumerable:!0,configurable:!0,writable:!0}):b[m]=h,t.Toolbar=d,Object.defineProperty(t,"__esModule",{value:!0}),t}({},React,primereact.core);
import React from 'react'; import OptionSelectButton from '../template/OptionSelectButton'; import ScheduleButton from './ScheduleButton'; import log from 'electron-log'; const DEFAULT_INTERVALS = [ {title: '1 Minute', milliseconds: 60000} ] function IntervalSelection(props) { const { channelNumber=1, scheduleInterval=60000, recorderStatus="stopped" } = props; const { inTransition=false, scheduleStatus="stopped", scheduledFunction=()=>{}, intervalsForSelection=DEFAULT_INTERVALS } = props; const { startSchedule=()=>{}, stopSchedule=()=>{}, setScheduleIntervalNSave=()=>{} } = props.HLSRecorderActions; const inRecording = recorderStatus !== 'stopped'; const selectItems = intervalsForSelection.map(interval => { return { value: interval.milliseconds, label: interval.title } }) const onChangeSelect = (event) => { setScheduleIntervalNSave({channelNumber, scheduleInterval:event.target.value}) } const ButtonElement = () => { return <ScheduleButton channelNumber={channelNumber} inTransition={inTransition} scheduleStatus={scheduleStatus} scheduledFunction={scheduledFunction} startSchedule={startSchedule} stopSchedule={stopSchedule} > </ScheduleButton> } return ( <OptionSelectButton // subtitle='CCTV' // titlewidth={"115px"} FrontButton={ButtonElement} // width="100%" currentItem={scheduleInterval} multiple={false} menuItems={selectItems} onChangeSelect={onChangeSelect} smallComponent={true} bgcolor={'#232738'} selectColor={"#2d2f3b"} disabled={inRecording} mb={"2px"} mt={"4px"} ></OptionSelectButton> ) } export default React.memo(IntervalSelection)