<commit_before>

// SETUP /////////////////////////////////////////////////////////////
// these functions set up specific areas after the boot function
// created a basic framework. All of these functions should only ever
// be run once.

window.setupLargeImagePreview = function() {
  $('#portaldetails').on('click', '.imgpreview img', function() {
    var ex = $('#largepreview');
    if(ex.length > 0) {
      ex.remove();
      return;
    }
    var img = $(this).parent().html();
    var w = $(this)[0].naturalWidth/2;
    var h = $(this)[0].naturalHeight/2;
    var c = $('#portaldetails').attr('class');
    $('body').append(
      '
' + img + '
'
    );
    $('#largepreview').click(function() { $(this).remove() });
    $('#largepreview img').attr('title', '');
  });
}

window.setupStyles = function() {
  $('head').append('');
}

window.setupMap = function() {
  $('#map').text('');

  var osmOpt = {attribution: 'Map data © OpenStreetMap contributors', maxZoom: 18};
  var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmOpt);

  var cmOpt = {attribution: 'Map data © OpenStreetMap contributors, Imagery © CloudMade', maxZoom: 18};
  var cmMin = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/22677/256/{z}/{x}/{y}.png', cmOpt);
  var cmMid = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/999/256/{z}/{x}/{y}.png', cmOpt);

  var views = [cmMid, cmMin, osm, new L.Google('INGRESS'), new L.Google('ROADMAP'),
               new L.Google('SATELLITE'), new L.Google('HYBRID')];

  window.map = new L.Map('map', $.extend(getPosition(),
    {zoomControl: !(localStorage['iitc.zoom.buttons'] === 'false')}
  ));

  try {
    map.addLayer(views[readCookie('ingress.intelmap.type')]);
  } catch(e) { map.addLayer(views[0]); }

  var addLayers = {};

  portalsLayers = [];
  for(var i = 0; i <= 8; i++) {
    portalsLayers[i] = L.layerGroup([]);
    map.addLayer(portalsLayers[i]);
    var t = (i === 0 ? 'Unclaimed' : 'Level ' + i) + ' Portals';
    addLayers[t] = portalsLayers[i];
  }

  fieldsLayer = L.layerGroup([]);
  map.addLayer(fieldsLayer, true);
  addLayers['Fields'] = fieldsLayer;

  linksLayer = L.layerGroup([]);
  map.addLayer(linksLayer, true);
  addLayers['Links'] = linksLayer;

  map.addControl(new L.Control.Layers({
    'OSM Cloudmade Midnight': views[0],
    'OSM Cloudmade Minimal': views[1],
    'OSM Mapnik': views[2],
    'Google Roads Ingress Style': views[3],
    'Google Roads':  views[4],
    'Google Satellite':  views[5],
    'Google Hybrid':  views[6]
    }, addLayers));
  map.attributionControl.setPrefix('');
  // listen for changes and store them in cookies
  map.on('moveend', window.storeMapPosition);
  map.on('zoomend', function() {
    window.storeMapPosition;

    // remove all resonators if zoom out to < RESONATOR_DISPLAY_ZOOM_LEVEL
    if(isResonatorsShow()) return;
    for(var i = 1; i < portalsLayers.length; i++) {
      portalsLayers[i].eachLayer(function(item) {
        var itemGuid = item.options.guid;
        // check if 'item' is a resonator
        if(getTypeByGuid(itemGuid) != TYPE_RESONATOR) return true;
        portalsLayers[i].removeLayer(item);
      });
    }

    console.log('Remove all resonators');
  });
  $("[name='leaflet-base-layers']").change(function () {
    writeCookie('ingress.intelmap.type', $(this).parent().index());
  });

  // map update status handling
  map.on('movestart zoomstart', function() { window.mapRunsUserAction = true });
  map.on('moveend zoomend', function() { window.mapRunsUserAction = false });

  // update map hooks
  map.on('movestart zoomstart', window.requests.abort);
  map.on('moveend zoomend', function() { window.startRefreshTimeout(500) });

  // run once on init
  window.requestData();
  window.startRefreshTimeout();

  window.addResumeFunction(window.requestData);
  window.requests.addRefreshFunction(window.requestData);
};

// renders player details into the website. Since the player info is
// included as inline script in the original site, the data is static
// and cannot be updated.
window.setupPlayerStat = function() {
  var level;
  var ap = parseInt(PLAYER.ap);
  for(level = 0; level < MIN_AP_FOR_LEVEL.length; level++) {
    if(ap < MIN_AP_FOR_LEVEL[level]) break;
  }

  var thisLvlAp = MIN_AP_FOR_LEVEL[level-1];
  var nextLvlAp = MIN_AP_FOR_LEVEL[level] || ap;
  var lvlUpAp = digits(nextLvlAp-ap);
  var lvlApProg = Math.round((ap-thisLvlAp)/(nextLvlAp-thisLvlAp)*100);

  var xmMax = MAX_XM_PER_LEVEL[level];
  var xmRatio = Math.round(PLAYER.energy/xmMax*100);

  var cls = PLAYER.team === 'ALIENS' ? 'enl' : 'res';

  var t = 'Level:\t\t' + level + '\n'
        + 'XM:\t\t\t' + PLAYER.energy + ' / ' + xmMax + '\n'
        + 'AP:\t\t\t' + digits(ap) + '\n'
        + (level < 8 ? 'level up in:\t' + lvlUpAp + ' AP' : 'Congrats! (neeeeerd)')
        + '\n\Invites:\t\t'+PLAYER.available_invites;
        + '\n\nNote: your player stats can only be updated by a full reload (F5)';

  $('#playerstat').html(''
    + '
'+level+' '
    + ''+PLAYER.nickname+''
    + '
'
    + 'XM: '+xmRatio+'%'
    + '' + (level < 8 ? 'level: '+lvlApProg+'%' : 'max level') + ''
    + '
'
    + '
'
  );
}

window.setupSidebarToggle = function() {
  $('#sidebartoggle').on('click', function() {
    var toggle = $('#sidebartoggle');
    var sidebar = $('#sidebar');
    if(sidebar.is(':visible')) {
      sidebar.hide();
      $('.leaflet-right').css('margin-right','0');
      toggle.html('');
      toggle.css('right', '0');
    } else {
      sidebar.show();
      $('.leaflet-right').css('margin-right', SIDEBAR_WIDTH+1+'px');
      toggle.html('');
      toggle.css('right', SIDEBAR_WIDTH+1+'px');
    }
  });
}

// BOOTING ///////////////////////////////////////////////////////////

function boot() {
  console.log('loading done, booting');
  window.setupStyles();
  window.setupMap();
  window.setupGeosearch();
  window.setupRedeem();
  window.setupLargeImagePreview();
  window.setupSidebarToggle();
  window.updateGameScore();
  window.setupPlayerStat();
  window.chat.setup();
  // read here ONCE, so the URL is only evaluated one time after the
  // necessary data has been loaded.
  urlPortal = getURLParam('pguid');

  // load only once
  var n = window.PLAYER['nickname'];
  window.PLAYER['nickMatcher'] = new RegExp('\\b('+n+')\\b', 'ig');

  $('#sidebar').show();

  if(window.bootPlugins)
    $.each(window.bootPlugins, function(ind, ref) { ref(); });

  window.iitcLoaded = true;
}

// this is the minified load.js script that allows us to easily load
// further javascript files async as well as in order.
// https://github.com/chriso/load.js
// Copyright (c) 2010 Chris O'Hara <cohara87@gmail.com>. MIT Licensed
function asyncLoadScript(a){return function(b,c){var d=document.createElement("script");d.type="text/javascript",d.src=a,d.onload=b,d.onerror=c,d.onreadystatechange=function(){var a=this.readyState;if(a==="loaded"||a==="complete")d.onreadystatechange=null,b()},head.insertBefore(d,head.firstChild)}}(function(a){a=a||{};var b={},c,d;c=function(a,d,e){var f=a.halt=!1;a.error=function(a){throw a},a.next=function(c){c&&(f=!1);if(!a.halt&&d&&d.length){var e=d.shift(),g=e.shift();f=!0;try{b[g].apply(a,[e,e.length,g])}catch(h){a.error(h)}}return a};for(var g in b){if(typeof a[g]=="function")continue;(function(e){a[e]=function(){var g=Array.prototype.slice.call(arguments);if(e==="onError"){if(d)return b.onError.apply(a,[g,g.length]),a;var h={};return b.onError.apply(h,[g,g.length]),c(h,null,"onError")}return g.unshift(e),d?(a.then=a[e],d.push(g),f?a:a.next()):c({},[g],e)}})(g)}return e&&(a.then=a[e]),a.call=function(b,c){c.unshift(b),d.unshift(c),a.next(!0)},a.next()},d=a.addMethod=function(d){var e=Array.prototype.slice.call(arguments),f=e.pop();for(var g=0,h=e.length;g<h;g++)typeof e[g]=="string"&&(b[e[g]]=f);--h||(b["then"+d.substr(0,1).toUpperCase()+d.substr(1)]=f),c(a)},d("chain",function(a){var b=this,c=function(){if(!b.halt){if(!a.length)return b.next(!0);try{null!=a.shift().call(b,c,b.error)&&c()}catch(d){b.error(d)}}};c()}),d("run",function(a,b){var c=this,d=function(){c.halt||--b||c.next(!0)},e=function(a){c.error(a)};for(var f=0,g=b;!c.halt&&f<g;f++)null!=a[f].call(c,d,e)&&d()}),d("defer",function(a){var b=this;setTimeout(function(){b.next(!0)},a.shift())}),d("onError",function(a,b){var c=this;this.error=function(d){c.halt=!0;for(var e=0;e<b;e++)a[e].call(c,d)}})})(this);var head=document.getElementsByTagName("head")[0]||document.documentElement;addMethod("load",function(a,b){for(var c=[],d=0;d<b;d++)(function(b){c.push(asyncLoadScript(a[b]))})(d);this.call("run",c)})

