<commit_before>/*

  Gekko is a Bitcoin trading bot for Mt. Gox written
  in node, it features multiple trading methods using
  technical analysis.

  Disclaimer:

  USE AT YOUR OWN RISK!

  The authors of this project is NOT responsible for any damage or loss caused
  by this software. There can be bugs and the bot may not perform as expected
  or specified. Please consider testing it first with a small amount of funds,
  and check to the code to see what how it's working.

*/
var tradingMethod = 'Exponential Moving Averages';
var tradeConfig = {
  // timeframe
  interval: 60, // in minutes
  // EMA weight (α)
  // the higher the weight, the more smooth
  // (and delayed) the line
  shortEMA: 10,
  longEMA: 21,
  // amount of samples to remember
  // and base initial EMAs on
  candles: 20,
  // max difference between first and last
  // trade to base price calculation on
  sampleSize: 10, // in seconds
  // the difference between the  EMAs (to
  // act as act triggers)
  sellTreshold: -0.25,
  buyTreshold: 0.25,
  debug: false // for additional logging
};

var MtGoxClient = require("mtgox-apiv2");
// create a public mtgox object which can retrieve
// open trade information from the API.
var publicMtgox = new MtGoxClient('~', '~');

// helpers
var moment = require('moment');
var _ = require('underscore');
var util = require('./util.js');

// implement a trading method to create a consultant, we pass it a config and a
// public mtgox object which the method can use to get data on past trades..
var consultant = require('./methods/' + tradingMethod.toLowerCase().split(' ').join('-') + '.js');
consultant.emit('init', tradeConfig, publicMtgox);

console.log(
  [
    '',
    util.now(),
    '',
    'I\'m gonna make you rich, Bud Fox.',
    'Let me show you some ' + tradingMethod + '.',
    ''
  ].join('\n')
);

// whenever the consultant advices to sell or buy we can act on the information
var info = function(a, b) {
  console.log(util.now(), a, b);
}
consultant.on('advice', info);<commit_msg>typos<commit_after>/*

  Gekko is a Bitcoin trading bot for Mt. Gox written
  in node, it features multiple trading methods using
  technical analysis.

  Disclaimer:

  USE AT YOUR OWN RISK!

  The authors of this project is NOT responsible for any damage or loss caused
  by this software. There can be bugs and the bot may not perform as expected
  or specified. Please consider testing it first with a small amount of funds,
  and check to the code to see what how it's working.

*/
var tradingMethod = 'Exponential Moving Averages';
var tradeConfig = {
  // timeframe
  interval: 60, // in minutes
  // EMA weight (α)
  // the higher the weight, the more smooth
  // (and delayed) the line
  shortEMA: 10,
  longEMA: 21,
  // amount of samples to remember
  // and base initial EMAs on
  candles: 20,
  // max difference between first and last
  // trade to base price calculation on
  sampleSize: 10, // in seconds
  // the difference between the EMAs (to
  // act as triggers)
  sellTreshold: -0.25,
  buyTreshold: 0.25,
  debug: false // for additional logging
};

console.log(
  [
    '',
    util.now(),
    '',
    'I\'m gonna make you rich, Bud Fox.',
    'Let me show you some ' + tradingMethod + '.',
    ''
  ].join('\n')
);

var MtGoxClient = require("mtgox-apiv2");
// create a public mtgox object which can retrieve
// open trade information from the API.
var publicMtgox = new MtGoxClient('~', '~');

// helpers
var moment = require('moment');
var _ = require('underscore');
var util = require('./util.js');

// implement a trading method to create a consultant, we pass it a config and a
// public mtgox object which the method can use to get data on past trades..
var consultant = require('./methods/' + tradingMethod.toLowerCase().split(' ').join('-') + '.js');
consultant.emit('init', tradeConfig, publicMtgox);

// whenever the consultant advices to sell or buy we can act on the information
var info = function(a, b) {
  console.log(util.now(), a, b);
}
consultant.on('advice', info);<|endoftext|>


<commit_before>"use strict";

(function () {
    var video             = document.getElementById('video-player'),
        videoControls     = document.getElementById('controls'),
        play              = document.getElementById('action'),
        playTime          = document.getElementById('play-time'),
        totalTime         = document.getElementById('total-time'),
        progressContainer = document.getElementById('progress'),
        playProgressBar   = document.getElementById('bar'),
        volume            = document.getElementById('volume'),
        volumeTick        = document.querySelectorAll('.volume-mark'),
        VideoPlayer;

    VideoPlayer = {
        init: function () {
            video.removeAttribute('controls');

            if (video.readyState > 0) {
                // metadata is loaded already, fire event handler manually
                VideoPlayer.initializeControls();
            } else {
                video.addEventListener("loadedmetadata", VideoPlayer.initializeControls, false);
            }

            // handle button presses/click events
            VideoPlayer.handleButtonPresses();
        },

        initializeControls: function () {
            // setup customized controls
            totalTime.innerHTML = VideoPlayer.convertTime(video.duration);

            VideoPlayer.showHideControls();
        },

        showHideControls: function () {
            // attach hover events, try to account for IE
            if (video.addEventListener && videoControls.addEventListener) {
                video.addEventListener('mouseover', VideoPlayer.showControls, false);
                video.addEventListener('mouseout', VideoPlayer.hideControls, false);
                videoControls.addEventListener('mouseover', VideoPlayer.showControls, false);
                videoControls.addEventListener('mouseout', VideoPlayer.hideControls, false);
            } else {
                video.attachEvent('onmouseover', VideoPlayer.showControls, false);
                video.attachEvent('onmouseout', VideoPlayer.hideControls, false);
                videoControls.attachEvent('onmouseover', VideoPlayer.showControls, false);
                videoControls.attachEvent('onmouseout', VideoPlayer.hideControls, false);
            }
        },

        showControls: function () {
            videoControls.style.opacity = 1;
            videoControls.style.zIndex = 2;
        },

        hideControls: function () {
            videoControls.style.opacity = 0;
            videoControls.style.zIndex = -1;
        },

        handleButtonPresses: function () {
            video.addEventListener('click', VideoPlayer.playORpause, false);
            play.addEventListener('click', VideoPlayer.playORpause, false);
            volumeTick.addEventListener('click', VideoPlayer.adjustVolume, false);

            video.addEventListener('play', function() {
                play.title = 'Pause';
                play.childNodes[0].classList.remove("icon-play");
                play.childNodes[0].className += " icon-pause";
                VideoPlayer.trackPlayProgress();
            }, false);

            video.addEventListener('pause', function() {
                play.title = 'Play';
                play.childNodes[0].classList.remove("icon-pause");
                play.childNodes[0].className += " icon-play";
                VideoPlayer.stopTrackingPlayProgress();
            }, false);

            video.addEventListener('ended', function() {
                this.currentTime = 0;
                this.pause();
            }, false);
        },

        playORpause: function () {
            if (video.paused || video.ended) {
                if (video.ended) {
                    video.currentTime = 0;
                }
                video.play();
            } else {
                video.pause();
            }
        },

        adjustVolume: function (event) {
            var level = event.target.getAttribute('id');

            if (level === "master-volume") {
                if (video.volume > 0) {
                    video.volume = 0;
                } else {
                    video.volume = 1;
                }
            } else {
                level = parseInt(level);
                if (isNaN(level)) {
                    console.log("NaN, not changing level");
                } else {
                    if (level === 1) {
                        video.volume = 1;
                    } else {
                        video.volume = level * 0.1;
                    }
                }
            }
        },

        trackPlayProgress: function () {
            (progressTrack = function () {
                VideoPlayer.updatePlayProgress();
                VideoPlayer.playProgressInterval = setTimeout(progressTrack, 50);
            })();
        },

        updatePlayProgress: function () {
            playTime.innerHTML = VideoPlayer.convertTime(video.currentTime);
            playProgressBar.style.width = parseInt(((video.currentTime / video.duration) * 100), 10) + "%";
        },

        stopTrackingPlayProgress: function () {
            clearTimeout(VideoPlayer.playProgressInterval);
        },

        convertTime: function (time) {
            var minutes = parseInt(time / 60, 10),
                seconds = parseInt(time % 60, 10),
                str;

            if (seconds < 10) {}
                seconds = '0' + seconds;
            }

            str = minutes + ':' + seconds;
            return str;
        }
    };

    VideoPlayer.init()
}());
<commit_msg>Minor fixes with jshint<commit_after>"use strict";

var video             = document.getElementById('video-player'),
    videoControls     = document.getElementById('controls'),
    play              = document.getElementById('action'),
    playTime          = document.getElementById('play-time'),
    totalTime         = document.getElementById('total-time'),
    progressContainer = document.getElementById('progress'),
    playProgressBar   = document.getElementById('bar'),
    volume            = document.getElementById('volume'),
    volumeTick        = document.querySelectorAll('.volume-mark'),
    VideoPlayer;