// modified version of https://github.com/shramov/leaflet-plugins. Also
// contains the default Ingress map style.
var LLGMAPS = 'http://breunigs.github.com/ingress-intel-total-conversion/dist/leaflet_google.js';
var JQUERY = 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js';
var LEAFLET = 'http://cdn.leafletjs.com/leaflet-0.5/leaflet.js';
var AUTOLINK = 'http://breunigs.github.com/ingress-intel-total-conversion/dist/autolink.js';

// after all scripts have loaded, boot the actual app
load(JQUERY, LEAFLET, AUTOLINK).then(LLGMAPS).onError(function (err) {
  alert('Could not all resources, the script likely won’t work.\n\nIf this happend the first time for you, it’s probably a temporary issue. Just wait a bit and try again.\n\nIf you installed the script for the first time and this happens:\n– try disabling NoScript if you have it installed\n– press CTRL+SHIFT+K in Firefox or CTRL+SHIFT+I in Chrome/Opera and reload the page. Additional info may be available in the console.\n– Open an issue at https://github.com/breunigs/ingress-intel-total-conversion/issues');
}).thenRun(boot);
<commit_msg>another typo<commit_after>

// SETUP /////////////////////////////////////////////////////////////
// these functions set up specific areas after the boot function
// created a basic framework. All of these functions should only ever
// be run once.

window.setupLargeImagePreview = function() {
  $('#portaldetails').on('click', '.imgpreview img', function() {
    var ex = $('#largepreview');
    if(ex.length > 0) {
      ex.remove();
      return;
    }
    var img = $(this).parent().html();
    var w = $(this)[0].naturalWidth/2;
    var h = $(this)[0].naturalHeight/2;
    var c = $('#portaldetails').attr('class');
    $('body').append(
      '
' + img + '
'
    );
    $('#largepreview').click(function() { $(this).remove() });
    $('#largepreview img').attr('title', '');
  });
}

window.setupStyles = function() {
  $('head').append('');
}

window.setupMap = function() {
  $('#map').text('');

  var osmOpt = {attribution: 'Map data © OpenStreetMap contributors', maxZoom: 18};
  var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmOpt);

  var cmOpt = {attribution: 'Map data © OpenStreetMap contributors, Imagery © CloudMade', maxZoom: 18};
  var cmMin = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/22677/256/{z}/{x}/{y}.png', cmOpt);
  var cmMid = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/999/256/{z}/{x}/{y}.png', cmOpt);

  var views = [cmMid, cmMin, osm, new L.Google('INGRESS'), new L.Google('ROADMAP'),
               new L.Google('SATELLITE'), new L.Google('HYBRID')];

  window.map = new L.Map('map', $.extend(getPosition(),
    {zoomControl: !(localStorage['iitc.zoom.buttons'] === 'false')}
  ));

  try {
    map.addLayer(views[readCookie('ingress.intelmap.type')]);
  } catch(e) { map.addLayer(views[0]); }

  var addLayers = {};

  portalsLayers = [];
  for(var i = 0; i <= 8; i++) {
    portalsLayers[i] = L.layerGroup([]);
    map.addLayer(portalsLayers[i]);
    var t = (i === 0 ? 'Unclaimed' : 'Level ' + i) + ' Portals';
    addLayers[t] = portalsLayers[i];
  }

  fieldsLayer = L.layerGroup([]);
  map.addLayer(fieldsLayer, true);
  addLayers['Fields'] = fieldsLayer;

  linksLayer = L.layerGroup([]);
  map.addLayer(linksLayer, true);
  addLayers['Links'] = linksLayer;

  map.addControl(new L.Control.Layers({
    'OSM Cloudmade Midnight': views[0],
    'OSM Cloudmade Minimal': views[1],
    'OSM Mapnik': views[2],
    'Google Roads Ingress Style': views[3],
    'Google Roads':  views[4],
    'Google Satellite':  views[5],
    'Google Hybrid':  views[6]
    }, addLayers));
  map.attributionControl.setPrefix('');
  // listen for changes and store them in cookies
  map.on('moveend', window.storeMapPosition);
  map.on('zoomend', function() {
    window.storeMapPosition;

    // remove all resonators if zoom out to < RESONATOR_DISPLAY_ZOOM_LEVEL
    if(isResonatorsShow()) return;
    for(var i = 1; i < portalsLayers.length; i++) {
      portalsLayers[i].eachLayer(function(item) {
        var itemGuid = item.options.guid;
        // check if 'item' is a resonator
        if(getTypeByGuid(itemGuid) != TYPE_RESONATOR) return true;
        portalsLayers[i].removeLayer(item);
      });
    }

    console.log('Remove all resonators');
  });
  $("[name='leaflet-base-layers']").change(function () {
    writeCookie('ingress.intelmap.type', $(this).parent().index());
  });

  // map update status handling
  map.on('movestart zoomstart', function() { window.mapRunsUserAction = true });
  map.on('moveend zoomend', function() { window.mapRunsUserAction = false });

  // update map hooks
  map.on('movestart zoomstart', window.requests.abort);
  map.on('moveend zoomend', function() { window.startRefreshTimeout(500) });

  // run once on init
  window.requestData();
  window.startRefreshTimeout();

  window.addResumeFunction(window.requestData);
  window.requests.addRefreshFunction(window.requestData);
};

// renders player details into the website. Since the player info is
// included as inline script in the original site, the data is static
// and cannot be updated.
window.setupPlayerStat = function() {
  var level;
  var ap = parseInt(PLAYER.ap);
  for(level = 0; level < MIN_AP_FOR_LEVEL.length; level++) {
    if(ap < MIN_AP_FOR_LEVEL[level]) break;
  }

  var thisLvlAp = MIN_AP_FOR_LEVEL[level-1];
  var nextLvlAp = MIN_AP_FOR_LEVEL[level] || ap;
  var lvlUpAp = digits(nextLvlAp-ap);
  var lvlApProg = Math.round((ap-thisLvlAp)/(nextLvlAp-thisLvlAp)*100);

  var xmMax = MAX_XM_PER_LEVEL[level];
  var xmRatio = Math.round(PLAYER.energy/xmMax*100);

  var cls = PLAYER.team === 'ALIENS' ? 'enl' : 'res';

  var t = 'Level:\t\t' + level + '\n'
        + 'XM:\t\t\t' + PLAYER.energy + ' / ' + xmMax + '\n'
        + 'AP:\t\t\t' + digits(ap) + '\n'
        + (level < 8 ? 'level up in:\t' + lvlUpAp + ' AP' : 'Congrats! (neeeeerd)')
        + '\n\Invites:\t\t'+PLAYER.available_invites;
        + '\n\nNote: your player stats can only be updated by a full reload (F5)';

  $('#playerstat').html(''
    + '
'+level+' '
    + ''+PLAYER.nickname+''
    + '
'
    + 'XM: '+xmRatio+'%'
    + '' + (level < 8 ? 'level: '+lvlApProg+'%' : 'max level') + ''
    + '
'
    + '
'
  );
}

window.setupSidebarToggle = function() {
  $('#sidebartoggle').on('click', function() {
    var toggle = $('#sidebartoggle');
    var sidebar = $('#sidebar');
    if(sidebar.is(':visible')) {
      sidebar.hide();
      $('.leaflet-right').css('margin-right','0');
      toggle.html('');
      toggle.css('right', '0');
    } else {
      sidebar.show();
      $('.leaflet-right').css('margin-right', SIDEBAR_WIDTH+1+'px');
      toggle.html('');
      toggle.css('right', SIDEBAR_WIDTH+1+'px');
    }
  });
}

// BOOTING ///////////////////////////////////////////////////////////

function boot() {
  console.log('loading done, booting');
  window.setupStyles();
  window.setupMap();
  window.setupGeosearch();
  window.setupRedeem();
  window.setupLargeImagePreview();
  window.setupSidebarToggle();
  window.updateGameScore();
  window.setupPlayerStat();
  window.chat.setup();
  // read here ONCE, so the URL is only evaluated one time after the
  // necessary data has been loaded.
  urlPortal = getURLParam('pguid');

  // load only once
  var n = window.PLAYER['nickname'];
  window.PLAYER['nickMatcher'] = new RegExp('\\b('+n+')\\b', 'ig');

  $('#sidebar').show();

  if(window.bootPlugins)
    $.each(window.bootPlugins, function(ind, ref) { ref(); });

  window.iitcLoaded = true;
}

// this is the minified load.js script that allows us to easily load
// further javascript files async as well as in order.
// https://github.com/chriso/load.js
// Copyright (c) 2010 Chris O'Hara <cohara87@gmail.com>. MIT Licensed
function asyncLoadScript(a){return function(b,c){var d=document.createElement("script");d.type="text/javascript",d.src=a,d.onload=b,d.onerror=c,d.onreadystatechange=function(){var a=this.readyState;if(a==="loaded"||a==="complete")d.onreadystatechange=null,b()},head.insertBefore(d,head.firstChild)}}(function(a){a=a||{};var b={},c,d;c=function(a,d,e){var f=a.halt=!1;a.error=function(a){throw a},a.next=function(c){c&&(f=!1);if(!a.halt&&d&&d.length){var e=d.shift(),g=e.shift();f=!0;try{b[g].apply(a,[e,e.length,g])}catch(h){a.error(h)}}return a};for(var g in b){if(typeof a[g]=="function")continue;(function(e){a[e]=function(){var g=Array.prototype.slice.call(arguments);if(e==="onError"){if(d)return b.onError.apply(a,[g,g.length]),a;var h={};return b.onError.apply(h,[g,g.length]),c(h,null,"onError")}return g.unshift(e),d?(a.then=a[e],d.push(g),f?a:a.next()):c({},[g],e)}})(g)}return e&&(a.then=a[e]),a.call=function(b,c){c.unshift(b),d.unshift(c),a.next(!0)},a.next()},d=a.addMethod=function(d){var e=Array.prototype.slice.call(arguments),f=e.pop();for(var g=0,h=e.length;g<h;g++)typeof e[g]=="string"&&(b[e[g]]=f);--h||(b["then"+d.substr(0,1).toUpperCase()+d.substr(1)]=f),c(a)},d("chain",function(a){var b=this,c=function(){if(!b.halt){if(!a.length)return b.next(!0);try{null!=a.shift().call(b,c,b.error)&&c()}catch(d){b.error(d)}}};c()}),d("run",function(a,b){var c=this,d=function(){c.halt||--b||c.next(!0)},e=function(a){c.error(a)};for(var f=0,g=b;!c.halt&&f<g;f++)null!=a[f].call(c,d,e)&&d()}),d("defer",function(a){var b=this;setTimeout(function(){b.next(!0)},a.shift())}),d("onError",function(a,b){var c=this;this.error=function(d){c.halt=!0;for(var e=0;e<b;e++)a[e].call(c,d)}})})(this);var head=document.getElementsByTagName("head")[0]||document.documentElement;addMethod("load",function(a,b){for(var c=[],d=0;d<b;d++)(function(b){c.push(asyncLoadScript(a[b]))})(d);this.call("run",c)})

// modified version of https://github.com/shramov/leaflet-plugins. Also
// contains the default Ingress map style.
var LLGMAPS = 'http://breunigs.github.com/ingress-intel-total-conversion/dist/leaflet_google.js';
var JQUERY = 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js';
var LEAFLET = 'http://cdn.leafletjs.com/leaflet-0.5/leaflet.js';
var AUTOLINK = 'http://breunigs.github.com/ingress-intel-total-conversion/dist/autolink.js';

// after all scripts have loaded, boot the actual app
load(JQUERY, LEAFLET, AUTOLINK).then(LLGMAPS).onError(function (err) {
  alert('Could not all resources, the script likely won’t work.\n\nIf this happend the first time for you, it’s probably a temporary issue. Just wait a bit and try again.\n\nIf you installed the script for the first time and this happens:\n– try disabling NoScript if you have it installed\n– press CTRL+SHIFT+K in Firefox or CTRL+SHIFT+I in Chrome/Opera and reload the page. Additional info may be available in the console.\n– Open an issue at https://github.com/breunigs/ingress-intel-total-conversion/issues');
}).thenRun(boot);
<|endoftext|>


<commit_before>"use strict";

const express = require('express');
const router = express.Router();

//twilio variables
const accountSid = process.env.TWILIO_KEY;
const authToken = process.env.TWILIO_SECRET;
const client = require('twilio')(accountSid, authToken);
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const myNumber = process.env.VERIFIED_NUMBER;
const twiNumber = process.env.TWILIO_NUMBER;

module.exports = (knex) => {

  //helper functions
  function respond(message, res, callback) {
    //generate twiml message and continue code after message is sent
    var twiml = new MessagingResponse();
    twiml.message(message);
    res.writeHead(200, {
      'Content-Type': 'text/xml'
    });
    callback(twiml.toString);
  }

  router.post('/', function(req, res) {
    knex('order').select('status').where('phone', '=', req.body.From).asCallback((err, row) => {
      if (err) console.error(err);
      var status = row[0].status;
      if (status === 'ordered') {
        if (req.body.Body.toLowerCase() === 'confirm') {
          knex('order')
            .where('phone', '=', req.body.From)
            .update({
              status: 'confirmed',
            }).asCallback((err) => {
            if (err) console.error(err);
            respond('Thanks, your order is now being processed\ntext "receipt" to review the order', res, function(sms) {
              knex.select('receipt').from('order')
                .where('phone', '=', req.body.From)
                .asCallback((err, row) => {
                  if (err) console.error(err);
                  client.messages.create({
                    to: myNumber,
                    from: twiNumber,
                    body: `Your order has been placed ${req.body.name}: ${req.body.receipt} text "confirm" to start the order or text "2" to undo`
                  }).then((message) => {
                    console.log(message.sid);
                    res.end(sms)
                  });
                });
            });
          });
        } else if (req.body.Body.toLowerCase() === '2') {
          respond('Your order has been cancelled', function() {
            ;
            knex('order').where('phone', '=', req.body.From).del();
          });
        }
      } else if (status === 'confirmed') {
        if (req.body.Body.toLowerCase() === 'receipt') {
          knex('order').select('receipt').where('phone', '=', req.body.From).asCallback((err, row) => {
            if (err) console.error(err);
            var receipt = row[0].receipt;
            respond(`Here is your current order: ${receipt}`, res, function() {
              knex('order')
                .where('phone', '=', req.body.From)
                .update({
                  status: 'confirmed',
                }).asCallback((err) => {
                if (err) console.error(err);
              });
            });
          });
        } else if (req.body.Body.toLowerCase() === '2' && status !== 'processed') {
          respond('Your order has been cancelled', res, function() {
            knex('order')
              .where('phone', '=', req.body.From)
              .del().asCallback((err) => {
              if (err) console.error(err);
            });
          });
        } else if (req.body.Body.toLowerCase() === 'ready') {
          respond('Your food is ready for pickup.', res, function() {
            knex('order')
              .where('phone', '=', req.body.From)
              .update({
                status: 'ready',
              }).asCallback((err) => {
              if (err) console.error(err);
            });
          });
        } else if (req.body.Body.toLowerCase() === 'done' && status === 'ready') {
          respond('Thanks for ordering at Zuckerburgers!', res, function() {
            knex('order')
              .where('phone', '=', req.body.From)
              .update({
                status: 'finished',
              }).asCallback((err) => {
              if (err) console.error(err);
            });
          });
        }
      }
    });
  });
  router.post("/order", (req, res) => {
    client.messages.create({
      to: myNumber,
      from: twiNumber,
      body: `Your order has been placed ${req.body.name}: ${req.body.receipt} text "confirm" to start the order or text "2" to undo`
    }).then((message) => {
      console.log(message.sid);
      knex('order').insert({
        name: req.body.name || 'kyle',
        phone: myNumber,
        receipt: req.body.receipt,
        status: 'ordered'
      }).asCallback((err, row) => {
        if (err) console.error(err);
      });
    });
  });
  return router;
}
<commit_msg>fixed mtypos ares end<commit_after>"use strict";

const express = require('express');
const router = express.Router();

//twilio variables
const accountSid = process.env.TWILIO_KEY;
const authToken = process.env.TWILIO_SECRET;
const client = require('twilio')(accountSid, authToken);
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const myNumber = process.env.VERIFIED_NUMBER;
const twiNumber = process.env.TWILIO_NUMBER;

module.exports = (knex) => {

  //helper functions
  function respond(message, res) {
    //generate twiml message and continue code after message is sent
    var twiml = new MessagingResponse();
    twiml.message(message);
    res.writeHead(200, {
      'Content-Type': 'text/xml'
    });
    return twiml.toString();
  }

  router.post('/', function(req, res) {
    knex('order').select('status').where('phone', '=', req.body.From).asCallback((err, row) => {
      if (err) console.error(err);
      var status = row[0].status;
      if (status === 'ordered') {
        if (req.body.Body.toLowerCase() === 'confirm') {
          knex('order')
            .where('phone', '=', req.body.From)
            .update({
              status: 'confirmed',
            }).asCallback((err) => {
            if (err) console.error(err);
            res.end(respond('Thanks, your order is now being processed\ntext "receipt" to review the order', res))
            knex.select('receipt').from('order')
              .where('phone', '=', req.body.From)
              .asCallback((err, row) => {
                if (err) console.error(err);
                client.messages.create({
                  to: myNumber,
                  from: twiNumber,
                  body: `Your order has been placed ${req.body.name}: ${req.body.receipt} text "confirm" to start the order or text "2" to undo`
                }).then((message) => {
                  console.log(message.sid);
                });
              });
          });
        } else if (req.body.Body.toLowerCase() === '2') {
          knex('order').where('phone', '=', req.body.From).del();
          res.end(respond('Your order has been cancelled', res));
        }
      } else if (status === 'confirmed') {
        if (req.body.Body.toLowerCase() === 'receipt') {
          knex('order').select('receipt').where('phone', '=', req.body.From).asCallback((err, row) => {
            if (err) console.error(err);
            var receipt = row[0].receipt;
            knex('order')
              .where('phone', '=', req.body.From)
              .update({
                status: 'confirmed',
              }).asCallback((err) => {
              if (err) console.error(err);
              res.end(respond(`Here is your current order: ${receipt}`, res));
            });
          });
        }
      } else if (req.body.Body.toLowerCase() === '2' && status !== 'processed') {
        res.end(respond('Your order has been cancelled', res))
        knex('order')
          .where('phone', '=', req.body.From)
          .del().asCallback((err) => {
          if (err) console.error(err);
        });
      } else if (req.body.Body.toLowerCase() === 'ready') {
        knex('order')
          .where('phone', '=', req.body.From)
          .update({
            status: 'ready',
          }).asCallback((err) => {
          if (err) console.error(err);
          res.end(respond('Your food is ready for pickup.', res));
        });
      } else if (req.body.Body.toLowerCase() === 'done' && status === 'ready') {
        knex('order')
          .where('phone', '=', req.body.From)
          .update({
            status: 'finished',
          }).asCallback((err) => {
          if (err) console.error(err);
          res.end(respond('Thanks for ordering at Zuckerburgers!', res));
        });
      }
    });
  });
  router.post("/order", (req, res) => {
    client.messages.create({
      to: myNumber,
      from: twiNumber,
      body: `Your order has been placed ${req.body.name}: ${req.body.receipt} text "confirm" to start the order or text "2" to undo`
    }).then((message) => {
      console.log(message.sid);
      knex('order').insert({
        name: req.body.name || 'kyle',
        phone: myNumber,
        receipt: req.body.receipt,
        status: 'ordered'
      }).asCallback((err, row) => {
        if (err) console.error(err);
      });
    });
  });
  return router;
}
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express'),
    Buffer = require('buffer').Buffer;