VideoPlayer = {
    init: function () {
        video.removeAttribute('controls');

        if (video.readyState > 0) {
            // metadata is loaded already, fire event handler manually
            VideoPlayer.initializeControls();
        } else {
            video.addEventListener("loadedmetadata", VideoPlayer.initializeControls, false);
        }

        // handle button presses/click events
        VideoPlayer.handleButtonPresses();
    },

    initializeControls: function () {
        // setup customized controls
        totalTime.innerHTML = VideoPlayer.convertTime(video.duration);

        VideoPlayer.showHideControls();
    },

    showHideControls: function () {
        // attach hover events, try to account for IE
        if (video.addEventListener && videoControls.addEventListener) {
            video.addEventListener('mouseover', VideoPlayer.showControls, false);
            video.addEventListener('mouseout', VideoPlayer.hideControls, false);
            videoControls.addEventListener('mouseover', VideoPlayer.showControls, false);
            videoControls.addEventListener('mouseout', VideoPlayer.hideControls, false);
        } else {
            video.attachEvent('onmouseover', VideoPlayer.showControls, false);
            video.attachEvent('onmouseout', VideoPlayer.hideControls, false);
            videoControls.attachEvent('onmouseover', VideoPlayer.showControls, false);
            videoControls.attachEvent('onmouseout', VideoPlayer.hideControls, false);
        }
    },

    showControls: function () {
        videoControls.style.opacity = 1;
        videoControls.style.zIndex = 2;
    },

    hideControls: function () {
        videoControls.style.opacity = 0;
        videoControls.style.zIndex = -1;
    },

    handleButtonPresses: function () {
        video.addEventListener('click', VideoPlayer.playORpause, false);
        play.addEventListener('click', VideoPlayer.playORpause, false);
        volumeTick.addEventListener('click', VideoPlayer.adjustVolume, false);

        video.addEventListener('play', function () {
            play.title = 'Pause';
            play.childNodes[0].classList.remove("icon-play");
            play.childNodes[0].className += " icon-pause";
            VideoPlayer.trackPlayProgress();
        }, false);

        video.addEventListener('pause', function () {
            play.title = 'Play';
            play.childNodes[0].classList.remove("icon-pause");
            play.childNodes[0].className += " icon-play";
            VideoPlayer.stopTrackingPlayProgress();
        }, false);

        video.addEventListener('ended', function () {
            this.currentTime = 0;
            this.pause();
        }, false);
    },

    playORpause: function () {
        if (video.paused || video.ended) {
            if (video.ended) {
                video.currentTime = 0;
            }
            video.play();
        } else {
            video.pause();
        }
    },

    adjustVolume: function (event) {
        var level = event.target.getAttribute('id');

        if (level === "master-volume") {
            if (video.volume > 0) {
                video.volume = 0;
            } else {
                video.volume = 1;
            }
        } else {
            level = parseInt(level, 10);
            if (isNaN(level)) {
                console.log("NaN, not changing level");
            } else {
                if (level === 1) {
                    video.volume = 1;
                } else {
                    video.volume = level * 0.1;
                }
            }
        }
    },

    trackPlayProgress: function () {
        (function progressTrack() {
            VideoPlayer.updatePlayProgress();
            VideoPlayer.playProgressInterval = setTimeout(progressTrack, 50);
        }());
    },

    updatePlayProgress: function () {
        playTime.innerHTML = VideoPlayer.convertTime(video.currentTime);
        playProgressBar.style.width = parseInt(((video.currentTime / video.duration) * 100), 10) + "%";
    },

    stopTrackingPlayProgress: function () {
        clearTimeout(VideoPlayer.playProgressInterval);
    },

    convertTime: function (time) {
        var minutes = parseInt(time / 60, 10),
            seconds = parseInt(time % 60, 10),
            str;

        if (seconds < 10) {
            seconds = '0' + seconds;
        }

        str = minutes + ':' + seconds;
        return str;
    }
};

(function () {
    VideoPlayer.init();
}());
<|endoftext|>


<commit_before>//     genie.js
//     (c) 2013 Kent C. Dodds
//     genie.js may be freely distributed under the MIT license.
//     http://www.github.com/kentcdodds/genie.git
//     See README.md

;(function(global){

  var _wishes = {},
    _previousId = 0,
    _enteredMagicWords = {},
    _defaultContext = 'universe'
    _context = _defaultContext
    _previousContext = _defaultContext;

  function _getNextId() {
    return 'g-' + _previousId++;
  }

  function registerWish(magicWords, action, context, data, id) {
    if (!Array.isArray(magicWords)) {
      // If they passed an object instead.
      if (typeof magicWords === 'object') {
        return registerWish(magicWords.magicWords, magicWords.action, magicWords.context, magicWords.data, magicWords.id);
      } else {
        magicWords = [magicWords];
      }
    }
    if (id === undefined) {
      id = _getNextId();
    }

    // Verify none of the magic words are objects
    for (var i = 0; i < magicWords.length; i++) {
      if (typeof magicWords[i] === 'object') {
        throw 'Cannot make an object a magic word!\n' + JSON.stringify(magicWords, null, 2);
      }
    }

    var wish = {
      id: id,
      context: context || _defaultContext,
      data: data,
      magicWords: magicWords,
      action: action
    };
    _wishes[id] = wish;
    return _wishes[id];
  }

  function deregisterWish(id) {
    // Check if it may be a wish object
    if (typeof id === 'object' && id.id) {
      id = id.id;
    }
    var wish = _wishes[id];
    delete _wishes[id];
    for (var word in _enteredMagicWords) {
      if (_enteredMagicWords[word].indexOf(id) != -1) {
        _enteredMagicWords[word].splice(_enteredMagicWords[word].indexOf(id), 1);
      }
    }
    return wish;
  }

  function clearWishes() {
    _wishes = {};
    _enteredMagicWords = {};
  }

  function getMatchingWishes(magicWord) {
    var otherMatchingWishId, allWishIds, matchingWishes, i; //Hoist-it!
    if (magicWord === undefined) {
      magicWord = '';
    } else if (magicWord === null) {
      return [];
    } else if (typeof magicWord === 'object') {
      throw 'Cannot match wishes to an object!\n' + JSON.stringify(magicWord, null, 2);
    }

    allWishIds = _enteredMagicWords[magicWord] || [];

    otherMatchingWishId = _getOtherMatchingMagicWords(allWishIds, magicWord);
    allWishIds = allWishIds.concat(otherMatchingWishId);

    matchingWishes = [];
    for (i = 0; i < allWishIds.length; i++) {
      matchingWishes.push(_wishes[allWishIds[i]]);
    }
    return matchingWishes;
  }

  function _getOtherMatchingMagicWords(currentMatchingWishIds, givenMagicWord) {
    var containsMagicWordWishIds = [];
    var acronymMagicWordWishIds = [];
    var otherMatchingWishIds = [];
    for (var wishId in _wishes) {
      if (currentMatchingWishIds.indexOf(wishId) == -1) {
        var wish =_wishes[wishId];
        if (_wishInContext(wish)) {
          var matchType = _bestMagicWordsMatch(wish.magicWords, givenMagicWord);
          switch (matchType) {
            case 'contains':
              containsMagicWordWishIds.push(wishId);
              break;
            case 'acronym':
              acronymMagicWordWishIds.push(wishId);
              break;
            case 'matches':
              otherMatchingWishIds.push(wishId);
              break;
            case '':
              break; // no match
          }
        }
      }
    }
    return containsMagicWordWishIds.concat(acronymMagicWordWishIds).concat(otherMatchingWishIds);
  }

  function _bestMagicWordsMatch(wishesMagicWords, givenMagicWord) {
    var bestMatch = '';
    for (var i = 0; i < wishesMagicWords.length; i++) {
      var matchType = _stringsMatch(wishesMagicWords[i], givenMagicWord);
      if ((matchType === 'contains')
        || (matchType === 'acronym' && (bestMatch === '' || bestMatch === 'matches'))
        || (matchType === 'matches' && bestMatch === '')) {
        bestMatch = matchType;
      }
      if (bestMatch === 'contains') {
        break;
      }
    }
    return bestMatch;
  }

  function _stringsMatch(magicWord, givenMagicWord) {
    var magicWordWords, splitByHyphen, acronym = '';

    magicWord = ('' + magicWord).toLowerCase();
    givenMagicWord = ('' + givenMagicWord).toLowerCase();

    // too long
    if (givenMagicWord.length > magicWord.length) {
      return '';
    }

    // contains
    if (magicWord.indexOf(givenMagicWord) != -1) {
      return 'contains';
    } else if (givenMagicWord.length == 1) {
      return '';
    }

    // acronym
    magicWordWords = magicWord.split(' ');
    for (var i = 0; i < magicWordWords.length; i++) {
      splitByHyphen = magicWordWords[i].split('-');
      for (var j = 0; j < splitByHyphen.length; j++) {
        acronym += splitByHyphen[j].substr(0, 1);
      }
    }
    if (acronym.indexOf(givenMagicWord) != -1) {
      return 'acronym';
    }

    return _stringsByCharOrder(magicWord, givenMagicWord);
  }

  function _stringsByCharOrder(magicWord, givenMagicWord) {
    var charNumber = 0;
    for (var i = 0; i < givenMagicWord.length; i++) {
      var matchChar = givenMagicWord[i];
      var found = false;
      for (var j = charNumber; j < magicWord.length; j++) {
        var stringChar = magicWord[j];
        if (stringChar == matchChar) {
          found = true;
          charNumber = j + 1;
          break;
        }
      }
      if (!found) {
        return '';
      }
    }
    return 'matches';
  }

  function makeWish(wish, magicWord) {
    var id, arry, existingIndex, first, matchingWishes;
    // Check if it may be a wish object
    if (typeof wish !== 'object') {
      wish = _wishes[wish];
    }
    if (wish === null || wish === undefined) {
      matchingWishes = getMatchingWishes(magicWord);
      if (matchingWishes.length > 0) {
        wish = matchingWishes[0];
      }
    }

    /* Don't execute the wish and return null if it:
     *   - doesn't exist
     *   - isn't in the registry
     *   - doesn't have an action
     *   - context doesn't match the current context and the wish's context is not the _defaultContext
     */
    if (!wish || !_wishes[wish.id] || !wish.action || !(_wishInContext(wish))) {
      return null;
    }

    wish.action(wish);

    if (magicWord !== undefined) {
      // Reset entered magicWords order.
      _enteredMagicWords[magicWord] = _enteredMagicWords[magicWord] || [];
      id = wish.id;
      arry = _enteredMagicWords[magicWord];
      existingIndex = arry.indexOf(id);
      if (existingIndex != -1) {
        // If it already exists, remove it before re-adding it in the correct spot
        arry.splice(existingIndex, 1);
      }
      if (existingIndex != 1 && arry.length > 0) {
        // If it's not "on deck" then put it in the first slot and set the King of the Hill to be the id to go first.
        first = arry[0];
        arry[0] = id;
        id = first;
      }
      arry.unshift(id);
    }
    return wish;
  }

  function _wishInContext(wish) {
    return _context === _defaultContext || wish.context === _defaultContext || wish.context === _context;
  }

  function options(options) {
    if (options) {
      _wishes = options.wishes || _wishes;
      _previousId = options.previousId || _previousId;
      _enteredMagicWords = options.enteredKeyWords || _enteredMagicWords;
      _context = options.context || _context;
      _previousContext = options.previousContext || _previousContext;
    }
    return {
      wishes: _wishes,
      previousId: _previousId,
      enteredMagicWords: _enteredMagicWords,
      contexts: _context,
      previousContext: _previousContext
    };
  }

  function context(newContext) {
    if (newContext) {
      _previousContext = _context;
      _context = newContext;
    }
    return _context;
  }

  function revertContext() {
    return context(_previousContext);
  }

  function restoreContext() {
    return context(_defaultContext);
  }

  global.genie = registerWish;
  global.genie.getMatchingWishes = getMatchingWishes;
  global.genie.makeWish = makeWish;
  global.genie.options = options;
  global.genie.deregisterWish = deregisterWish;
  global.genie.clearWishes = clearWishes;
  global.genie.context = context;
  global.genie.revertContext = revertContext;
  global.genie.restoreContext = restoreContext;

})(this);
<commit_msg>Whoops! Added commas to remove globals.<commit_after>//     genie.js
//     (c) 2013 Kent C. Dodds
//     genie.js may be freely distributed under the MIT license.
//     http://www.github.com/kentcdodds/genie.git
//     See README.md