module.exports = {
    'test #send()': function(assert){
        var app = express.createServer();

        app.get('/html', function(req, res){
            res.send('
test
', { 'Content-Language': 'en' });
        });

        app.get('/json', function(req, res){
            res.header('X-Foo', 'bar');
            res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);
        });

        app.get('/text', function(req, res){
            res.header('X-Foo', 'bar');
            res.contentType('.txt');
            res.send('wahoo');
        });

        app.get('/status', function(req, res){
            res.send(404);
        });

        app.get('/error', function(req, res){
            res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);
        });

        app.get('/buffer', function(req, res){
            res.send(new Buffer('wahoo!'));
        });

        app.get('/noargs', function(req, res, next){
            res.send();
        });

        assert.response(app,
            { url: '/html' },
            { body: '
test
', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});
        assert.response(app,
            { url: '/json' },
            { body: '{"foo":"bar"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});
        assert.response(app,
            { url: '/text' },
            { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});
        assert.response(app,
            { url: '/status' },
            { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});
        assert.response(app,
            { url: '/error' },
            { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});
        assert.response(app,
            { url: '/buffer' },
            { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});
        assert.response(app,
            { url: '/noargs' },
            { status: 204 }, function(res){
                assert.equal(undefined, res.headers['content-type']);
                assert.equal(undefined, res.headers['content-length']);
            });
    },

    'test #contentType()': function(assert){
        var app = express.createServer();

        app.get('/html', function(req, res){
            res.contentType('index.html');
            res.writeHead(200, res.headers);
            res.end('
yay
');
        });

        assert.response(app,
            { url: '/html' },
            { body: '
yay
', headers: { 'Content-Type': 'text/html; charset=utf-8' }});
    },

    'test #attachment()': function(assert){
        var app = express.createServer();

        app.get('/style.css', function(req, res){
            res.attachment();
            res.send('some stylezzz');
        });

        app.get('/*', function(req, res){
            res.attachment(req.params[0]);
            res.send('whatever');
        });

        assert.response(app,
            { url: '/javascripts/jquery.js' },
            { body: 'whatever', headers: { 'Content-Disposition': 'attachment; filename="jquery.js"' }});
        assert.response(app,
            { url: '/style.css' },
            { body: 'some stylezzz', headers: { 'Content-Disposition': 'attachment' }});
    },

    'test #redirect()': function(assert){
        var app = express.createServer(),
            app2 = express.createServer();

        app2.set('home', '/blog');

        app2.redirect('google', 'http://google.com');

        app2.redirect('blog', function(req, res){
            return req.params.id
                ? '/user/' + req.params.id + '/blog'
                : null;
        });

        app.get('/', function(req, res){
            res.redirect('http://google.com', 301);
        });

        app.get('/back', function(req, res){
            res.redirect('back');
        });

        app.get('/home', function(req, res){
            res.redirect('home');
        });

        app2.get('/', function(req, res){
            res.redirect('http://google.com', 301);
        });

        app2.get('/back', function(req, res){
            res.redirect('back');
        });

        app2.get('/home', function(req, res){
            res.redirect('home');
        });

        app2.get('/google', function(req, res){
            res.redirect('google');
        });

        app2.get('/user/:id', function(req, res){
            res.header('X-Foo', 'bar');
            res.redirect('blog');
        });

        assert.response(app,
            { url: '/' },
            { body: 'Redirecting to http://google.com', status: 301, headers: { Location: 'http://google.com' }});
        assert.response(app,
            { url: '/back' },
            { body: 'Redirecting to /', status: 302, headers: { Location: '/', 'Content-Type': 'text/plain' }});
        assert.response(app,
            { url: '/back', headers: { Referer: '/foo' }},
            { body: 'Redirecting to /foo', status: 302, headers: { Location: '/foo' }});
        assert.response(app,
            { url: '/back', headers: { Referrer: '/foo' }},
            { body: 'Redirecting to /foo', status: 302, headers: { Location: '/foo' }});
        assert.response(app,
            { url: '/home' },
            { body: 'Redirecting to /', status: 302, headers: { Location: '/' }});

        assert.response(app2,
            { url: '/' },
            { body: 'Redirecting to http://google.com', status: 301, headers: { Location: 'http://google.com' }});
        assert.response(app2,
            { url: '/back' },
            { body: 'Redirecting to /blog', status: 302, headers: { Location: '/blog' }});
        assert.response(app2,
            { url: '/home' },
            { body: 'Redirecting to /blog', status: 302, headers: { Location: '/blog' }});
        assert.response(app2,
            { url: '/google' },
            { body: 'Redirecting to http://google.com', headers: { Location: 'http://google.com' }});
        assert.response(app2,
            { url: '/user/12' },
            { body: 'Redirecting to /user/12/blog', headers: { Location: '/user/12/blog', 'X-Foo': 'bar' }});
    },

    'test #sendfile()': function(assert){
        var app = express.createServer();

        app.get('/*', function(req, res, next){
            var file = req.params[0],
                filePath = __dirname + '/fixtures/' + file;
            res.sendfile(filePath, function(err, path){
                assert.equal(path, filePath);
                if (err) next(err);
            });
        });

        app.use(express.errorHandler());

        assert.response(app,
            { url: '/user.json' },
            { body: '{"name":"tj"}', status: 200, headers: { 'Content-Type': 'application/json' }});
        assert.response(app,
            { url: '/hello.haml' },
            { body: '%p Hello World', status: 200, headers: { 'Content-Type': 'application/octet-stream' }});
        assert.response(app,
            { url: '/doesNotExist' },
            { body: 'Internal Server Error', status: 500 });
        assert.response(app,
            { url: '/partials' },
            { body: 'Internal Server Error', status: 500 });
    },

    'test #download()': function(assert){
        var app = express.createServer();

        app.get('/json', function(req, res, next){
            var filePath = __dirname + '/fixtures/user.json';
            res.download(filePath, 'account.json', function(err, path){
                assert.equal(filePath, path);
            });
        });

        app.get('/*', function(req, res, next){
            res.download(__dirname + '/fixtures/' + req.params[0]);
        });

        assert.response(app,
            { url: '/user.json' },
            { body: '{"name":"tj"}', status: 200, headers: {
                'Content-Type': 'application/json',
                'Content-Disposition': 'attachment; filename="user.json"'
            }});

        assert.response(app,
            { url: '/json' },
            { body: '{"name":"tj"}', status: 200, headers: {
                'Content-Type': 'application/json',
                'Content-Disposition': 'attachment; filename="account.json"'
            }});
    },

    'test #cookie()': function(assert){
        var app = express.createServer();

        app.get('/', function(req, res){
            res.cookie('rememberme', 'yes', { expires: new Date(1), httpOnly: true });
            res.redirect('/');
        });

        assert.response(app,
            { url: '/' },
            function(res){
                //assert.length(res.headers['set-cookie'], 1);
                assert.equal(
                    'rememberme=yes; expires=Thu, 01 Jan 1970 00:00:00 GMT; httpOnly',
                    res.headers['set-cookie'][0]);
            });
    }
};<commit_msg>Added test for res.clearCookie()<commit_after>
/**
 * Module dependencies.
 */

var express = require('express'),
    Buffer = require('buffer').Buffer;

module.exports = {
    'test #send()': function(assert){
        var app = express.createServer();

        app.get('/html', function(req, res){
            res.send('
test
', { 'Content-Language': 'en' });
        });

        app.get('/json', function(req, res){
            res.header('X-Foo', 'bar');
            res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);
        });

        app.get('/text', function(req, res){
            res.header('X-Foo', 'bar');
            res.contentType('.txt');
            res.send('wahoo');
        });

        app.get('/status', function(req, res){
            res.send(404);
        });

        app.get('/error', function(req, res){
            res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);
        });

        app.get('/buffer', function(req, res){
            res.send(new Buffer('wahoo!'));
        });

        app.get('/noargs', function(req, res, next){
            res.send();
        });

        assert.response(app,
            { url: '/html' },
            { body: '
test
', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});
        assert.response(app,
            { url: '/json' },
            { body: '{"foo":"bar"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});
        assert.response(app,
            { url: '/text' },
            { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});
        assert.response(app,
            { url: '/status' },
            { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});
        assert.response(app,
            { url: '/error' },
            { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});
        assert.response(app,
            { url: '/buffer' },
            { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});
        assert.response(app,
            { url: '/noargs' },
            { status: 204 }, function(res){
                assert.equal(undefined, res.headers['content-type']);
                assert.equal(undefined, res.headers['content-length']);
            });
    },

    'test #contentType()': function(assert){
        var app = express.createServer();

        app.get('/html', function(req, res){
            res.contentType('index.html');
            res.writeHead(200, res.headers);
            res.end('
yay
');
        });

        assert.response(app,
            { url: '/html' },
            { body: '
yay
', headers: { 'Content-Type': 'text/html; charset=utf-8' }});
    },

    'test #attachment()': function(assert){
        var app = express.createServer();

        app.get('/style.css', function(req, res){
            res.attachment();
            res.send('some stylezzz');
        });

        app.get('/*', function(req, res){
            res.attachment(req.params[0]);
            res.send('whatever');
        });

        assert.response(app,
            { url: '/javascripts/jquery.js' },
            { body: 'whatever', headers: { 'Content-Disposition': 'attachment; filename="jquery.js"' }});
        assert.response(app,
            { url: '/style.css' },
            { body: 'some stylezzz', headers: { 'Content-Disposition': 'attachment' }});
    },

    'test #redirect()': function(assert){
        var app = express.createServer(),
            app2 = express.createServer();

        app2.set('home', '/blog');

        app2.redirect('google', 'http://google.com');

        app2.redirect('blog', function(req, res){
            return req.params.id
                ? '/user/' + req.params.id + '/blog'
                : null;
        });

        app.get('/', function(req, res){
            res.redirect('http://google.com', 301);
        });

        app.get('/back', function(req, res){
            res.redirect('back');
        });

        app.get('/home', function(req, res){
            res.redirect('home');
        });

        app2.get('/', function(req, res){
            res.redirect('http://google.com', 301);
        });

        app2.get('/back', function(req, res){
            res.redirect('back');
        });

        app2.get('/home', function(req, res){
            res.redirect('home');
        });

        app2.get('/google', function(req, res){
            res.redirect('google');
        });

        app2.get('/user/:id', function(req, res){
            res.header('X-Foo', 'bar');
            res.redirect('blog');
        });

        assert.response(app,
            { url: '/' },
            { body: 'Redirecting to http://google.com', status: 301, headers: { Location: 'http://google.com' }});
        assert.response(app,
            { url: '/back' },
            { body: 'Redirecting to /', status: 302, headers: { Location: '/', 'Content-Type': 'text/plain' }});
        assert.response(app,
            { url: '/back', headers: { Referer: '/foo' }},
            { body: 'Redirecting to /foo', status: 302, headers: { Location: '/foo' }});
        assert.response(app,
            { url: '/back', headers: { Referrer: '/foo' }},
            { body: 'Redirecting to /foo', status: 302, headers: { Location: '/foo' }});
        assert.response(app,
            { url: '/home' },
            { body: 'Redirecting to /', status: 302, headers: { Location: '/' }});

        assert.response(app2,
            { url: '/' },
            { body: 'Redirecting to http://google.com', status: 301, headers: { Location: 'http://google.com' }});
        assert.response(app2,
            { url: '/back' },
            { body: 'Redirecting to /blog', status: 302, headers: { Location: '/blog' }});
        assert.response(app2,
            { url: '/home' },
            { body: 'Redirecting to /blog', status: 302, headers: { Location: '/blog' }});
        assert.response(app2,
            { url: '/google' },
            { body: 'Redirecting to http://google.com', headers: { Location: 'http://google.com' }});
        assert.response(app2,
            { url: '/user/12' },
            { body: 'Redirecting to /user/12/blog', headers: { Location: '/user/12/blog', 'X-Foo': 'bar' }});
    },

    'test #sendfile()': function(assert){
        var app = express.createServer();

        app.get('/*', function(req, res, next){
            var file = req.params[0],
                filePath = __dirname + '/fixtures/' + file;
            res.sendfile(filePath, function(err, path){
                assert.equal(path, filePath);
                if (err) next(err);
            });
        });

        app.use(express.errorHandler());

        assert.response(app,
            { url: '/user.json' },
            { body: '{"name":"tj"}', status: 200, headers: { 'Content-Type': 'application/json' }});
        assert.response(app,
            { url: '/hello.haml' },
            { body: '%p Hello World', status: 200, headers: { 'Content-Type': 'application/octet-stream' }});
        assert.response(app,
            { url: '/doesNotExist' },
            { body: 'Internal Server Error', status: 500 });
        assert.response(app,
            { url: '/partials' },
            { body: 'Internal Server Error', status: 500 });
    },

    'test #download()': function(assert){
        var app = express.createServer();

        app.get('/json', function(req, res, next){
            var filePath = __dirname + '/fixtures/user.json';
            res.download(filePath, 'account.json', function(err, path){
                assert.equal(filePath, path);
            });
        });

        app.get('/*', function(req, res, next){
            res.download(__dirname + '/fixtures/' + req.params[0]);
        });

        assert.response(app,
            { url: '/user.json' },
            { body: '{"name":"tj"}', status: 200, headers: {
                'Content-Type': 'application/json',
                'Content-Disposition': 'attachment; filename="user.json"'
            }});

        assert.response(app,
            { url: '/json' },
            { body: '{"name":"tj"}', status: 200, headers: {
                'Content-Type': 'application/json',
                'Content-Disposition': 'attachment; filename="account.json"'
            }});
    },

    'test #cookie()': function(assert){
        var app = express.createServer();

        app.get('/', function(req, res){
            res.cookie('rememberme', 'yes', { expires: new Date(1), httpOnly: true });
            res.redirect('/');
        });

        assert.response(app,
            { url: '/' },
            function(res){
                //assert.length(res.headers['set-cookie'], 1);
                assert.equal(
                    'rememberme=yes; expires=Thu, 01 Jan 1970 00:00:00 GMT; httpOnly',
                    res.headers['set-cookie'][0]);
            });
    },

    'test #clearCookie()': function(assert){
        var app = express.createServer();

        app.get('/', function(req, res){
            res.clearCookie('rememberme');
            res.redirect('/');
        });

        assert.response(app,
            { url: '/' },
            function(res){
                //assert.length(res.headers['set-cookie'], 1);
                assert.equal(
                    'rememberme=; expires=Thu, 01 Jan 1970 00:00:00 GMT',
                    res.headers['set-cookie'][0]);
            });
    }
};<|endoftext|>


<commit_before>'use strict';
const url = require('url');
const qs = require('querystring');

const MongoClient = require('../../lib/mongo_client');
const TopologyType = require('../../lib/core/sdam/topology_description').TopologyType;
const core = require('../../lib/core');

class NativeConfiguration {
  constructor(parsedURI, context) {
    this.topologyType = context.topologyType;
    this.options = Object.assign(
      {
        host: parsedURI.hosts[0] ? parsedURI.hosts[0].host : 'localhost',
        port: parsedURI.hosts[0] ? parsedURI.hosts[0].port : 27017,
        db: parsedURI.auth && parsedURI.auth.db ? parsedURI.auth.db : 'integration_tests'
      },
      parsedURI.options
    );

    this.mongo = this.require = require('../..');
    this.writeConcern = function() {
      return { w: 1 };
    };
  }

  get host() {
    return this.options.host;
  }

  get port() {
    return this.options.port;
  }

  set db(_db) {
    this.options.db = _db;
  }

  get db() {
    return this.options.db;
  }

  // legacy accessors, consider for removal
  get replicasetName() {
    return this.options.replicaSet;
  }

  get setName() {
    return this.options.replicaSet;
  }

  usingUnifiedTopology() {
    return !!process.env.MONGODB_UNIFIED_TOPOLOGY;
  }

  newClient(dbOptions, serverOptions) {
    if (typeof dbOptions === 'string') {
      return new MongoClient(
        dbOptions,
        this.usingUnifiedTopology()
          ? Object.assign({ useUnifiedTopology: true }, serverOptions)
          : serverOptions
      );
    }

    // support MongoClient contructor form (url, options) for `newClient`
    if (typeof dbOptions === 'string') {
      return new MongoClient(
        dbOptions,
        this.usingUnifiedTopology()
          ? Object.assign({ useUnifiedTopology: true }, serverOptions)
          : serverOptions
      );
    }

    dbOptions = dbOptions || {};
    serverOptions = Object.assign({}, { haInterval: 100 }, serverOptions);
    if (this.usingUnifiedTopology()) {
      serverOptions.useUnifiedTopology = true;
    }

    // // Set up the options
    // const keys = Object.keys(this.options);
    // if (keys.indexOf('sslOnNormalPorts') !== -1) {
    //   serverOptions.ssl = true;
    // }

    // Fall back
    let dbHost = (serverOptions && serverOptions.host) || this.options.host;
    const dbPort = (serverOptions && serverOptions.port) || this.options.port;
    if (dbHost.indexOf('.sock') !== -1) {
      dbHost = qs.escape(dbHost);
    }

    if (this.options.replicaSet) {
      Object.assign(dbOptions, { replicaSet: this.options.replicaSet, auto_reconnect: false });
    }

    const connectionString = url.format({
      protocol: 'mongodb',
      slashes: true,
      hostname: dbHost,
      port: dbPort,
      query: dbOptions,
      pathname: '/'
    });

    return new MongoClient(connectionString, serverOptions);
  }

  newTopology(host, port, options) {
    options = Object.assign({}, options);
    if (this.usingUnifiedTopology()) {
      return new core.Topology([{ host, port }], options);
    }

    if (this.topologyType === TopologyType.ReplicaSetWithPrimary) {
      options.poolSize = 1;
      options.autoReconnect = false;
      return new core.ReplSet([{ host, port }], options);
    }

    if (this.topologyType === TopologyType.Sharded) {
      return new core.Mongos([{ host, port }], options);
    }

    return core.Server(host, port, options);
  }

  url(username, password) {
    const query = {};
    if (this.options.replicaSet) {
      Object.assign(query, { replicaSet: this.options.replicaSet, auto_reconnect: false });
    }

    const urlObject = {
      protocol: 'mongodb',
      slashes: true,
      hostname: this.options.host,
      port: this.options.port,
      pathname: `/${this.options.db}`,
      query
    };

    if (username || password) {
      urlObject.auth = password == null ? username : `${username}:${password}`;
    }

    return url.format(urlObject);
  }

  writeConcernMax() {
    if (this.topologyType !== TopologyType.Single) {
      return { w: 'majority', wtimeout: 30000 };
    }

    return { w: 1 };
  }

  // server37631Workaround() {
  //   console.log('[applying SERVER-37631 workaround]');
  //   const configServers = this.manager.configurationServers.managers;
  //   const proxies = this.manager.proxies;
  //   const configServersPromise = configServers.reduce((result, server) => {
  //     return result.then(() =>
  //       server.executeCommand('admin.$cmd', { refreshLogicalSessionCacheNow: 1 })
  //     );
  //   }, Promise.resolve());

  //   return configServersPromise.then(() => {
  //     return proxies.reduce((promise, proxy) => {
  //       return promise.then(() =>
  //         proxy.executeCommand('admin.$cmd', { refreshLogicalSessionCacheNow: 1 })
  //       );
  //     }, Promise.resolve());
  //   });
  // }
}

module.exports = NativeConfiguration;
<commit_msg>test: provide default host and port info for `newTopology` helper<commit_after>'use strict';
const url = require('url');
const qs = require('querystring');

const MongoClient = require('../../lib/mongo_client');
const TopologyType = require('../../lib/core/sdam/topology_description').TopologyType;
const core = require('../../lib/core');

class NativeConfiguration {
  constructor(parsedURI, context) {
    this.topologyType = context.topologyType;
    this.options = Object.assign(
      {
        host: parsedURI.hosts[0] ? parsedURI.hosts[0].host : 'localhost',
        port: parsedURI.hosts[0] ? parsedURI.hosts[0].port : 27017,
        db: parsedURI.auth && parsedURI.auth.db ? parsedURI.auth.db : 'integration_tests'
      },
      parsedURI.options
    );

    this.mongo = this.require = require('../..');
    this.writeConcern = function() {
      return { w: 1 };
    };
  }

  get host() {
    return this.options.host;
  }

  get port() {
    return this.options.port;
  }

  set db(_db) {
    this.options.db = _db;
  }

  get db() {
    return this.options.db;
  }

  // legacy accessors, consider for removal
  get replicasetName() {
    return this.options.replicaSet;
  }

  get setName() {
    return this.options.replicaSet;
  }

  usingUnifiedTopology() {
    return !!process.env.MONGODB_UNIFIED_TOPOLOGY;
  }

  newClient(dbOptions, serverOptions) {
    if (typeof dbOptions === 'string') {
      return new MongoClient(
        dbOptions,
        this.usingUnifiedTopology()
          ? Object.assign({ useUnifiedTopology: true }, serverOptions)
          : serverOptions
      );
    }

    // support MongoClient contructor form (url, options) for `newClient`
    if (typeof dbOptions === 'string') {
      return new MongoClient(
        dbOptions,
        this.usingUnifiedTopology()
          ? Object.assign({ useUnifiedTopology: true }, serverOptions)
          : serverOptions
      );
    }

    dbOptions = dbOptions || {};
    serverOptions = Object.assign({}, { haInterval: 100 }, serverOptions);
    if (this.usingUnifiedTopology()) {
      serverOptions.useUnifiedTopology = true;
    }

    // // Set up the options
    // const keys = Object.keys(this.options);
    // if (keys.indexOf('sslOnNormalPorts') !== -1) {
    //   serverOptions.ssl = true;
    // }

    // Fall back
    let dbHost = (serverOptions && serverOptions.host) || this.options.host;
    const dbPort = (serverOptions && serverOptions.port) || this.options.port;
    if (dbHost.indexOf('.sock') !== -1) {
      dbHost = qs.escape(dbHost);
    }

    if (this.options.replicaSet) {
      Object.assign(dbOptions, { replicaSet: this.options.replicaSet, auto_reconnect: false });
    }

    const connectionString = url.format({
      protocol: 'mongodb',
      slashes: true,
      hostname: dbHost,
      port: dbPort,
      query: dbOptions,
      pathname: '/'
    });

    return new MongoClient(connectionString, serverOptions);
  }

  newTopology(host, port, options) {
    options = Object.assign({}, options);
    host = host || this.options.host;
    port = port || this.options.port;

    if (this.usingUnifiedTopology()) {
      return new core.Topology([{ host, port }], options);
    }

    if (this.topologyType === TopologyType.ReplicaSetWithPrimary) {
      options.poolSize = 1;
      options.autoReconnect = false;
      return new core.ReplSet([{ host, port }], options);
    }

    if (this.topologyType === TopologyType.Sharded) {
      return new core.Mongos([{ host, port }], options);
    }

    return core.Server(host, port, options);
  }

  url(username, password) {
    const query = {};
    if (this.options.replicaSet) {
      Object.assign(query, { replicaSet: this.options.replicaSet, auto_reconnect: false });
    }

    const urlObject = {
      protocol: 'mongodb',
      slashes: true,
      hostname: this.options.host,
      port: this.options.port,
      pathname: `/${this.options.db}`,
      query
    };

    if (username || password) {
      urlObject.auth = password == null ? username : `${username}:${password}`;
    }

    return url.format(urlObject);
  }

  writeConcernMax() {
    if (this.topologyType !== TopologyType.Single) {
      return { w: 'majority', wtimeout: 30000 };
    }

    return { w: 1 };
  }

  // server37631Workaround() {
  //   console.log('[applying SERVER-37631 workaround]');
  //   const configServers = this.manager.configurationServers.managers;
  //   const proxies = this.manager.proxies;
  //   const configServersPromise = configServers.reduce((result, server) => {
  //     return result.then(() =>
  //       server.executeCommand('admin.$cmd', { refreshLogicalSessionCacheNow: 1 })
  //     );
  //   }, Promise.resolve());

  //   return configServersPromise.then(() => {
  //     return proxies.reduce((promise, proxy) => {
  //       return promise.then(() =>
  //         proxy.executeCommand('admin.$cmd', { refreshLogicalSessionCacheNow: 1 })
  //       );
  //     }, Promise.resolve());
  //   });
  // }
}

module.exports = NativeConfiguration;
<|endoftext|>


<commit_before>// routes/web.js
//
// Spurtin' out pumpy goodness all over your browser window
//
// Copyright 2011-2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var databank = require('databank'),
    url = require('url'),
    Step = require('step'),
    _ = require('underscore'),
    Activity = require('../lib/model/activity').Activity,
    User = require('../lib/model/user').User,
    mw = require('../lib/middleware'),
    he = require('../lib/httperror'),
    HTTPError = he.HTTPError,
    maybeAuth = mw.maybeAuth,
    reqUser = mw.reqUser,
    mustAuth = mw.mustAuth,
    sameUser = mw.sameUser,
    noUser = mw.noUser,
    checkCredentials = mw.checkCredentials,
    NoSuchThingError = databank.NoSuchThingError;

var addRoutes = function(app) {

    app.get('/', maybeAuth, showMain);

    app.post('/main/login', noUser, handleLogin);
    app.post('/main/logout', mustAuth, handleLogout);

    app.get('/main/settings', mustAuth, showSettings);

    app.get('/:nickname', maybeAuth, reqUser, showStream);
    app.get('/:nickname/inbox', mustAuth, reqUser, sameUser, showInbox);
    app.get('/:nickname/activity/:uuid', maybeAuth, reqUser, showActivity);
};

var showSettings = function(req, res, next) {
    res.render("settings", {title: "Settings"});
};

var showMain = function(req, res, next) {
    res.render("main", {title: "Welcome"});
};

var handleLogin = function(req, res, next) {
    Step(
        function () {
            checkCredentials(req.body.nickname, req.body.password, this);
        },
        function(err, user) {
            if (err) {
                if (err instanceof NoSuchThingError) {
                    next(new HTTPError("Not authorized", 403));
                } else {
                    throw err;
                }
            } else if (!user) {
                // done here
                next(new HTTPError("Not authorized", 403));
            } else {
                user.expand(this);
            }
        },
        function(err, user) {
            if (err) {
                next(err);
            } else {
                req.session.nickname = user.nickname;
                user.sanitize();
                res.json(user);
            }
        }
    );
};

var handleLogout = function(req, res, next) {
    delete req.session.nickname;
    res.json("OK");
};

var showActivity = function(req, res, next) {
    var uuid = req.params.uuid,
        user = req.user;

    Step(
        function() {
            Activity.search({'uuid': req.params.uuid}, this);
        },
        function(err, activities) {
            if (err) throw err;
            if (activities.length === 0) {
                throw new NoSuchThingError('activity', uuid);
            }
            if (activities.length > 1) {
                throw new Error("Too many activities with ID = " + req.params.uuid);
            }
            activities[0].expand(this);
        },
        function(err, activity) {
            if (err) {
                next(err);
            } else {
                res.render("activity", {title: "Welcome",
                                        user: req.remoteUser,
                                        activity: activity});
            }
        }
    );
};

var showInbox = function(req, res, next) {

    Step(
        function() {
            req.user.getInbox(0, 20, this);
        },
        function(err, activities) {
            if (err) {
                next(err);
            } else {
                res.render("inbox", {title: "Inbox",
                                     user: req.remoteUser,
                                     activities: activities});
            }
        }
    );
};

var showStream = function(req, res, next) {
    var pump = this;

    Step(
        function() {
            req.user.getStream(0, 20, this);
        },
        function(err, activities) {
            if (err) {
                next(err);
            } else {
                res.render("user", {title: req.user.nickname,
                                    user: req.remoteUser,
                                    actor: req.user.profile,
                                    activities: activities});
            }
        }
    );
};

var authenticate = function(req, res) {
    // XXX: I think there's an easier way to get this, but leave it for now.
    var parsedUrl = url.parse(req.originalUrl, true);
    res.render('authentication', {token: parsedUrl.query.oauth_token, error: false});
};

var authorize = function(err, req, res, authorized, authResults, application, user) {

    var self = this;

    if(err) {
        res.render('authentication', {token: authResults.token, error: "Incorrect username or password"});
    } else {
        res.render('authorization', {token: authResults.token,
                                     verifier: authResults.verifier,
                                     user: user,
                                     application: application});
    }
};

var authorizationFinished = function(err, req, res, result) {
    res.render('authorization-finished', {token: result.token,
                                          verifier: result.verifier});
};

exports.addRoutes = addRoutes;

// Need these for OAuth shenanigans

exports.authenticate = authenticate;
exports.authorize = authorize;
exports.authorizationFinished = authorizationFinished;
<commit_msg>Add a title to form<commit_after>// routes/web.js
//
// Spurtin' out pumpy goodness all over your browser window
//
// Copyright 2011-2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var databank = require('databank'),
    url = require('url'),
    Step = require('step'),
    _ = require('underscore'),
    Activity = require('../lib/model/activity').Activity,
    User = require('../lib/model/user').User,
    mw = require('../lib/middleware'),
    he = require('../lib/httperror'),
    HTTPError = he.HTTPError,
    maybeAuth = mw.maybeAuth,
    reqUser = mw.reqUser,
    mustAuth = mw.mustAuth,
    sameUser = mw.sameUser,
    noUser = mw.noUser,
    checkCredentials = mw.checkCredentials,
    NoSuchThingError = databank.NoSuchThingError;

var addRoutes = function(app) {

    app.get('/', maybeAuth, showMain);

    app.post('/main/login', noUser, handleLogin);
    app.post('/main/logout', mustAuth, handleLogout);

    app.get('/main/settings', mustAuth, showSettings);

    app.get('/:nickname', maybeAuth, reqUser, showStream);
    app.get('/:nickname/inbox', mustAuth, reqUser, sameUser, showInbox);
    app.get('/:nickname/activity/:uuid', maybeAuth, reqUser, showActivity);
};

var showSettings = function(req, res, next) {
    res.render("settings", {title: "Settings"});
};

var showMain = function(req, res, next) {
    res.render("main", {title: "Welcome"});
};

var handleLogin = function(req, res, next) {
    Step(
        function () {
            checkCredentials(req.body.nickname, req.body.password, this);
        },
        function(err, user) {
            if (err) {
                if (err instanceof NoSuchThingError) {
                    next(new HTTPError("Not authorized", 403));
                } else {
                    throw err;
                }
            } else if (!user) {
                // done here
                next(new HTTPError("Not authorized", 403));
            } else {
                user.expand(this);
            }
        },
        function(err, user) {
            if (err) {
                next(err);
            } else {
                req.session.nickname = user.nickname;
                user.sanitize();
                res.json(user);
            }
        }
    );
};

var handleLogout = function(req, res, next) {
    delete req.session.nickname;
    res.json("OK");
};

var showActivity = function(req, res, next) {
    var uuid = req.params.uuid,
        user = req.user;

    Step(
        function() {
            Activity.search({'uuid': req.params.uuid}, this);
        },
        function(err, activities) {
            if (err) throw err;
            if (activities.length === 0) {
                throw new NoSuchThingError('activity', uuid);
            }
            if (activities.length > 1) {
                throw new Error("Too many activities with ID = " + req.params.uuid);
            }
            activities[0].expand(this);
        },
        function(err, activity) {
            if (err) {
                next(err);
            } else {
                res.render("activity", {title: "Welcome",
                                        user: req.remoteUser,
                                        activity: activity});
            }
        }
    );
};

var showInbox = function(req, res, next) {

    Step(
        function() {
            req.user.getInbox(0, 20, this);
        },
        function(err, activities) {
            if (err) {
                next(err);
            } else {
                res.render("inbox", {title: "Inbox",
                                     user: req.remoteUser,
                                     activities: activities});
            }
        }
    );
};

var showStream = function(req, res, next) {
    var pump = this;

    Step(
        function() {
            req.user.getStream(0, 20, this);
        },
        function(err, activities) {
            if (err) {
                next(err);
            } else {
                res.render("user", {title: req.user.nickname,
                                    user: req.remoteUser,
                                    actor: req.user.profile,
                                    activities: activities});
            }
        }
    );
};

var authenticate = function(req, res) {
    // XXX: I think there's an easier way to get this, but leave it for now.
    var parsedUrl = url.parse(req.originalUrl, true);
    res.render('authentication', {title: "Authentication", token: parsedUrl.query.oauth_token, error: false});
};

var authorize = function(err, req, res, authorized, authResults, application, user) {

    var self = this;

    if(err) {
        res.render('authentication', {token: authResults.token, error: "Incorrect username or password"});
    } else {
        res.render('authorization', {token: authResults.token,
                                     verifier: authResults.verifier,
                                     user: user,
                                     application: application});
    }
};

var authorizationFinished = function(err, req, res, result) {
    res.render('authorization-finished', {token: result.token,
                                          verifier: result.verifier});
};

exports.addRoutes = addRoutes;

// Need these for OAuth shenanigans

exports.authenticate = authenticate;
exports.authorize = authorize;
exports.authorizationFinished = authorizationFinished;
<|endoftext|>


<commit_before>var assert = require('assert');

describe('webdriver.io page', function() {
    it('should have the right title - the fancy generator way', function () {
        browser.url('http://webdriver.io');
        var title = browser.getTitle();
        assert.equal(title, 'WebdriverIO - Selenium 2.0 javascript bindings for nodejs');
    });
});
<commit_msg>Removed unused files<commit_after><|endoftext|>


<commit_before>'use strict'

module.exports = function (protocol, key) {
  describe('client', function () {
    var Hub = require('../../lib')
    var server, receiver, receiver2

    it('can create a server and clients', function () {
      server = new Hub({
        key: 'server_client',
        adapter: {
          id: 'server_client',
          inject: protocol
        }
      })
      receiver = new Hub({
        key: 'receiver_client',
        adapter: {
          id: 'receiver_client',
          inject: protocol,
          [key]: {}
        }
      })
      receiver2 = new Hub({
        key: 'receiver_client_2',
        adapter: {
          id: 'receiver_client_2',
          inject: protocol,
          [key]: {}
        }
      })
      server.set({
        adapter: {
          [key]: {
            server: key === 'mock' ? 'server_client' : 6001
          }
        }
      })
    })

    it('receiver can connect to server', function (done) {
      receiver.adapter[key].once('connect', function () {
        server.get('clients', {}).once(function () {
          expect(server)
            .to.have.property('clients')
            .which.has.property('receiver_client')
            .which.has.property('platform')
        })
        done()
      })
      receiver.set({
        adapter: {
          [key]: key === 'mock' ? 'server_client' : 'ws://localhost:6001'
        }
      })
    })

    it('receiver has ip', function (done) {
      receiver.get('clients.receiver_client.ip', {})
        .is((val) => val > 0 || typeof val === 'string')
        .then(() => done())
    })

    it('receiver2 can connect to server', function (done) {
      receiver2.set({
        adapter: {
          [key]: 'server_client'
        }
      })

      receiver2.get('clients.receiver_client_2.platform', {})
        .is((val) => { return typeof val === 'string' })
        .then(() => done())
    })

    xit('reciever2 has ip', function () {
      expect(receiver2)
        .to.have.property('clients')
        .which.has.property('receiver_client_2')
        .which.has.property('ip')
    })

    // sending info back is weird
    xit('reciever has correct client meta data about receiver2', function () {
      expect(receiver)
        .to.have.property('clients')
        .which.has.property('receiver_client_2')
        .which.has.property('platform')
    })
  })
}
<commit_msg>added client tests (async)<commit_after>'use strict'

module.exports = function (protocol, key) {
  describe('client', function () {
    var Hub = require('../../lib')
    var server, receiver, receiver2

    it('can create a server and clients', function () {
      server = new Hub({
        key: 'server_client',
        adapter: {
          id: 'server_client',
          inject: protocol
        }
      })
      receiver = new Hub({
        key: 'receiver_client',
        adapter: {
          id: 'receiver_client',
          inject: protocol,
          [key]: {}
        }
      })
      receiver2 = new Hub({
        key: 'receiver_client_2',
        adapter: {
          id: 'receiver_client_2',
          inject: protocol,
          [key]: {}
        }
      })
      server.set({
        adapter: {
          [key]: {
            server: key === 'mock' ? 'server_client' : 6001
          }
        }
      })
    })

    it('receiver can connect to server', function (done) {
      receiver.adapter[key].once('connect', function () {
        server.get('clients', {}).once(function () {
          expect(server)
            .to.have.property('clients')
            .which.has.property('receiver_client')
            .which.has.property('platform')
        })
        done()
      })
      receiver.set({
        adapter: {
          [key]: key === 'mock' ? 'server_client' : 'ws://localhost:6001'
        }
      })
    })

    it('receiver has ip', function (done) {
      receiver.get('clients.receiver_client.ip', {})
        .is((val) => val > 0 || typeof val === 'string')
        .then(() => done())
    })

    it('receiver2 can connect to server', function (done) {
      receiver2.set({
        adapter: {
          [key]: key === 'mock' ? 'server_client' : 'ws://localhost:6001'
        }
      })

      receiver2.get('clients.receiver_client_2.platform', {})
        .is((val) => { return typeof val === 'string' })
        .then(() => done())
    })

    it('reciever2 has ip', function (done) {
      receiver2.get('clients.receiver_client_2.ip', {})
        .is((val) => val > 0 || typeof val === 'string')
        .then(() => done())
    })

    // sending info back is weird
    it('reciever has correct client meta data about receiver2', function () {
      expect(receiver)
        .to.have.property('clients')
        .which.has.property('receiver_client_2')
        .which.has.property('platform')
    })
  })
}
<|endoftext|>


<commit_before>var SerialPort = require("./mock-serial").SerialPort,
    pins = require("./mock-pins"),
    five = require("../lib/johnny-five.js"),
    serial = new SerialPort("/path/to/fake/usb"),
    Board = five.Board,
    ShiftRegister = five.ShiftRegister,
    board = new five.Board({
      repl: false,
      debug: true,
      mock: serial
    }),
    sinon = require("sinon");

board.firmata.pins = pins.UNO;
board.firmata.analogPins = [ 14, 15, 16, 17, 18, 19 ];
board.pins = Board.Pins( board );

// END

exports["ShiftRegister"] = {

  setUp: function( done ) {

    this.shiftRegister = new ShiftRegister({
      pins: {
        data: 2,
        clock: 3,
        latch: 4
      },
      board: board
    });

    this.proto = [
      { name: "send" }
    ];

    this.instance = [
      { name: "pins" }
    ];

    this.pins = [
      { name: "data" },
      { name: "clock" },
      { name: "latch" }
    ];

    done();
  },
  shape: function( test ) {
    test.expect( this.proto.length + this.instance.length + this.pins.length );

    this.proto.forEach(function( method ) {
      test.equal( typeof this.shiftRegister[ method.name ], "function" );
    }, this);

    this.instance.forEach(function( property ) {
      test.notEqual( typeof this.shiftRegister[ property.name ], "undefined" );
    }, this);

    this.pins.forEach(function( property ) {
      test.notEqual( typeof this.shiftRegister.pins[ property.name ], "undefined" );
    }, this);

    test.done();
  },
  send: function( test ){
    var spy = sinon.spy(board.firmata, 'digitalWrite');
    var shiftOutSpy = sinon.spy(board, 'shiftOut');
    test.expect(6);

    this.shiftRegister.send(0x01);
    test.ok(spy.getCall(0).calledWith(4, 0)); // latch, low
    test.ok(shiftOutSpy.calledWith(2, 3, true, 1));
    test.ok(spy.getCall(25).calledWith(4, 1)); // latch, high

    this.shiftRegister.send(0x10);
    test.ok(spy.getCall(26).calledWith(4, 0)); // latch, low
    test.ok(shiftOutSpy.calledWith(2, 3, true, 16));
    test.ok(spy.getCall(51).calledWith(4, 1)); // latch, high

    shiftOutSpy.restore();
    spy.restore();
    test.done();
  }

};
<commit_msg>ShiftRegister to use mockfirmata<commit_after>var MockFirmata = require("./mock-firmata"),
    five = require("../lib/johnny-five.js"),
    Board = five.Board,
    ShiftRegister = five.ShiftRegister,
    board = new five.Board({
      repl: false,
      firmata: new MockFirmata()
    }),
    sinon = require("sinon");

exports["ShiftRegister"] = {

  setUp: function( done ) {

    this.shiftRegister = new ShiftRegister({
      pins: {
        data: 2,
        clock: 3,
        latch: 4
      },
      board: board
    });

    this.proto = [
      { name: "send" }
    ];

    this.instance = [
      { name: "pins" }
    ];

    this.pins = [
      { name: "data" },
      { name: "clock" },
      { name: "latch" }
    ];

    done();
  },

  shape: function( test ) {
    test.expect( this.proto.length + this.instance.length + this.pins.length );

    this.proto.forEach(function( method ) {
      test.equal( typeof this.shiftRegister[ method.name ], "function" );
    }, this);

    this.instance.forEach(function( property ) {
      test.notEqual( typeof this.shiftRegister[ property.name ], "undefined" );
    }, this);

    this.pins.forEach(function( property ) {
      test.notEqual( typeof this.shiftRegister.pins[ property.name ], "undefined" );
    }, this);

    test.done();
  },

  send: function( test ){
    var spy = sinon.spy(board.firmata, 'digitalWrite');
    var shiftOutSpy = sinon.spy(board, 'shiftOut');
    test.expect(6);

    this.shiftRegister.send(0x01);
    test.ok(spy.getCall(0).calledWith(4, 0)); // latch, low
    test.ok(shiftOutSpy.calledWith(2, 3, true, 1));
    test.ok(spy.getCall(25).calledWith(4, 1)); // latch, high

    this.shiftRegister.send(0x10);
    test.ok(spy.getCall(26).calledWith(4, 0)); // latch, low
    test.ok(shiftOutSpy.calledWith(2, 3, true, 16));
    test.ok(spy.getCall(51).calledWith(4, 1)); // latch, high

    shiftOutSpy.restore();
    spy.restore();
    test.done();
  }

};
<|endoftext|>


<commit_before>define(function () {
  'use strict';

  function testBaseInfo(assert, baseInfo, doc) {
    var head = doc.head || doc.getElementsByTagName('head')[0],
      base = doc.getElementsByTagName('base')[0];

    baseInfo();

    if (baseInfo.baseElement) {
      assert.strictEqual(baseInfo.baseElement, base, 'baseInfo.baseElement stores the correct value');
      head = baseInfo.baseElement.parentNode;
    }

    equal(baseInfo.head, head, 'baseInfo.head  stores the correct value');

    assert.strictEqual(baseInfo.baseUrl, '../spec/', 'baseInfo.baseUrl  stores the correct value');
    assert.strictEqual(baseInfo.baseGlobal, 'GLOB', 'baseInfo.baseGlobal  stores the correct value');
  }

  fix.test('baseInfo', {
    message: 'is a expose function for AMD functions and more DefineJS attributes',
    module: {
      beforeEach: function () {
        var currentScript = $('<script>', {
          'src': 'spec/baseInfo.js',
          'global': 'GLOB',
          'base': '../spec/'
        }).get(0);

        Object.defineProperty(document, 'currentScript', {
          get: function () {
            return currentScript;
          },
          configurable: true
        });
      },
      afterEach: function () {
        delete document.currentScript;
      }
    },
    require: ['./baseInfo', './var/doc']
  }).then(function (assert, baseInfo, doc) {

    assert.strictEqual(typeof baseInfo, 'function', 'baseInfo is an object');

    assert.strictEqual(doc, document, 'doc is the global document object');

    testBaseInfo(assert, baseInfo, doc);
  });
});<commit_msg>test baseInfo with base element in page<commit_after>define(function () {
  'use strict';

  function testBaseInfo(assert, baseInfo, doc) {
    var head = doc.head || doc.getElementsByTagName('head')[0];

    //First test run on baseInfo
    var baseEl = $('<base>', {
      href: '/baseUrl'
    }).appendTo(baseInfo.head);

    assert.currentScript = undefined;

    baseInfo.baseUrl = '/testBase';

    baseInfo();

    assert.strictEqual(baseInfo.baseElement, baseEl.get(0), 'baseInfo.baseElement stores the correct value');
    equal(baseInfo.head, baseInfo.baseElement.parentNode, 'baseInfo.head stores the correct value:with base element in page');
    assert.strictEqual(baseInfo.baseUrl, '', 'baseInfo.baseUrl is empty when there is no currentScript');

    baseEl.remove();

    //second test run on baseInfo
    assert.currentScript = $('<script>', {
      'src': 'spec/baseInfo.js',
      'global': 'GLOB',
      'base': '../spec/'
    }).get(0);

    baseInfo();

    equal(baseInfo.head, head, 'baseInfo.head  stores the correct value');

    assert.strictEqual(baseInfo.baseUrl, '../spec/', 'baseInfo.baseUrl  stores the correct value');
    assert.strictEqual(baseInfo.baseGlobal, 'GLOB', 'baseInfo.baseGlobal  stores the correct value');
  }

  fix.test('baseInfo', {
    message: 'is a expose function for AMD functions and more DefineJS attributes',
    module: {
      beforeEach: function (assert) {
        Object.defineProperty(document, 'currentScript', {
          get: function () {
            return assert.currentScript;
          },
          configurable: true
        });
      },
      afterEach: function (assert) {
        delete document.currentScript;
      }
    },
    require: ['./baseInfo', './var/doc']
  }).then(function (assert, baseInfo, doc) {

    assert.strictEqual(typeof baseInfo, 'function', 'baseInfo is an object');

    assert.strictEqual(doc, document, 'doc is the global document object');

    testBaseInfo(assert, baseInfo, doc);
  });
});<|endoftext|>