;(function(global){

  var _wishes = {},
    _previousId = 0,
    _enteredMagicWords = {},
    _defaultContext = 'universe',
    _context = _defaultContext,
    _previousContext = _defaultContext;

  function _getNextId() {
    return 'g-' + _previousId++;
  }

  function registerWish(magicWords, action, context, data, id) {
    if (!Array.isArray(magicWords)) {
      // If they passed an object instead.
      if (typeof magicWords === 'object') {
        return registerWish(magicWords.magicWords, magicWords.action, magicWords.context, magicWords.data, magicWords.id);
      } else {
        magicWords = [magicWords];
      }
    }
    if (id === undefined) {
      id = _getNextId();
    }

    // Verify none of the magic words are objects
    for (var i = 0; i < magicWords.length; i++) {
      if (typeof magicWords[i] === 'object') {
        throw 'Cannot make an object a magic word!\n' + JSON.stringify(magicWords, null, 2);
      }
    }

    var wish = {
      id: id,
      context: context || _defaultContext,
      data: data,
      magicWords: magicWords,
      action: action
    };
    _wishes[id] = wish;
    return _wishes[id];
  }

  function deregisterWish(id) {
    // Check if it may be a wish object
    if (typeof id === 'object' && id.id) {
      id = id.id;
    }
    var wish = _wishes[id];
    delete _wishes[id];
    for (var word in _enteredMagicWords) {
      if (_enteredMagicWords[word].indexOf(id) != -1) {
        _enteredMagicWords[word].splice(_enteredMagicWords[word].indexOf(id), 1);
      }
    }
    return wish;
  }

  function clearWishes() {
    _wishes = {};
    _enteredMagicWords = {};
  }

  function getMatchingWishes(magicWord) {
    var otherMatchingWishId, allWishIds, matchingWishes, i; //Hoist-it!
    if (magicWord === undefined) {
      magicWord = '';
    } else if (magicWord === null) {
      return [];
    } else if (typeof magicWord === 'object') {
      throw 'Cannot match wishes to an object!\n' + JSON.stringify(magicWord, null, 2);
    }

    allWishIds = _enteredMagicWords[magicWord] || [];

    otherMatchingWishId = _getOtherMatchingMagicWords(allWishIds, magicWord);
    allWishIds = allWishIds.concat(otherMatchingWishId);

    matchingWishes = [];
    for (i = 0; i < allWishIds.length; i++) {
      matchingWishes.push(_wishes[allWishIds[i]]);
    }
    return matchingWishes;
  }

  function _getOtherMatchingMagicWords(currentMatchingWishIds, givenMagicWord) {
    var containsMagicWordWishIds = [];
    var acronymMagicWordWishIds = [];
    var otherMatchingWishIds = [];
    for (var wishId in _wishes) {
      if (currentMatchingWishIds.indexOf(wishId) == -1) {
        var wish =_wishes[wishId];
        if (_wishInContext(wish)) {
          var matchType = _bestMagicWordsMatch(wish.magicWords, givenMagicWord);
          switch (matchType) {
            case 'contains':
              containsMagicWordWishIds.push(wishId);
              break;
            case 'acronym':
              acronymMagicWordWishIds.push(wishId);
              break;
            case 'matches':
              otherMatchingWishIds.push(wishId);
              break;
            case '':
              break; // no match
          }
        }
      }
    }
    return containsMagicWordWishIds.concat(acronymMagicWordWishIds).concat(otherMatchingWishIds);
  }

  function _bestMagicWordsMatch(wishesMagicWords, givenMagicWord) {
    var bestMatch = '';
    for (var i = 0; i < wishesMagicWords.length; i++) {
      var matchType = _stringsMatch(wishesMagicWords[i], givenMagicWord);
      if ((matchType === 'contains')
        || (matchType === 'acronym' && (bestMatch === '' || bestMatch === 'matches'))
        || (matchType === 'matches' && bestMatch === '')) {
        bestMatch = matchType;
      }
      if (bestMatch === 'contains') {
        break;
      }
    }
    return bestMatch;
  }

  function _stringsMatch(magicWord, givenMagicWord) {
    var magicWordWords, splitByHyphen, acronym = '';

    magicWord = ('' + magicWord).toLowerCase();
    givenMagicWord = ('' + givenMagicWord).toLowerCase();

    // too long
    if (givenMagicWord.length > magicWord.length) {
      return '';
    }

    // contains
    if (magicWord.indexOf(givenMagicWord) != -1) {
      return 'contains';
    } else if (givenMagicWord.length == 1) {
      return '';
    }

    // acronym
    magicWordWords = magicWord.split(' ');
    for (var i = 0; i < magicWordWords.length; i++) {
      splitByHyphen = magicWordWords[i].split('-');
      for (var j = 0; j < splitByHyphen.length; j++) {
        acronym += splitByHyphen[j].substr(0, 1);
      }
    }
    if (acronym.indexOf(givenMagicWord) != -1) {
      return 'acronym';
    }

    return _stringsByCharOrder(magicWord, givenMagicWord);
  }

  function _stringsByCharOrder(magicWord, givenMagicWord) {
    var charNumber = 0;
    for (var i = 0; i < givenMagicWord.length; i++) {
      var matchChar = givenMagicWord[i];
      var found = false;
      for (var j = charNumber; j < magicWord.length; j++) {
        var stringChar = magicWord[j];
        if (stringChar == matchChar) {
          found = true;
          charNumber = j + 1;
          break;
        }
      }
      if (!found) {
        return '';
      }
    }
    return 'matches';
  }

  function makeWish(wish, magicWord) {
    var id, arry, existingIndex, first, matchingWishes;
    // Check if it may be a wish object
    if (typeof wish !== 'object') {
      wish = _wishes[wish];
    }
    if (wish === null || wish === undefined) {
      matchingWishes = getMatchingWishes(magicWord);
      if (matchingWishes.length > 0) {
        wish = matchingWishes[0];
      }
    }

    /* Don't execute the wish and return null if it:
     *   - doesn't exist
     *   - isn't in the registry
     *   - doesn't have an action
     *   - context doesn't match the current context and the wish's context is not the _defaultContext
     */
    if (!wish || !_wishes[wish.id] || !wish.action || !(_wishInContext(wish))) {
      return null;
    }

    wish.action(wish);

    if (magicWord !== undefined) {
      // Reset entered magicWords order.
      _enteredMagicWords[magicWord] = _enteredMagicWords[magicWord] || [];
      id = wish.id;
      arry = _enteredMagicWords[magicWord];
      existingIndex = arry.indexOf(id);
      if (existingIndex != -1) {
        // If it already exists, remove it before re-adding it in the correct spot
        arry.splice(existingIndex, 1);
      }
      if (existingIndex != 1 && arry.length > 0) {
        // If it's not "on deck" then put it in the first slot and set the King of the Hill to be the id to go first.
        first = arry[0];
        arry[0] = id;
        id = first;
      }
      arry.unshift(id);
    }
    return wish;
  }

  function _wishInContext(wish) {
    return _context === _defaultContext || wish.context === _defaultContext || wish.context === _context;
  }

  function options(options) {
    if (options) {
      _wishes = options.wishes || _wishes;
      _previousId = options.previousId || _previousId;
      _enteredMagicWords = options.enteredKeyWords || _enteredMagicWords;
      _context = options.context || _context;
      _previousContext = options.previousContext || _previousContext;
    }
    return {
      wishes: _wishes,
      previousId: _previousId,
      enteredMagicWords: _enteredMagicWords,
      contexts: _context,
      previousContext: _previousContext
    };
  }

  function context(newContext) {
    if (newContext) {
      _previousContext = _context;
      _context = newContext;
    }
    return _context;
  }

  function revertContext() {
    return context(_previousContext);
  }

  function restoreContext() {
    return context(_defaultContext);
  }

  global.genie = registerWish;
  global.genie.getMatchingWishes = getMatchingWishes;
  global.genie.makeWish = makeWish;
  global.genie.options = options;
  global.genie.deregisterWish = deregisterWish;
  global.genie.clearWishes = clearWishes;
  global.genie.context = context;
  global.genie.revertContext = revertContext;
  global.genie.restoreContext = restoreContext;

})(this);
<|endoftext|>


<commit_before>'use strict';
var path = require('path');

var _ = require('lodash');
var portfinder = require('portfinder');
var webpack = require('webpack');

var WebpackDevServer = require('webpack-dev-server');
var devConfig = require('../config/dev');

function devServer(port, config) {
  var devConfigParams = {};

  devConfigParams.entry = {
    main: [
      'webpack-dev-server/client?http://localhost:' + port,
      'webpack/hot/dev-server',
      path.join(__dirname, './dev_entry.js'),
    ],
  };

  devConfigParams.plugins = [
    new webpack.HotModuleReplacementPlugin(),
  ];

  devConfigParams.devtool = 'eval';
  devConfigParams.debug = true;

  return devConfig(config).then(function(c) {
    runServer(port, merge(devConfigParams, c));
  });
}

function merge(parent, child) {
  return _.merge({}, child, parent, function(a, b) {
    return _.isArray(a) ? a.concat(b) : undefined;
  });
}

function runServer(port, config) {
  new WebpackDevServer(webpack(config), {
    contentBase: path.join(process.cwd(), './.antwar/build'),
    hot: true,
    historyApiFallback: true,
    stats: {
      hash: false,
      version: false,
      assets: false,
      cached: false,
      colors: true,
    }
  }).listen(port, function(err) {
    if(err) {
      return console.error(err);
    }

    console.info('Listening at port ' + port);
  });
}

module.exports = function(config) {
  return new Promise(function(resolve, reject) {
    portfinder.getPort(function(err, port) {
      if(err) {
        return reject(err);
      }

      devServer(port, config);

      resolve();
    });
  });
};
<commit_msg>Tidy up dev server configuration<commit_after>'use strict';
var path = require('path');

var merge = require('webpack-merge');
var portfinder = require('portfinder');
var webpack = require('webpack');

var WebpackDevServer = require('webpack-dev-server');
var devConfig = require('../config/dev');

module.exports = function(config) {
  return new Promise(function(resolve, reject) {
    portfinder.getPort(function(err, port) {
      if(err) {
        return reject(err);
      }

      devServer(port, config);

      resolve();
    });
  });
};

function devServer(port, config) {
  var devConfigParams = {
    entry: {
      main: path.join(__dirname, './dev_entry.js'),
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin()
    ],
    devtool: 'eval',
    debug: true
  };

  return devConfig(config).then(function(c) {
    runServer(port, merge(c, devConfigParams));
  });
}

function runServer(port, config) {
  new WebpackDevServer(webpack(config), {
    contentBase: path.join(process.cwd(), './.antwar/build'),
    hot: true,
    inline: true,
    historyApiFallback: true,
    stats: {
      hash: false,
      version: false,
      assets: false,
      cached: false,
      colors: true,
    }
  }).listen(port, function(err) {
    if(err) {
      return console.error(err);
    }

    console.info('Listening at port ' + port);
  });
}
<|endoftext|>


<commit_before>var should = require('should');
process.env.NODE_ENV = 'mocha';
process.env.DB = 'test_iasurvey';
var app = require('../app.js');
var request = require('supertest');
var passwordHash = require('password-hash');

// used to wait for app before starting test
var waitOnApp = function(done){
  // wait for the controller to become available
  var checkFinished = function() {
    if(app.get('controller') === undefined) {
      setTimeout(checkFinished, 10);
    } else {
      done();
    }
  };
  checkFinished();
};

describe('Website View', function() {
  before(waitOnApp);

  it('should be able to fetch the survey page', function(done) {
    request(app)
      .get('/')
      .expect(200)
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should be able to fetch the subscribe page', function(done) {
    request(app)
      .get('/subscribe')
      .expect(200)
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should be able to fetch the login page', function(done) {
    request(app)
      .get('/admin/login')
      .expect(200)
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });
});

describe('Login Mask', function() {
  before(waitOnApp);

  it('should not be able to fetch the admin index without login', function(done) {
    request(app)
      .get('/admin')
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the password-update page without login', function(done) {
    request(app)
      .get('/admin/password-update')
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the survey manage page without login', function(done) {
    request(app)
      .get('/admin/surveys')
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the survey create page without login', function(done) {
    request(app)
      .get('/admin/surveys/create')
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the staff manage page without login', function(done) {
    request(app)
      .get('/admin/staff')
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the staff create page without login', function(done) {
    request(app)
      .get('/admin/staff/create')
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });
});
<commit_msg>fix website view test program<commit_after>var should = require('should');
process.env.NODE_ENV = 'mocha';
process.env.DB = 'test_iasurvey';
var app = require('../app.js');
var request = require('supertest');
var passwordHash = require('password-hash');

// used to wait for app before starting test
var waitOnApp = function(done){
  // wait for the controller to become available
  var checkFinished = function() {
    if(app.get('controller') === undefined) {
      setTimeout(checkFinished, 10);
    } else {
      done();
    }
  };
  checkFinished();
};

describe('Website View', function() {
  before(waitOnApp);

  it('should be able to fetch the survey page', function(done) {
    request(app)
      .get('/')
      .expect(200)
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should be able to fetch the subscribe page', function(done) {
    request(app)
      .get('/subscribe')
      .expect(200)
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should be able to fetch the login page', function(done) {
    request(app)
      .get('/admin/login')
      .expect(200)
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });
});

describe('Login Mask', function() {
  before(waitOnApp);

  it('should not be able to fetch the admin index without login', function(done) {
    request(app)
      .get('/admin')
      .expect(302)
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the password-update page without login', function(done) {
    request(app)
      .get('/admin/password-update')
      .expect(302)
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the survey manage page without login', function(done) {
    request(app)
      .get('/admin/surveys')
      .expect(302)
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the survey create page without login', function(done) {
    request(app)
      .get('/admin/surveys/create')
      .expect(302)
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the staff manage page without login', function(done) {
    request(app)
      .get('/admin/staff')
      .expect(302)
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });

  it('should not be able to fetch the staff create page without login', function(done) {
    request(app)
      .get('/admin/staff/create')
      .expect(302)
      .expect('Moved Temporarily. Redirecting to /admin/login')
      .end(function (err, res){
      should.not.exist(err);
      done();
      });
  });
});
<|endoftext|>


<commit_before>require('chai').should();

var JSDOC = require('../../lib/jsdoc'),
    FS = require('fs'),
    PATH = require('path'),
    PRJ_ROOT = PATH.join(__dirname, '..', '..');

exports.testPlugins = function(testFile, plugins) {
    var jsdoc = new JSDOC();
    (
        plugins ||
        [
            'class',
            'module',
            'type',
            'exports',
            'alias',
            'description',
            'constructor',
            'augments',
            'const',
            'deprecated',
            'param',
            'returns'
        ]
    ).forEach(function(plugin) {
        jsdoc.registerPlugin(PATH.join(PRJ_ROOT, 'plugins', plugin));
    });

    var baseName = PATH.basename(testFile, '.js');

    describe(baseName, function() {
        FS.readdirSync(PATH.join(PATH.dirname(testFile), baseName)).forEach(function(fileName) {
            if(PATH.extname(fileName) === '.js') {
                var dirName = PATH.join(__dirname, '..', baseName),
                    jsFileName = PATH.join(dirName, fileName),
                    jsonFileName = PATH.join(dirName, fileName.replace(/\.js$/, '.json')),
                    resFileName = PATH.join(dirName, fileName.replace(/\.js$/, '.res.json'));

                it(
                    PATH.relative(PRJ_ROOT, jsFileName) +
                        ' should be parsed as expected in ' +
                        PATH.relative(PRJ_ROOT, jsonFileName),
                    function() {
                        // NOTE: JSON.parse(JSON.stringify(...)) because of Chai.js bug
                        var res = JSON.stringify(jsdoc.doIt(FS.readFileSync(jsFileName, 'utf-8')), null, 4);
                        FS.writeFileSync(resFileName, res);
                        JSON.parse(res).should.be.eql(
                            JSON.parse(FS.readFileSync(jsonFileName)),
                            'Result file: ' + resFileName);
                    }
                );
            }
        });
    });
};
<commit_msg>show relative paths in tests<commit_after>require('chai').should();

var JSDOC = require('../../lib/jsdoc'),
    FS = require('fs'),
    PATH = require('path'),
    PRJ_ROOT = PATH.join(__dirname, '..', '..');

exports.testPlugins = function(testFile, plugins) {
    var jsdoc = new JSDOC();
    (
        plugins ||
        [
            'class',
            'module',
            'type',
            'exports',
            'alias',
            'description',
            'constructor',
            'augments',
            'const',
            'deprecated',
            'param',
            'returns'
        ]
    ).forEach(function(plugin) {
        jsdoc.registerPlugin(PATH.join(PRJ_ROOT, 'plugins', plugin));
    });

    var baseName = PATH.basename(testFile, '.js');

    describe(baseName, function() {
        FS.readdirSync(PATH.join(PATH.dirname(testFile), baseName)).forEach(function(fileName) {
            if(PATH.extname(fileName) === '.js') {
                var dirName = PATH.join(__dirname, '..', baseName),
                    jsFileName = PATH.join(dirName, fileName),
                    jsonFileName = PATH.join(dirName, fileName.replace(/\.js$/, '.json')),
                    resFileName = PATH.join(dirName, fileName.replace(/\.js$/, '.res.json'));

                it(
                    PATH.relative(PRJ_ROOT, jsFileName) +
                        ' should be parsed as expected in ' +
                        PATH.relative(PRJ_ROOT, jsonFileName),
                    function() {
                        // NOTE: JSON.parse(JSON.stringify(...)) because of Chai.js bug
                        var res = JSON.stringify(jsdoc.doIt(FS.readFileSync(jsFileName, 'utf-8')), null, 4);
                        FS.writeFileSync(resFileName, res);
                        JSON.parse(res).should.be.eql(
                            JSON.parse(FS.readFileSync(jsonFileName)),
                            'Result file: ' + resFileName);
                    }
                );
            }
        });
    });
};<|endoftext|>


<commit_before>const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser').json();
const TimeBlock = require('../models/timeblock');

router

  .post('/', bodyParser, (req, res, next) => {
    req.body.userId = req.user.id;
    new TimeBlock(req.body).save()
      .then(saved => res.send(saved))
      .catch(next);
  })

  .put('/:id', bodyParser, (req, res, next) => {
    TimeBlock.findById(req.params.id)
      .then(block => {
        if (req.user.id === block.userId.toString()) {
          for (var key in req.body) {
            block[key] = req.body[key];
          }
          return block.save();
        } else {
          throw {
            code: 403,
            error: 'Unauthorized, invalid token'
          };
        }
      })
      .then(saved => res.json(saved))
      .catch(next);
  })

  // .delete('/:id', (req, res, next) => {

  //   //TODO: if nothing to delete throw a 404
  //   TimeBlock.findByIdAndRemove(req.params.id)
  //     .then(deleted => res.send(deleted))
  //     .catch(next);
  // })

  .delete('/:id', (req, res, next) => {
    TimeBlock.findById(req.params.id)
      .then(block => {
        if (req.user.id === block.userId.toString()) {
          return block.remove();
        } else {
          throw {
            code: 403,
            error: 'Unauthorized, invalid token'
          };
        }
      })
      .then(deleted => res.json(deleted))
      .catch(next);
  })

  .get('/users', (req, res, next) => {
    console.log(req.user.toString());
    let userId = req.user.id.toString();
    TimeBlock.find({userId})
        .lean()
        .then(blocks => {
          console.log(blocks);
          if (!blocks) {
            throw {
              code: 404,
              error: 'Not found'
            };
          } else {
            return res.json(blocks);
          }
        })
        .catch(next);
  })

  .get('/:id', (req, res, next) => {
    TimeBlock.findById(req.params.id)
      .then(timeblock => {
        if (!timeblock) {
          throw {
            code: 404,
            error: 'Not found'
          };
        } else if (req.user.id === timeblock.userId.toString()) {
          return res.send(timeblock);
        } else {
          throw {
            code: 403,
            error: 'Unauthorized, invalid token'
          };
        }
      })
      .catch(next);

  });

module.exports = router;

  <commit_msg>Tried changing let to var in time-blocks.js to see if Heroku will work<commit_after>const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser').json();
const TimeBlock = require('../models/timeblock');

router

  .post('/', bodyParser, (req, res, next) => {
    req.body.userId = req.user.id;
    new TimeBlock(req.body).save()
      .then(saved => res.send(saved))
      .catch(next);
  })

  .put('/:id', bodyParser, (req, res, next) => {
    TimeBlock.findById(req.params.id)
      .then(block => {
        if (req.user.id === block.userId.toString()) {
          for (var key in req.body) {
            block[key] = req.body[key];
          }
          return block.save();
        } else {
          throw {
            code: 403,
            error: 'Unauthorized, invalid token'
          };
        }
      })
      .then(saved => res.json(saved))
      .catch(next);
  })

  // .delete('/:id', (req, res, next) => {

  //   //TODO: if nothing to delete throw a 404
  //   TimeBlock.findByIdAndRemove(req.params.id)
  //     .then(deleted => res.send(deleted))
  //     .catch(next);
  // })

  .delete('/:id', (req, res, next) => {
    TimeBlock.findById(req.params.id)
      .then(block => {
        if (req.user.id === block.userId.toString()) {
          return block.remove();
        } else {
          throw {
            code: 403,
            error: 'Unauthorized, invalid token'
          };
        }
      })
      .then(deleted => res.json(deleted))
      .catch(next);
  })

  .get('/users', (req, res, next) => {
    console.log(req.user.toString());
    var userId = req.user.id.toString();
    TimeBlock.find({userId})
        .lean()
        .then(blocks => {
          console.log(blocks);
          if (!blocks) {
            throw {
              code: 404,
              error: 'Not found'
            };
          } else {
            return res.json(blocks);
          }
        })
        .catch(next);
  })

  .get('/:id', (req, res, next) => {
    TimeBlock.findById(req.params.id)
      .then(timeblock => {
        if (!timeblock) {
          throw {
            code: 404,
            error: 'Not found'
          };
        } else if (req.user.id === timeblock.userId.toString()) {
          return res.send(timeblock);
        } else {
          throw {
            code: 403,
            error: 'Unauthorized, invalid token'
          };
        }
      })
      .catch(next);

  });

module.exports = router;

  <|endoftext|>


<commit_before>require('mocha');
require('should');
var assert = require('assert');
var support = require('./support');
var App = support.resolve();
var app;

describe('engine support', function() {
  beforeEach(function() {
    app = new App();
  });

  it('should throw an error when engine name is invalid:', function() {
    (function() {
      app.engine(null, {});
    }).should.throw('expected engine ext to be a string or array.');
  });

  it('should register an engine to the given extension', function() {
    app.engine('hbs', function() {});
    assert(typeof app.engines['.hbs'] === 'object');
  });

  it('should set an engine with the given extension', function() {
    var hbs = function() {};
    hbs.render = function() {};
    hbs.renderFile = function() {};
    app.engine('hbs', hbs);
    assert(app.engines['.hbs']);
    assert(app.engines['.hbs'].renderFile);
    assert(app.engines['.hbs'].render);
  });

  it('should get an engine:', function() {
    app.engine('hbs', function() {});
    var hbs = app.engine('hbs');
    assert(typeof hbs === 'object');
    assert(hbs.hasOwnProperty('render'));
    assert(hbs.hasOwnProperty('compile'));
  });

  it('should return undefined if no engine is found:', function() {
    var hbs = app.getEngine();
    assert.equal(typeof hbs, 'undefined');
  });

  it('should register multiple engines to the given extension', function() {
    app.engine(['hbs', 'md'], function() {});
    assert(typeof app.engines['.hbs'] === 'object');
    assert(typeof app.engines['.md'] === 'object');
  });
});

describe('engines', function() {
  beforeEach(function() {
    app = new App();
    app.create('pages');
    app.pages('foo.tmpl', {content: 'A <%= letter %> {{= letter }} C'});
    app.pages('bar.tmpl', {content: 'A <%= letter %> {{ letter }} C'});
  });

  it('should register an engine:', function() {
    app.engine('a', {render: function() {}});
    app.engines.should.have.property('.a');
  });

  it('should use custom delimiters:', function(done) {
    app.engine('tmpl', require('engine-base'), {
      delims: ['{{', '}}']
    });
    app.render('foo.tmpl', {letter: 'B'}, function(err, res) {
      if (err) return done(err);
      res.contents.toString().should.equal('A <%= letter %> B C');
      done();
    });
  });

  it('should override individual delims values:', function(done) {
    app.engine('tmpl', require('engine-base'), {
      interpolate: /\{{([^}]+)}}/g,
      evaluate: /\{{([^}]+)}}/g,
      escape: /\{{-([^}]+)}}/g
    });
    app.render('bar.tmpl', {letter: 'B'}, function(err, res) {
      if (err) return done(err);
      res.contents.toString().should.equal('A <%= letter %> B C');
      done();
    });
  });

  it('should get an engine:', function() {
    app.engine('a', {
      render: function() {}
    });
    var a = app.engine('a');
    a.should.have.property('render');
  });
});

describe('engine selection:', function() {
  beforeEach(function(done) {
    app = new App();
    app.engine('tmpl', require('engine-base'));
    app.engine('hbs', require('engine-handlebars'));
    app.create('pages');
    done();
  });

  it('should get the engine from file extension:', function(done) {
    app.page('a.tmpl', {content: '<%= a %>', locals: {a: 'b'}})
      .render(function(err, view) {
        if (err) return done(err);
        assert(view.content === 'b');
        done();
      });
  });

  it('should use the engine defined on the collection:', function(done) {
    app.create('posts', {engine: 'hbs'});

    app.post('a', {content: '{{a}}', locals: {a: 'b'}})
      .render(function(err, view) {
        if (err) return done(err);
        assert(view.content === 'b');
        done();
      });
  });

  it('should use the engine defined on the view:', function(done) {
    app.create('posts');
    app.post('a', {content: '{{a}}', engine: 'hbs', locals: {a: 'b'}})
      .render(function(err, view) {
        if (err) return done(err);
        assert(view.content === 'b');
        done();
      });
  });

  it('should use the engine defined on `view.data`:', function(done) {
    app.create('posts');
    app.post('a', {content: '{{a}}', locals: {a: 'b'}, data: {engine: 'hbs'}})
      .render(function(err, view) {
        if (err) return done(err);
        assert(view.content === 'b');
        done();
      });
  });

  it('should use the engine defined on render locals:', function(done) {
    app.create('posts');
    app.post('a', {content: '{{a}}', locals: {a: 'b'}})
      .render({engine: 'hbs'}, function(err, view) {
        if (err) return done(err);
        assert(view.content === 'b');
        done();
      });
  });
});
<commit_msg>formatting<commit_after>require('mocha');
require('should');
var async = require('async');
var assert = require('assert');
var support = require('./support');
var App = support.resolve();
var app;

describe('engine support', function() {
  beforeEach(function() {
    app = new App();
  });

  it('should throw an error when engine name is invalid:', function() {
    (function() {
      app.engine(null, {});
    }).should.throw('expected engine ext to be a string or array.');
  });

  it('should register an engine to the given extension', function() {
    app.engine('hbs', function() {});
    assert(typeof app.engines['.hbs'] === 'object');
  });

  it('should set an engine with the given extension', function() {
    var hbs = function() {};
    hbs.render = function() {};
    hbs.renderFile = function() {};
    app.engine('hbs', hbs);
    assert(app.engines['.hbs']);
    assert(app.engines['.hbs'].renderFile);
    assert(app.engines['.hbs'].render);
  });

  it('should get an engine:', function() {
    app.engine('hbs', function() {});
    var hbs = app.engine('hbs');
    assert(typeof hbs === 'object');
    assert(hbs.hasOwnProperty('render'));
    assert(hbs.hasOwnProperty('compile'));
  });

  it('should return undefined if no engine is found:', function() {
    var hbs = app.getEngine();
    assert.equal(typeof hbs, 'undefined');
  });

  it('should register multiple engines to the given extension', function() {
    app.engine(['hbs', 'md'], function() {});
    assert(typeof app.engines['.hbs'] === 'object');
    assert(typeof app.engines['.md'] === 'object');
  });
});

describe('engines', function() {
  beforeEach(function() {
    app = new App();
    app.create('pages');
    app.pages('foo.tmpl', {content: 'A <%= letter %> {{= letter }} C'});
    app.pages('bar.tmpl', {content: 'A <%= letter %> {{ letter }} C'});
  });

  it('should register an engine:', function() {
    app.engine('a', {render: function() {}});
    app.engines.should.have.property('.a');
  });

  it('should use custom delimiters:', function(cb) {
    app.engine('tmpl', require('engine-base'), {
      delims: ['{{', '}}']
    });
    app.render('foo.tmpl', {letter: 'B'}, function(err, res) {
      if (err) return cb(err);
      res.contents.toString().should.equal('A <%= letter %> B C');
      cb();
    });
  });

  it('should override individual delims values:', function(cb) {
    app.engine('tmpl', require('engine-base'), {
      interpolate: /\{{([^}]+)}}/g,
      evaluate: /\{{([^}]+)}}/g,
      escape: /\{{-([^}]+)}}/g
    });
    app.render('bar.tmpl', {letter: 'B'}, function(err, res) {
      if (err) return cb(err);
      res.contents.toString().should.equal('A <%= letter %> B C');
      cb();
    });
  });

  it('should get an engine:', function() {
    app.engine('a', {
      render: function() {}
    });
    var a = app.engine('a');
    a.should.have.property('render');
  });
});

describe('engine selection:', function() {
  beforeEach(function(cb) {
    app = new App();
    app.engine('tmpl', require('engine-base'));
    app.engine('hbs', require('engine-handlebars'));
    app.create('pages');
    cb();
  });

  it('should get the engine from file extension:', function(cb) {
    app.page('a.tmpl', {content: '<%= a %>', locals: {a: 'b'}})
      .render(function(err, view) {
        if (err) return cb(err);
        assert(view.content === 'b');
        cb();
      });
  });

  it('should use the engine defined on the collection:', function(cb) {
    app.create('posts', {engine: 'hbs'});

    app.post('a', {content: '{{a}}', locals: {a: 'b'}})
      .render(function(err, view) {
        if (err) return cb(err);
        assert(view.content === 'b');
        cb();
      });
  });

  it('should use the engine defined on the view:', function(cb) {
    app.create('posts');
    app.post('a', {content: '{{a}}', engine: 'hbs', locals: {a: 'b'}})
      .render(function(err, view) {
        if (err) return cb(err);
        assert(view.content === 'b');
        cb();
      });
  });

  it('should use the engine defined on `view.data`:', function(cb) {
    app.create('posts');
    app.post('a', {content: '{{a}}', locals: {a: 'b'}, data: {engine: 'hbs'}})
      .render(function(err, view) {
        if (err) return cb(err);
        assert(view.content === 'b');
        cb();
      });
  });

  it('should use the engine defined on render locals:', function(cb) {
    app.create('posts');
    app.post('a', {content: '{{a}}', locals: {a: 'b'}})
      .render({engine: 'hbs'}, function(err, view) {
        if (err) return cb(err);
        assert(view.content === 'b');
        cb();
      });
  });
});
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var utils = require('../util/utils');
var defaultAcceptorFactory = require('./acceptor');
var Dispatcher = require('./dispatcher');
var fs = require('fs');
var Loader = require('pomelo-loader');

var Gateway = function(opts) {
  EventEmitter.call(this);
  this.opts = opts || {};
  this.port = opts.port || 3050;
  this.host = opts.host || '0.0.0.0';
  this.started = false;
  this.stoped = false;
  this.acceptorFactory = opts.acceptorFactory || defaultAcceptorFactory;
  this.services = opts.services;
  var dispatcher = new Dispatcher(this.services);
  if(!!this.opts.reloadRemotes) {
    watchServices(this, dispatcher);
  }
  var self = this;
  this.acceptor = this.acceptorFactory.create(opts, function(tracer, msg, cb) {
    dispatcher.route(tracer, msg, cb);
  });
};
util.inherits(Gateway, EventEmitter);

var pro = Gateway.prototype;

pro.stop = function() {
  if(!this.started || this.stoped) {
    return;
  }
  this.stoped = true;
  try {
    this.acceptor.close();
  } catch(err) {}
};

pro.start = function() {
  if(this.started) {
    throw new Error('gateway already start.');
  }
  this.started = true;

  var self = this;
  this.acceptor.on('error', self.emit.bind(self, 'error'));
  this.acceptor.on('closed', self.emit.bind(self, 'closed'));
  this.acceptor.listen(this.port, this.host);
};

/**
 * create and init gateway
 *
 * @param opts {services: {rpcServices}, connector:conFactory(optional), router:routeFunction(optional)}
 */
module.exports.create = function(opts) {
  if(!opts || !opts.services) {
    throw new Error('opts and opts.services should not be empty.');
  }

  return new Gateway(opts);
};

var watchServices = function(gateway, dispatcher) {
  var paths = gateway.opts.paths;
  var app = gateway.opts.context;
  for(var i=0; i<paths.length; i++) {
    (function(index) {
      fs.watch(paths[index].path, function(event, name) {
        if(event === 'change') {
          var res = {};
          var item = paths[index];
          var m = Loader.load(item.path, app);
          if(m) {
            createNamespace(item.namespace, res);
            for(var s in m) {
              res[item.namespace][s] = m[s];
            }
          }
          dispatcher.emit('reload', res);
        }
      });
    })(i);
  }
};

var createNamespace = function(namespace, proxies) {
  proxies[namespace] = proxies[namespace] || {};
};
<commit_msg>queue acceptor<commit_after>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var utils = require('../util/utils');
var defaultAcceptorFactory = require('./acceptor');
var Dispatcher = require('./dispatcher');
var fs = require('fs');
var Loader = require('pomelo-loader');

var Gateway = function(opts) {
  EventEmitter.call(this);
  this.opts = opts || {};
  this.port = opts.port || 3050;
  this.host = opts.host || '0.0.0.0';
  this.dispatchEnqueue = opts.dispatchEnqueue || false;
  this.started = false;
  this.stoped = false;
  this.acceptorFactory = opts.acceptorFactory || defaultAcceptorFactory;
  this.services = opts.services;
  this.dispatcher = new Dispatcher(this.services);
  if(!!this.opts.reloadRemotes) {
    watchServices(this, this.dispatcher);
  }
  var msgProcessCB;
  if (this.dispatchEnqueue) {
    this.dispatchInterval = opts.dispatchInterval || 50;
    this.dispatchCountOnce = opts.dispatchCountOnce || 0;
    this.msgMaxPriority = opts.msgMaxPriority || 10;
    if (this.dispatchCountOnce <= 0) {
      this.dispatchCountOnce = (1 << 30)
    }
    this.dispatchQueue = [];
    msgProcessCB = this.queueMsg.bind(this);
  }
  else {
    msgProcessCB = this.dispatcher.route.bind(this.dispatcher);
  }

  this.acceptor = this.acceptorFactory.create(opts, msgProcessCB);
};
util.inherits(Gateway, EventEmitter);

var pro = Gateway.prototype;

pro.stop = function() {
  if(!this.started || this.stoped) {
    return;
  }
  this.stoped = true;
  try {
    this.acceptor.close();
  } catch(err) {}
};

pro.start = function() {
  if(this.started) {
    throw new Error('gateway already start.');
  }
  this.started = true;

  var self = this;
  this.acceptor.on('error', self.emit.bind(self, 'error'));
  this.acceptor.on('closed', self.emit.bind(self, 'closed'));
  this.acceptor.listen(this.port, this.host);

  if (this.dispatchEnqueue) {
    setInterval(this.dispatchQueuedMsg.bind(this), this.dispatchInterval)
  }
};

pro.queueMsg = function(tracer, msg, cb) {
  var priority
  if (!msg.priority || msg.priority < 0) {
    priority = 0
  }
  else {
    priority = msg.priority
    if (priority > this.msgMaxPriority) {
      priority = this.msgMaxPriority
    }
  }

  if (!this.dispatchQueue[priority]) {
    this.dispatchQueue[priority] = []
  }
  this.dispatchQueue[priority].push([tracer, msg, cb])
};

pro.dispatchQueuedMsg = function() {
  var count = this.dispatchCountOnce;
  var i, j;
console.time('dispatchQueuedMsg')
  for (i=0; i<this.dispatchQueue.length; ++i) {
    var queue = this.dispatchQueue[i]
    if (!!queue && queue.length>0) {
      for (j=0; j<queue.length; ++j) {
        this.dispatcher.route.apply(this.dispatcher, queue[j])
        count--
        if (!count) {
          break
        }
      }
      this.dispatchQueue[i] = queue.slice(j)

      if (!count) {
        break
      }
    }
  }
console.timeEnd('dispatchQueuedMsg')
console.log('process %s msg', this.dispatchCountOnce - count)
};

pro.getQueuedMsgCount = function() {
  var count = 0
  for (i=0; i<this.dispatchQueue.length; ++i) {
    if (!!this.dispatchQueue[i]) {
      count += this.dispatchQueue[i].length
    }
  }
  return count
}

pro.setDispatchCountOnce = function(dispatchCountOnce) {
  this.dispatchCountOnce = dispatchCountOnce
}

/**
 * create and init gateway
 *
 * @param opts {services: {rpcServices}, connector:conFactory(optional), router:routeFunction(optional)}
 */
module.exports.create = function(opts) {
  if(!opts || !opts.services) {
    throw new Error('opts and opts.services should not be empty.');
  }

  return new Gateway(opts);
};

var watchServices = function(gateway, dispatcher) {
  var paths = gateway.opts.paths;
  var app = gateway.opts.context;
  for(var i=0; i<paths.length; i++) {
    (function(index) {
      fs.watch(paths[index].path, function(event, name) {
        if(event === 'change') {
          var res = {};
          var item = paths[index];
          var m = Loader.load(item.path, app);
          if(m) {
            createNamespace(item.namespace, res);
            for(var s in m) {
              res[item.namespace][s] = m[s];
            }
          }
          dispatcher.emit('reload', res);
        }
      });
    })(i);
  }
};

var createNamespace = function(namespace, proxies) {
  proxies[namespace] = proxies[namespace] || {};
};

<|endoftext|>


<commit_before>;((rc) => {
  'use strict';
  var tagContent = 'router2-content';
  var tagView = 'router2-view';
  var tagSrc = 'router2-src';

  var div = document.createElement('div');
  div.innerHTML = `
    <${tagContent} hash="case8" src="/test/case8/case8-external.html">
    </${tagContent}>
  `;

  var async1 = async_test('Case 8: hash changed to content[hash="case8"] and imports from "case8-external.html"');

  async1.next = async1.step_func(_ => {
    var hash = "case8";
    var content = document.querySelector(`${tagContent}[hash="${hash}"]`);

    // Simulate what the pseudoHTMLimport should do
    //content.innerHTML = `
    //  <${tagSrc}>
This is an external content
</${tagSrc}>
    //`;

    var check_hash = async1.step_func((e) => {
      assert_false(content.hidden);

      var src = content.querySelector(`${tagSrc}`);
      assert_true(src instanceof HTMLElement);
      assert_equals(src.textContent, 'This is an external content\n');

      // clean the test
      window.removeEventListener('hashchange', check_hash);
      document.body.removeChild(div);
      window.location.hash = '';

      async1.done();
      rc.next();
    });

    content.addEventListener('show', check_hash);
    window.location.hash = hash;
  });

  rc.push(_ => {
    async1.step(_ => {
      document.body.appendChild(div);
      async1.next();
    });
  })

})(window.routeCases);
<commit_msg>Add a second test for case 8<commit_after>;((rc) => {
  'use strict';
  var tagContent = 'router2-content';
  var tagView = 'router2-view';
  var tagSrc = 'router2-src';

  var div = document.createElement('div');
  div.innerHTML = `
    <${tagContent} hash="case8" src="/test/case8/case8-external.html">
    </${tagContent}>
  `;

  var async1 = async_test('Case 8: hash changed to content[hash="case8"] and imports from "case8-external.html"');
  var async2 = async_test('Case 8: repeat last test and see if case8-external.html has been fetched once');

  async1.next = async1.step_func(_ => {
    var hash = "case8";
    var content = document.querySelector(`${tagContent}[hash="${hash}"]`);

    var check_hash = async1.step_func((e) => {
      assert_false(content.hidden);

      var src = content.querySelector(`${tagSrc}`);
      assert_true(src instanceof HTMLElement);
      assert_equals(src.textContent, 'This is an external content\n');

      // clean the test
      window.location.hash = '';

      async1.done();
      async2.next();
    });

    content.addEventListener('show', check_hash);
    window.location.hash = hash;
  });

  async2.next = async2.step_func(_ => {
    var hash = "case8";
    var content = document.querySelector(`${tagContent}[hash="${hash}"]`);

    var check_hash = async2.step_func((e) => {
      assert_false(content.hidden);

      var src = content.querySelector(`${tagSrc}`);
      assert_true(src instanceof HTMLElement);
      assert_equals(src.textContent, 'This is an external content\n');

      // clean the test
      window.removeEventListener('hashchange', check_hash);
      document.body.removeChild(div);
      window.location.hash = '';

      async2.done();
      rc.next();
    });

    content.addEventListener('show', check_hash);
    window.location.hash = hash;
  });

  rc.push(_ => {
    async1.step(_ => {
      document.body.appendChild(div);
      async1.next();
    });
  })

})(window.routeCases);
<|endoftext|>


<commit_before>const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const getFilesForOptions = require('./utils/utils').getFilesForOptions;
const expectedFiles = require('./utils/expected-files');
const angularFiles = require('../generators/client/files-angular').files;
const reactFiles = require('../generators/client/files-react').files;
const constants = require('../generators/generator-constants');
const { appDefaultConfig } = require('../generators/generator-defaults');
const {
    SUPPORTED_CLIENT_FRAMEWORKS: { ANGULAR, REACT, VUE },
} = require('../generators/generator-constants');

const { CLIENT_TEST_SRC_DIR } = constants;

describe('JHipster client generator', () => {
    describe('generate client with React', () => {
        before(done => {
            helpers
                .run(path.join(__dirname, '../generators/client'))
                .withOptions({ skipInstall: true, auth: 'jwt', experimental: true })
                .withPrompts({
                    baseName: 'jhipster',
                    serviceDiscoveryType: false,
                    enableTranslation: true,
                    nativeLanguage: 'en',
                    languages: ['fr'],
                    clientFramework: REACT,
                })
                .on('end', done);
        });
        it('creates expected files for react configuration for client generator', () => {
            assert.noFile(expectedFiles.maven);
            assert.file(expectedFiles.clientCommon);
            assert.file(
                getFilesForOptions(reactFiles, {
                    enableTranslation: true,
                    serviceDiscoveryType: false,
                    authenticationType: 'jwt',
                    testFrameworks: [],
                })
            );
        });
        it('contains clientFramework with react value', () => {
            assert.fileContent('.yo-rc.json', /"clientFramework": "react"/);
        });
        it('should not contain version placeholders at package.json', () => {
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_COMMON/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_ANGULAR/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_REACT/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_VUE/);
        });
    });

    describe('generate client with Angular', () => {
        before(done => {
            helpers
                .run(path.join(__dirname, '../generators/client'))
                .withOptions({ skipInstall: true, auth: 'jwt' })
                .withPrompts({
                    baseName: 'jhipster',
                    serviceDiscoveryType: false,
                    enableTranslation: true,
                    nativeLanguage: 'en',
                    languages: ['fr'],
                    clientFramework: ANGULAR,
                })
                .on('end', done);
        });

        it('creates expected files for default configuration for client generator', () => {
            assert.noFile(expectedFiles.server);
            assert.noFile(expectedFiles.maven);
            assert.file(expectedFiles.common);
            assert.file(expectedFiles.i18nJson);
            assert.file(expectedFiles.clientCommon);
            assert.file(
                getFilesForOptions(angularFiles, {
                    enableTranslation: true,
                    serviceDiscoveryType: false,
                    authenticationType: 'jwt',
                    testFrameworks: [],
                })
            );
        });
        it('contains clientFramework with angularX value', () => {
            assert.fileContent('.yo-rc.json', /"clientFramework": "angularX"/);
        });
        it('contains clientPackageManager with npm value', () => {
            assert.fileContent('.yo-rc.json', /"clientPackageManager": "npm"/);
        });
        it('should not contain version placeholders at package.json', () => {
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_COMMON/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_ANGULAR/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_REACT/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_VUE/);
        });
    });

    describe('--skip-jhipster-dependencies', () => {
        [ANGULAR, REACT, VUE].forEach(clientFramework => {
            describe(`and ${clientFramework}`, () => {
                let runResult;
                before(() => {
                    return helpers
                        .create(require.resolve('../generators/app'))
                        .withOptions({
                            fromCli: true,
                            skipInstall: true,
                            defaultLocalConfig: { ...appDefaultConfig, clientFramework, skipServer: true },
                            skipJhipsterDependencies: true,
                        })
                        .run()
                        .then(result => {
                            runResult = result;
                        });
                });

                after(() => runResult.cleanup());

                it('should add clientFramework to .yo-rc.json', () => {
                    runResult.assertFileContent('.yo-rc.json', `"clientFramework": "${clientFramework}"`);
                });
                it('should not add generator-jhipster to package.json', () => {
                    runResult.assertNoFileContent('package.json', 'generator-jhipster');
                });
            });
        });
    });

    describe('--with-admin-ui', () => {
        [ANGULAR].forEach(clientFramework => {
            describe(`selected and ${clientFramework}`, () => {
                let runResult;
                before(() => {
                    return helpers
                        .create(require.resolve('../generators/client'))
                        .withOptions({
                            fromCli: true,
                            skipInstall: true,
                            defaultLocalConfig: { ...appDefaultConfig, clientFramework, testFrameworks: ['cypress'] },
                            withAdminUi: true,
                        })
                        .run()
                        .then(result => {
                            runResult = result;
                        });
                });

                after(() => runResult.cleanup());

                it('should have admin ui components', () => {
                    runResult.assertFile(expectedFiles.clientAdmin);
                });

                it('should contains admin ui cypress tests', () => {
                    assert.fileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/integration/administration/administration.spec.ts`,
                        '  metricsPageHeadingSelector,\n' +
                            '  healthPageHeadingSelector,\n' +
                            '  logsPageHeadingSelector,\n' +
                            '  configurationPageHeadingSelector,'
                    );

                    assert.fileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/integration/administration/administration.spec.ts`,
                        "  describe('/metrics', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('metrics');\n" +
                            "      cy.get(metricsPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/health', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('health');\n" +
                            "      cy.get(healthPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/logs', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('logs');\n" +
                            "      cy.get(logsPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/configuration', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('configuration');\n" +
                            "      cy.get(configurationPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });'
                    );

                    assert.fileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/support/commands.ts`,
                        'export const metricsPageHeadingSelector = \'[data-cy="metricsPageHeading"]\';\n' +
                            'export const healthPageHeadingSelector = \'[data-cy="healthPageHeading"]\';\n' +
                            'export const logsPageHeadingSelector = \'[data-cy="logsPageHeading"]\';\n' +
                            'export const configurationPageHeadingSelector = \'[data-cy="configurationPageHeading"]\';'
                    );
                });
            });

            describe(`not selected and ${clientFramework}`, () => {
                let runResult;
                before(() => {
                    return helpers
                        .create(require.resolve('../generators/client'))
                        .withOptions({
                            fromCli: true,
                            skipInstall: true,
                            defaultLocalConfig: { ...appDefaultConfig, clientFramework, testFrameworks: ['cypress'] },
                            withAdminUi: false,
                        })
                        .run()
                        .then(result => {
                            runResult = result;
                        });
                });

                after(() => runResult.cleanup());

                it('should not have admin ui components', () => {
                    runResult.assertNoFile(expectedFiles.clientAdmin);
                });

                it('should not contains admin ui cypress tests', () => {
                    assert.noFileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/integration/administration/administration.spec.ts`,
                        '  metricsPageHeadingSelector,\n' +
                            '  healthPageHeadingSelector,\n' +
                            '  logsPageHeadingSelector,\n' +
                            '  configurationPageHeadingSelector,'
                    );

                    assert.noFileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/integration/administration/administration.spec.ts`,
                        "  describe('/metrics', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('metrics');\n" +
                            "      cy.get(metricsPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/health', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('health');\n" +
                            "      cy.get(healthPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/logs', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('logs');\n" +
                            "      cy.get(logsPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/configuration', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('configuration');\n" +
                            "      cy.get(configurationPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });'
                    );

                    assert.noFileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/support/commands.ts`,
                        'export const metricsPageHeadingSelector = \'[data-cy="metricsPageHeading"]\';\n' +
                            'export const healthPageHeadingSelector = \'[data-cy="healthPageHeading"]\';\n' +
                            'export const logsPageHeadingSelector = \'[data-cy="logsPageHeading"]\';\n' +
                            'export const configurationPageHeadingSelector = \'[data-cy="configurationPageHeading"]\';'
                    );
                });
            });
        });
    });
});
<commit_msg>Add a test about admin routing.<commit_after>const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const getFilesForOptions = require('./utils/utils').getFilesForOptions;
const expectedFiles = require('./utils/expected-files');
const angularFiles = require('../generators/client/files-angular').files;
const reactFiles = require('../generators/client/files-react').files;
const constants = require('../generators/generator-constants');
const { appDefaultConfig } = require('../generators/generator-defaults');
const {
    SUPPORTED_CLIENT_FRAMEWORKS: { ANGULAR, REACT, VUE },
} = require('../generators/generator-constants');

const { CLIENT_TEST_SRC_DIR, CLIENT_MAIN_SRC_DIR } = constants;

describe('JHipster client generator', () => {
    describe('generate client with React', () => {
        before(done => {
            helpers
                .run(path.join(__dirname, '../generators/client'))
                .withOptions({ skipInstall: true, auth: 'jwt', experimental: true })
                .withPrompts({
                    baseName: 'jhipster',
                    serviceDiscoveryType: false,
                    enableTranslation: true,
                    nativeLanguage: 'en',
                    languages: ['fr'],
                    clientFramework: REACT,
                })
                .on('end', done);
        });
        it('creates expected files for react configuration for client generator', () => {
            assert.noFile(expectedFiles.maven);
            assert.file(expectedFiles.clientCommon);
            assert.file(
                getFilesForOptions(reactFiles, {
                    enableTranslation: true,
                    serviceDiscoveryType: false,
                    authenticationType: 'jwt',
                    testFrameworks: [],
                })
            );
        });
        it('contains clientFramework with react value', () => {
            assert.fileContent('.yo-rc.json', /"clientFramework": "react"/);
        });
        it('should not contain version placeholders at package.json', () => {
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_COMMON/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_ANGULAR/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_REACT/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_VUE/);
        });
    });

    describe('generate client with Angular', () => {
        before(done => {
            helpers
                .run(path.join(__dirname, '../generators/client'))
                .withOptions({ skipInstall: true, auth: 'jwt' })
                .withPrompts({
                    baseName: 'jhipster',
                    serviceDiscoveryType: false,
                    enableTranslation: true,
                    nativeLanguage: 'en',
                    languages: ['fr'],
                    clientFramework: ANGULAR,
                })
                .on('end', done);
        });

        it('creates expected files for default configuration for client generator', () => {
            assert.noFile(expectedFiles.server);
            assert.noFile(expectedFiles.maven);
            assert.file(expectedFiles.common);
            assert.file(expectedFiles.i18nJson);
            assert.file(expectedFiles.clientCommon);
            assert.file(
                getFilesForOptions(angularFiles, {
                    enableTranslation: true,
                    serviceDiscoveryType: false,
                    authenticationType: 'jwt',
                    testFrameworks: [],
                })
            );
        });
        it('contains clientFramework with angularX value', () => {
            assert.fileContent('.yo-rc.json', /"clientFramework": "angularX"/);
        });
        it('contains clientPackageManager with npm value', () => {
            assert.fileContent('.yo-rc.json', /"clientPackageManager": "npm"/);
        });
        it('should not contain version placeholders at package.json', () => {
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_COMMON/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_ANGULAR/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_REACT/);
            assert.noFileContent('package.json', /VERSION_MANAGED_BY_CLIENT_VUE/);
        });
    });

    describe('--skip-jhipster-dependencies', () => {
        [ANGULAR, REACT, VUE].forEach(clientFramework => {
            describe(`and ${clientFramework}`, () => {
                let runResult;
                before(() => {
                    return helpers
                        .create(require.resolve('../generators/app'))
                        .withOptions({
                            fromCli: true,
                            skipInstall: true,
                            defaultLocalConfig: { ...appDefaultConfig, clientFramework, skipServer: true },
                            skipJhipsterDependencies: true,
                        })
                        .run()
                        .then(result => {
                            runResult = result;
                        });
                });

                after(() => runResult.cleanup());

                it('should add clientFramework to .yo-rc.json', () => {
                    runResult.assertFileContent('.yo-rc.json', `"clientFramework": "${clientFramework}"`);
                });
                it('should not add generator-jhipster to package.json', () => {
                    runResult.assertNoFileContent('package.json', 'generator-jhipster');
                });
            });
        });
    });

    describe('--with-admin-ui', () => {
        [ANGULAR].forEach(clientFramework => {
            describe(`selected and ${clientFramework}`, () => {
                let runResult;
                before(() => {
                    return helpers
                        .create(require.resolve('../generators/client'))
                        .withOptions({
                            fromCli: true,
                            skipInstall: true,
                            defaultLocalConfig: { ...appDefaultConfig, clientFramework, testFrameworks: ['cypress'] },
                            withAdminUi: true,
                        })
                        .run()
                        .then(result => {
                            runResult = result;
                        });
                });

                after(() => runResult.cleanup());

                it('should have admin ui components', () => {
                    runResult.assertFile(expectedFiles.clientAdmin);
                });

                it('should contains admin routing', () => {
                    runResult.assertFileContent(
                        `${CLIENT_MAIN_SRC_DIR}app/admin/admin-routing.module.ts`,
                        '        {\n' +
                            "          path: 'configuration',\n" +
                            "          loadChildren: () => import('./configuration/configuration.module').then(m => m.ConfigurationModule)\n" +
                            '        },\n' +
                            '        {\n' +
                            "          path: 'docs',\n" +
                            "          loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule)\n" +
                            '        },\n' +
                            '        {\n' +
                            "          path: 'health',\n" +
                            "          loadChildren: () => import('./health/health.module').then(m => m.HealthModule)\n" +
                            '        },\n' +
                            '        {\n' +
                            "          path: 'logs',\n" +
                            "          loadChildren: () => import('./logs/logs.module').then(m => m.LogsModule)\n" +
                            '        },\n' +
                            '        {\n' +
                            "          path: 'metrics',\n" +
                            "          loadChildren: () => import('./metrics/metrics.module').then(m => m.MetricsModule)\n" +
                            '        },'
                    );
                });

                it('should contains admin ui cypress tests', () => {
                    assert.fileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/integration/administration/administration.spec.ts`,
                        '  metricsPageHeadingSelector,\n' +
                            '  healthPageHeadingSelector,\n' +
                            '  logsPageHeadingSelector,\n' +
                            '  configurationPageHeadingSelector,'
                    );

                    assert.fileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/integration/administration/administration.spec.ts`,
                        "  describe('/metrics', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('metrics');\n" +
                            "      cy.get(metricsPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/health', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('health');\n" +
                            "      cy.get(healthPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/logs', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('logs');\n" +
                            "      cy.get(logsPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/configuration', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('configuration');\n" +
                            "      cy.get(configurationPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });'
                    );

                    assert.fileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/support/commands.ts`,
                        'export const metricsPageHeadingSelector = \'[data-cy="metricsPageHeading"]\';\n' +
                            'export const healthPageHeadingSelector = \'[data-cy="healthPageHeading"]\';\n' +
                            'export const logsPageHeadingSelector = \'[data-cy="logsPageHeading"]\';\n' +
                            'export const configurationPageHeadingSelector = \'[data-cy="configurationPageHeading"]\';'
                    );
                });
            });

            describe(`not selected and ${clientFramework}`, () => {
                let runResult;
                before(() => {
                    return helpers
                        .create(require.resolve('../generators/client'))
                        .withOptions({
                            fromCli: true,
                            skipInstall: true,
                            defaultLocalConfig: { ...appDefaultConfig, clientFramework, testFrameworks: ['cypress'] },
                            withAdminUi: false,
                        })
                        .run()
                        .then(result => {
                            runResult = result;
                        });
                });

                after(() => runResult.cleanup());

                it('should not have admin ui components', () => {
                    runResult.assertNoFile(expectedFiles.clientAdmin);
                });

                it('should not contains admin routing', () => {
                    runResult.assertNoFileContent(
                        `${CLIENT_MAIN_SRC_DIR}app/admin/admin-routing.module.ts`,
                        '        {\n' +
                            "          path: 'configuration',\n" +
                            "          loadChildren: () => import('./configuration/configuration.module').then(m => m.ConfigurationModule)\n" +
                            '        },\n' +
                            '        {\n' +
                            "          path: 'docs',\n" +
                            "          loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule)\n" +
                            '        },\n' +
                            '        {\n' +
                            "          path: 'health',\n" +
                            "          loadChildren: () => import('./health/health.module').then(m => m.HealthModule)\n" +
                            '        },\n' +
                            '        {\n' +
                            "          path: 'logs',\n" +
                            "          loadChildren: () => import('./logs/logs.module').then(m => m.LogsModule)\n" +
                            '        },\n' +
                            '        {\n' +
                            "          path: 'metrics',\n" +
                            "          loadChildren: () => import('./metrics/metrics.module').then(m => m.MetricsModule)\n" +
                            '        },'
                    );
                });

                it('should not contains admin ui cypress tests', () => {
                    assert.noFileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/integration/administration/administration.spec.ts`,
                        '  metricsPageHeadingSelector,\n' +
                            '  healthPageHeadingSelector,\n' +
                            '  logsPageHeadingSelector,\n' +
                            '  configurationPageHeadingSelector,'
                    );

                    assert.noFileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/integration/administration/administration.spec.ts`,
                        "  describe('/metrics', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('metrics');\n" +
                            "      cy.get(metricsPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/health', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('health');\n" +
                            "      cy.get(healthPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/logs', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('logs');\n" +
                            "      cy.get(logsPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });\n' +
                            '\n' +
                            "  describe('/configuration', () => {\n" +
                            "    it('should load the page', () => {\n" +
                            "      cy.clickOnAdminMenuItem('configuration');\n" +
                            "      cy.get(configurationPageHeadingSelector).should('be.visible');\n" +
                            '    });\n' +
                            '  });'
                    );

                    assert.noFileContent(
                        `${CLIENT_TEST_SRC_DIR}cypress/support/commands.ts`,
                        'export const metricsPageHeadingSelector = \'[data-cy="metricsPageHeading"]\';\n' +
                            'export const healthPageHeadingSelector = \'[data-cy="healthPageHeading"]\';\n' +
                            'export const logsPageHeadingSelector = \'[data-cy="logsPageHeading"]\';\n' +
                            'export const configurationPageHeadingSelector = \'[data-cy="configurationPageHeading"]\';'
                    );
                });
            });
        });
    });
});
<|endoftext|>