<commit_before>var secrets = require('../config/secrets');
var User = require('../models/User');
var querystring = require('querystring');
var async = require('async');
var cheerio = require('cheerio');
var request = require('request');
var _ = require('underscore');
var graph = require('fbgraph');
var LastFmNode = require('lastfm').LastFmNode;
var tumblr = require('tumblr.js');
var foursquare = require('node-foursquare')({ secrets: secrets.foursquare });
var Github = require('github-api');
var Twit = require('twit');

/**
 * GET /api
 * List of API examples.
 */

exports.getApi = function(req, res) {
  res.render('api/index', {
    title: 'API Browser'
  });
};

/**
 * GET /api/foursquare
 * Foursquare API example.
 */

exports.getFoursquare = function(req, res, next) {
  var token = _.findWhere(req.user.tokens, { kind: 'foursquare' });
  async.parallel({
    trendingVenues: function(callback) {
      foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function(err, results) {
        callback(err, results);
      });
    },
    venueDetail: function(callback) {
      foursquare.Venues.getVenue('49da74aef964a5208b5e1fe3', token.accessToken, function(err, results) {
        callback(err, results);
      });
    },
    userCheckins: function(callback) {
      foursquare.Users.getCheckins('self', null, token.accessToken, function(err, results) {
        callback(err, results);
      });
    }
  },
  function(err, results) {
    if (err) return next(err);
    res.render('api/foursquare', {
      title: 'Foursquare API',
      trendingVenues: results.trendingVenues,
      venueDetail: results.venueDetail,
      userCheckins: results.userCheckins
    });
  });
};

/**
 * GET /api/tumblr
 * Tumblr API example.
 */

exports.getTumblr = function(req, res) {
  var token = _.findWhere(req.user.tokens, { kind: 'tumblr' });
  var client = tumblr.createClient({
    consumer_key: secrets.tumblr.consumerKey,
    consumer_secret: secrets.tumblr.consumerSecret,
    token: token.accessToken,
    token_secret: token.tokenSecret
  });
  client.posts('goddess-of-imaginary-light.tumblr.com', { type: 'photo' }, function(err, data) {
    res.render('api/tumblr', {
      title: 'Tumblr API',
      blog: data.blog,
      photoset: data.posts[0].photos
    });
  });
};

/**
 * GET /api/facebook
 * Facebook API example.
 */

exports.getFacebook = function(req, res, next) {
  var token = _.findWhere(req.user.tokens, { kind: 'facebook' });
  graph.setAccessToken(token.accessToken);
  async.parallel({
    getMe: function(done) {
      graph.get(req.user.facebook, function(err, me) {
        done(err, me);
      });
    },
    getMyFriends: function(done) {
      graph.get(req.user.facebook + '/friends', function(err, friends) {
        done(err, friends.data);
      });
    }
  },
  function(err, results) {
    if (err) return next(err);
    res.render('api/facebook', {
      title: 'Facebook API',
      me: results.getMe,
      friends: results.getMyFriends
    });
  });
};

/**
 * GET /api/scraping
 * Web scraping example using Cheerio library.
 */

exports.getScraping = function(req, res, next) {
  request.get('https://news.ycombinator.com/', function(err, request, body) {
    if (err) return next(err);
    var $ = cheerio.load(body);
    var links = [];
    $('.title a').each(function() {
      links.push($(this));
    });
    res.render('api/scraping', {
      title: 'Web Scraping',
      links: links
    });
  });
};

/**
 * GET /api/github
 * GitHub API Example.
 */
exports.getGithub = function(req, res) {
  var token = _.findWhere(req.user.tokens, { kind: 'github' });
  var github = new Github({ token: token.accessToken });
  var repo = github.getRepo('sahat', 'requirejs-library');
  repo.show(function(err, repo) {
    res.render('api/github', {
      title: 'GitHub API',
      repo: repo
    });
  });

};

/**
 * GET /api/aviary
 * Aviary image processing example.
 */

exports.getAviary = function(req, res) {
  res.render('api/aviary', {
    title: 'Aviary API'
  });
};

/**
 * GET /api/nyt
 * New York Times API example.
 */

exports.getNewYorkTimes = function(req, res, next) {
  var query = querystring.stringify({ 'api-key': secrets.nyt.key, 'list-name': 'young-adult' });
  var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query;
  request.get(url, function(error, request, body) {
    if (request.statusCode === 403) return next(Error('Missing New York Times API Key'));
    var bestsellers = JSON.parse(body);
    res.render('api/nyt', {
      title: 'New York Times API',
      books: bestsellers.results
    });
  });
};

/**
 * GET /api/lastfm
 * Last.fm API example.
 */

exports.getLastfm = function(req, res, next) {
  var lastfm = new LastFmNode(secrets.lastfm);
  async.parallel({
    artistInfo: function(done) {
      lastfm.request("artist.getInfo", {
        artist: 'Epica',
        handlers: {
          success: function(data) {
            done(null, data);
          },
          error: function(err) {
            done(err);
          }
        }
      });
    },
    artistTopAlbums: function(done) {
      lastfm.request("artist.getTopAlbums", {
        artist: 'Epica',
        handlers: {
          success: function(data) {
            var albums = [];
            _.each(data.topalbums.album, function(album) {
              albums.push(album.image.slice(-1)[0]['#text']);
            });
            done(null, albums.slice(0,4));
          },
          error: function(err) {
            done(err);
          }
        }
      });
    }
  },
  function(err, results) {
    if (err) return next(err);
    var artist = {
      name: results.artistInfo.artist.name,
      image: results.artistInfo.artist.image.slice(-1)[0]['#text'],
      tags: results.artistInfo.artist.tags.tag,
      bio: results.artistInfo.artist.bio.summary,
      stats: results.artistInfo.artist.stats,
      similar: results.artistInfo.artist.similar.artist,
      topAlbums: results.artistTopAlbums
    };
    res.render('api/lastfm', {
      title: 'Last.fm API',
      artist: artist
    });
  });
};

/**
 * GET /api/twitter
 * Twiter API example.
 */

exports.getTwitter = function(req, res, next) {
  var token = _.findWhere(req.user.tokens, { kind: 'twitter' });
  var T = new Twit({
    consumer_key: secrets.twitter.consumerKey,
    consumer_secret: secrets.twitter.consumerSecret,
    access_token: token.accessToken,
    access_token_secret: token.tokenSecret
  });
  T.get('search/tweets', { q: 'hackathon since:2013-01-01', geocode: '40.71448,-74.00598,5mi', count: 50 }, function(err, reply) {
    if (err) return next(err);
    res.render('api/twitter', {
      title: 'Twitter API',
      tweets: reply.statuses
    });
  });
};
<commit_msg>Display error message when Last.fm api key is missing<commit_after>var secrets = require('../config/secrets');
var User = require('../models/User');
var querystring = require('querystring');
var async = require('async');
var cheerio = require('cheerio');
var request = require('request');
var _ = require('underscore');
var graph = require('fbgraph');
var LastFmNode = require('lastfm').LastFmNode;
var tumblr = require('tumblr.js');
var foursquare = require('node-foursquare')({ secrets: secrets.foursquare });
var Github = require('github-api');
var Twit = require('twit');

/**
 * GET /api
 * List of API examples.
 */

exports.getApi = function(req, res) {
  res.render('api/index', {
    title: 'API Browser'
  });
};

/**
 * GET /api/foursquare
 * Foursquare API example.
 */

exports.getFoursquare = function(req, res, next) {
  var token = _.findWhere(req.user.tokens, { kind: 'foursquare' });
  async.parallel({
    trendingVenues: function(callback) {
      foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function(err, results) {
        callback(err, results);
      });
    },
    venueDetail: function(callback) {
      foursquare.Venues.getVenue('49da74aef964a5208b5e1fe3', token.accessToken, function(err, results) {
        callback(err, results);
      });
    },
    userCheckins: function(callback) {
      foursquare.Users.getCheckins('self', null, token.accessToken, function(err, results) {
        callback(err, results);
      });
    }
  },
  function(err, results) {
    if (err) return next(err);
    res.render('api/foursquare', {
      title: 'Foursquare API',
      trendingVenues: results.trendingVenues,
      venueDetail: results.venueDetail,
      userCheckins: results.userCheckins
    });
  });
};

/**
 * GET /api/tumblr
 * Tumblr API example.
 */

exports.getTumblr = function(req, res) {
  var token = _.findWhere(req.user.tokens, { kind: 'tumblr' });
  var client = tumblr.createClient({
    consumer_key: secrets.tumblr.consumerKey,
    consumer_secret: secrets.tumblr.consumerSecret,
    token: token.accessToken,
    token_secret: token.tokenSecret
  });
  client.posts('goddess-of-imaginary-light.tumblr.com', { type: 'photo' }, function(err, data) {
    res.render('api/tumblr', {
      title: 'Tumblr API',
      blog: data.blog,
      photoset: data.posts[0].photos
    });
  });
};

/**
 * GET /api/facebook
 * Facebook API example.
 */

exports.getFacebook = function(req, res, next) {
  var token = _.findWhere(req.user.tokens, { kind: 'facebook' });
  graph.setAccessToken(token.accessToken);
  async.parallel({
    getMe: function(done) {
      graph.get(req.user.facebook, function(err, me) {
        done(err, me);
      });
    },
    getMyFriends: function(done) {
      graph.get(req.user.facebook + '/friends', function(err, friends) {
        done(err, friends.data);
      });
    }
  },
  function(err, results) {
    if (err) return next(err);
    res.render('api/facebook', {
      title: 'Facebook API',
      me: results.getMe,
      friends: results.getMyFriends
    });
  });
};

/**
 * GET /api/scraping
 * Web scraping example using Cheerio library.
 */

exports.getScraping = function(req, res, next) {
  request.get('https://news.ycombinator.com/', function(err, request, body) {
    if (err) return next(err);
    var $ = cheerio.load(body);
    var links = [];
    $('.title a').each(function() {
      links.push($(this));
    });
    res.render('api/scraping', {
      title: 'Web Scraping',
      links: links
    });
  });
};

/**
 * GET /api/github
 * GitHub API Example.
 */
exports.getGithub = function(req, res) {
  var token = _.findWhere(req.user.tokens, { kind: 'github' });
  var github = new Github({ token: token.accessToken });
  var repo = github.getRepo('sahat', 'requirejs-library');
  repo.show(function(err, repo) {
    res.render('api/github', {
      title: 'GitHub API',
      repo: repo
    });
  });

};

/**
 * GET /api/aviary
 * Aviary image processing example.
 */

exports.getAviary = function(req, res) {
  res.render('api/aviary', {
    title: 'Aviary API'
  });
};

/**
 * GET /api/nyt
 * New York Times API example.
 */

exports.getNewYorkTimes = function(req, res, next) {
  var query = querystring.stringify({ 'api-key': secrets.nyt.key, 'list-name': 'young-adult' });
  var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query;
  request.get(url, function(error, request, body) {
    if (request.statusCode === 403) return next(Error('Missing or Invalid New York Times API Key'));
    var bestsellers = JSON.parse(body);
    res.render('api/nyt', {
      title: 'New York Times API',
      books: bestsellers.results
    });
  });
};

/**
 * GET /api/lastfm
 * Last.fm API example.
 */

exports.getLastfm = function(req, res, next) {
  var lastfm = new LastFmNode(secrets.lastfm);
  async.parallel({
    artistInfo: function(done) {
      lastfm.request("artist.getInfo", {
        artist: 'Epica',
        handlers: {
          success: function(data) {
            done(null, data);
          },
          error: function(err) {
            done(err);
          }
        }
      });
    },
    artistTopAlbums: function(done) {
      lastfm.request("artist.getTopAlbums", {
        artist: 'Epica',
        handlers: {
          success: function(data) {
            var albums = [];
            _.each(data.topalbums.album, function(album) {
              albums.push(album.image.slice(-1)[0]['#text']);
            });
            done(null, albums.slice(0,4));
          },
          error: function(err) {
            done(err);
          }
        }
      });
    }
  },
  function(err, results) {
    if (err) return next(err.message);
    var artist = {
      name: results.artistInfo.artist.name,
      image: results.artistInfo.artist.image.slice(-1)[0]['#text'],
      tags: results.artistInfo.artist.tags.tag,
      bio: results.artistInfo.artist.bio.summary,
      stats: results.artistInfo.artist.stats,
      similar: results.artistInfo.artist.similar.artist,
      topAlbums: results.artistTopAlbums
    };
    res.render('api/lastfm', {
      title: 'Last.fm API',
      artist: artist
    });
  });
};

/**
 * GET /api/twitter
 * Twiter API example.
 */

exports.getTwitter = function(req, res, next) {
  var token = _.findWhere(req.user.tokens, { kind: 'twitter' });
  var T = new Twit({
    consumer_key: secrets.twitter.consumerKey,
    consumer_secret: secrets.twitter.consumerSecret,
    access_token: token.accessToken,
    access_token_secret: token.tokenSecret
  });
  T.get('search/tweets', { q: 'hackathon since:2013-01-01', geocode: '40.71448,-74.00598,5mi', count: 50 }, function(err, reply) {
    if (err) return next(err);
    res.render('api/twitter', {
      title: 'Twitter API',
      tweets: reply.statuses
    });
  });
};
<|endoftext|>


<commit_before>import { Dispatcher } from 'flux';
import immutableUpdate from 'react/lib/update';
import deepFreeze from 'deep-freeze';
import deepEqual from 'deep-equal';
import initialState from './state.json';

let state = deepFreeze(initialState);

let dispatcher = new Dispatcher();

function get(statePath = []) {
    return statePath.reduce((s, k) => (s || {})[k], state);
}

function update(statePath = [], spec = {}) {
    state = deepFreeze(immutableUpdate(
        state,
        statePath.reduceRight((s, k) => { return { [k]: s }; }, spec)
    ));
    dispatcher.dispatch();
}

function createHandle(...statePath) {

    let localState = get(statePath);

    let localDispatcher = new Dispatcher();

    return Object.create({

        dispatcher: localDispatcher,

        update: update.bind(null, statePath),

        get: get.bind(null, statePath),

        detach: dispatcher.unregister.bind(
            dispatcher,
            dispatcher.register(() => {
                let nextState = get(statePath);
                if (!deepEqual(localState, nextState)) {
                    localState = nextState;
                    localDispatcher.dispatch(nextState);
                }
            })
        )
    });
}
export default Object.assign(createHandle(), { createHandle });

export const StateMixin = {

    updateState(spec = {}) {
        update(this.statePath, spec);
    },

    getInitialState() {
        return get(this.statePath);
    },

    componentDidMount() {
        this._stateToken = dispatcher.register(() => {
            this.setState(this.getInitialState());
        });
    },

    componentWillUnmount() {
        if (this._stateToken) {
            dispatcher.unregister(this._stateToken);
            delete this._stateToken;
        }
    },

    shouldComponentUpdate(nextProps, nextState) {
        return !deepEqual(this.state, nextState);
    }
};
<commit_msg>cleanup; remove overly defensive code<commit_after>import { Dispatcher } from 'flux';
import immutableUpdate from 'react/lib/update';
import deepFreeze from 'deep-freeze';
import deepEqual from 'deep-equal';
import initialState from './state.json';

let state = deepFreeze(initialState);

let dispatcher = new Dispatcher();

function get(statePath = []) {
    return statePath.reduce((s, k) => (s || {})[k], state);
}

function update(statePath = [], spec = {}) {
    state = deepFreeze(immutableUpdate(
        state,
        statePath.reduceRight((s, k) => { return { [k]: s }; }, spec)
    ));
    dispatcher.dispatch();
}

function createHandle(...statePath) {

    let localState = get(statePath);

    let localDispatcher = new Dispatcher();

    return Object.create({

        dispatcher: localDispatcher,

        get: get.bind(null, statePath),

        update: update.bind(null, statePath),

        detach: dispatcher.unregister.bind(
            dispatcher,
            dispatcher.register(() => {
                let nextState = get(statePath);
                if (!deepEqual(localState, nextState)) {
                    localState = nextState;
                    localDispatcher.dispatch(nextState);
                }
            })
        )
    });
}
export default Object.assign(createHandle(), { createHandle });

export const StateMixin = {

    updateState(spec = {}) {
        update(this.statePath, spec);
    },

    getInitialState() {
        return get(this.statePath);
    },

    componentDidMount() {
        this._stateToken = dispatcher.register(() => {
            this.setState(this.getInitialState());
        });
    },

    componentWillUnmount() {
        dispatcher.unregister(this._stateToken);
    },

    shouldComponentUpdate(nextProps, nextState) {
        return !deepEqual(this.state, nextState);
    }
};
<|endoftext|>


<commit_before>// Double Click Plugin for HTMLArea-3.0
// Implementation by Marijn Kampf http://www.marijn.org
// Sponsored by http://www.smiling-faces.com
//
// (c) Marijn Kampf 2004.
// Distributed under the same terms as HTMLArea itself.
// This notice MUST stay intact for use (see license.txt).
//
// Cut-n-paste version of double click plugin.
// Almost no original code used. Based on
// Luis HTMLarea and Mihai Bazon Context Menu
//
//
//

DoubleClick._pluginInfo = {
	name          : "DoubleClick",
	version       : "1.0",
	developer     : "Marijn Kampf",
	developer_url : "http://www.marijn.org",
	c_owner       : "Marijn Kampf",
	sponsor       : "smiling-faces.com",
	sponsor_url   : "http://www.smiling-faces.com",
	license       : "htmlArea"
};

function DoubleClick(editor) {
	this.editor = editor;

	// ADDING CUSTOM DOUBLE CLICK ACTIONS
	// format of the dblClickList elements is "TAGNAME: [ ACTION ]"
	//    - TAGNAME: tagname of the tag that is double clicked
	//    - ACTION: function that gets called when the button is clicked.
	//              it has the following prototype:
	//                 function(editor, event)
	//              - editor is the HTMLArea object that triggered the call
	//							- target is the selected object
	this.editor.dblClickList = {
		// Edit Link dialog
		a: [ function(e) {e.config.btnList['createlink'][3](e); } ],
		// Follow link
		//a: [ function(editor, target) { window.location = target.href; properties(target); } ],

		img: [ function(e) {e.execCommand("insertimage");} ],
		td: [ function(e) {e.execCommand("inserttable");} ]
	};
}

DoubleClick.prototype.onGenerate = function() {
	var self = this;
	var doc = this.editordoc = this.editor._iframe.contentWindow.document;
	HTMLArea._addEvents(doc, ["dblclick"],
			    function (event) {
			    return self.onDoubleClick(HTMLArea.is_ie ? self.editor._iframe.contentWindow.event : event);
			    });
	this.currentClick = null;
};

DoubleClick.prototype.onDoubleClick = function(ev) {
	var target = HTMLArea.is_ie ? ev.srcElement : ev.target;
	var tagName = target.tagName.toLowerCase();

	if (this.editor.dblClickList[tagName] != undefined) {
		this.editor.dblClickList[tagName][0](this.editor, target);
	}
};<commit_msg>change htmlarea to Xinha in plugin DoubleClick<commit_after>// Double Click Plugin for Xinha
// Implementation by Marijn Kampf http://www.marijn.org
// Sponsored by http://www.smiling-faces.com
//
// (c) Marijn Kampf 2004.
// Distributed under the same terms as HTMLArea itself.
// This notice MUST stay intact for use (see license.txt).
//
// Cut-n-paste version of double click plugin.
// Almost no original code used. Based on
// Luis HTMLarea and Mihai Bazon Context Menu
//
//
//

DoubleClick._pluginInfo = {
  name          : "DoubleClick",
  version       : "1.0",
  developer     : "Marijn Kampf",
  developer_url : "http://www.marijn.org",
  c_owner       : "Marijn Kampf",
  sponsor       : "smiling-faces.com",
  sponsor_url   : "http://www.smiling-faces.com",
  license       : "htmlArea"
};

function DoubleClick(editor) {
  this.editor = editor;

  // ADDING CUSTOM DOUBLE CLICK ACTIONS
  // format of the dblClickList elements is "TAGNAME: [ ACTION ]"
  //    - TAGNAME: tagname of the tag that is double clicked
  //    - ACTION: function that gets called when the button is clicked.
  //              it has the following prototype:
  //                 function(editor, event)
  //              - editor is the Xinha object that triggered the call
  //              - target is the selected object
  this.editor.dblClickList = {
    // Edit Link dialog
    a: [ function(e) {e.config.btnList['createlink'][3](e); } ],
    // Follow link
    //a: [ function(editor, target) { window.location = target.href; properties(target); } ],

    img: [ function(e) {e.execCommand("insertimage");} ],
    td: [ function(e) {e.execCommand("inserttable");} ]
  };
}

DoubleClick.prototype.onGenerate = function() {
  var self = this;
  var doc = this.editordoc = this.editor._iframe.contentWindow.document;
  Xinha._addEvents(doc, ["dblclick"],
          function (event) {
          return self.onDoubleClick(Xinha.is_ie ? self.editor._iframe.contentWindow.event : event);
          });
  this.currentClick = null;
};

DoubleClick.prototype.onDoubleClick = function(ev) {
  var target = Xinha.is_ie ? ev.srcElement : ev.target;
  var tagName = target.tagName.toLowerCase();

  if (this.editor.dblClickList[tagName] != undefined) {
    this.editor.dblClickList[tagName][0](this.editor, target);
  }
};<|endoftext|>


<commit_before>/*
 * For reducing boilerplate on examine listeners.
 *
 * config object:
 *
 * poi : An array or object with points of interest.
 *   It can be an array of strings or an object with strings as the keys and
 *   functions as the values.
 *
 *  action: Needed if poi is an array of strings,
 *    It is the function to run if the POI is found.
 *
 *  (optional) notFound: Function to run if the POI is
 *    not found. A default is provided.
*/
var util = require('util');
module.exports.examine = (args, player, players, config) => {
  // Check to make sure config is valid

  if (!config.poi) {
    util.log("Invalid config for examine event: ", config);
    return;
  }

  var valid = poi.indexOf(args.toLowerCase()) > -1;
  if (valid && CommandUtil.isDaytime()) {
    player.say();
    players.eachIf(p => CommandUtil.otherPlayerInRoom(player, p),
      p => { p.sayL10n(l10n, 'OTHER_LOOKING', player.getName()); });
  } else if (valid) {
    player.sayL10n(l10n, 'DARKNESS');
  } else nothingFound()

}
<commit_msg>Add function calls and check for a night success function.<commit_after>/*
 * For reducing boilerplate on examine listeners.
 *
 * config object:
 *
 *  poi : An array or object with points of interest.
 *    It can be an array of strings or an object with strings as the keys and
 *    functions as the values.
 *
 *  action: Needed if poi is an array of strings,
 *    It is the function to run if the POI is found.
 *
 *  (optional) notFound: Function to run if the POI is
 *    not found. A default is provided.
 */

var util = require('util');
module.exports.examine = (args, player, players, config) => {

  // Check to make sure config is valid.
  if (!config.poi) {
    util.log("Invalid config for examine event: ", config);
    return;
  }

  // Set defaults as needed.
  config.foundAtNight = config.foundAtNight || config.found;

  var valid = config.poi.indexOf(args.toLowerCase()) > -1;

  if (valid && CommandUtil.isDaytime()) {
    config.found();
  } else if (valid) {
    config.foundAtNight()
  } else config.nothingFound()
}
<|endoftext|>


<commit_before>"use strict";

/** @const */
var STATE_VERSION = 0;

/** @const */
var STATE_MAGIC = 0x86768676|0;

/** @const */
var STATE_INDEX_MAGIC = 0;

/** @const */
var STATE_INDEX_VERSION = 1;

/** @const */
var STATE_INDEX_TOTAL_LEN = 2;

/** @const */
var STATE_INDEX_INFO_LEN = 3;

/** @const */
var STATE_INFO_BLOCK_START = 16;

/** @constructor */
function StateLoadError(msg)
{
    this.message = msg;
}
StateLoadError.prototype = new Error;

function save_object(obj, arraybuffers)
{
    // recursively create a structure that can be json-dumped, pushing
    // arraybuffers into the second argument

    if(typeof obj !== "object" || obj === null || obj instanceof Array)
    {
        return obj;
    }

    if(obj.constructor === Object)
    {
        var keys = Object.keys(obj);
        var result = {};

        for(var i = 0; i < keys.length; i++)
        {
            var key = keys[i];
            result[key] = save_object(obj[key], arraybuffers);
        }

        return result;
    }

    if(obj.BYTES_PER_ELEMENT)
    {
        // Uint8Array, etc.
        return {
            __state_type__: obj.constructor.name,
            buffer_id: arraybuffers.push(obj.buffer) - 1,
        };
    }

    if(obj instanceof ArrayBuffer)
    {
        return {
            __state_type__: "ArrayBuffer",
            buffer_id: arraybuffers.push(obj) - 1,
        };
    }

    var skip = Array.setify(obj._state_skip || []);
    skip["_state_skip"] = true;

    var keys = Object.keys(obj);
    var result = {};

    for(var i = 0; i < keys.length; i++)
    {
        var key = keys[i];

        if(skip[key])
        {
            continue;
        }

        var value = obj[key];

        if(typeof value === "function")
        {
            continue;
        }

        result[key] = save_object(value, arraybuffers);
    }

    return result;
}

function restore_object(base, obj, buffers)
{
    // recurisvely restore obj into base

    if(typeof obj !== "object" || obj instanceof Array || obj === null)
    {
        return obj;
    }

    var type = obj.__state_type__;

    if(type === undefined)
    {
        var keys = Object.keys(obj);

        for(var i = 0; i < keys.length; i++)
        {
            var key = keys[i];
            base[key] = restore_object(base[key], obj[key], buffers);
        }

        if(base._state_restore)
        {
            base._state_restore();
        }

        return base;
    }
    else if(type === "ArrayBuffer")
    {
        var info = buffers.infos[obj.buffer_id];

        if(base && base.byteLength === info.length)
        {
            new Uint8Array(base).set(new Uint8Array(buffers.full, info.offset, info.length));
        }
        else
        {
            //base = buffers.full.slice(info.offset, info.offset + info.length);
            dbg_assert(false);
        }

        return base;
    }
    else
    {
        var table = {
            "Uint8Array": Uint8Array,
            "Int8Array": Int8Array,
            "Uint16Array": Uint16Array,
            "Int16Array": Int16Array,
            "Uint32Array": Uint32Array,
            "Int32Array": Int32Array,
            "Float32Array": Float32Array,
            "Float64Array": Float64Array,
        };

        var constructor = table[type];
        dbg_assert(constructor, "Unkown type: " + type);

        var info = buffers.infos[obj.buffer_id];

        // avoid a new allocation if possible
        if(base &&
           base.constructor === constructor &&
           base.byteOffset === 0 &&
           base.byteLength === info.length)
        {
            new Uint8Array(base.buffer).set(
                new Uint8Array(buffers.full, info.offset, info.length),
                base.byteOffset
            );
            return base;
        }
        else
        {
            var buf = buffers.full.slice(info.offset, info.offset + info.length);
            return new constructor(buf);
        }
    }
}

CPU.prototype.save_state = function()
{
    var arraybuffers = [];
    var state = save_object(this, arraybuffers);

    var buffer_infos = [];
    var total_buffer_size = 0;

    for(var i = 0; i < arraybuffers.length; i++)
    {
        var len = arraybuffers[i].byteLength;

        buffer_infos[i] = {
            offset: total_buffer_size,
            length: len,
        };

        total_buffer_size += len;

        // align
        total_buffer_size = total_buffer_size + 3 & ~3;
    }

    var info_object = JSON.stringify({
        buffer_infos: buffer_infos,
        state: state,
    });

    var buffer_block_start = STATE_INFO_BLOCK_START + 2 * info_object.length;
    var total_size = buffer_block_start + total_buffer_size;

    var result = new ArrayBuffer(total_size);

    var header_block = new Int32Array(
        result,
        0,
        STATE_INFO_BLOCK_START / 4
    );
    var info_block = new Uint16Array(
        result,
        STATE_INFO_BLOCK_START,
        info_object.length
    );
    var buffer_block = new Uint8Array(
        result,
        buffer_block_start
    );

    header_block[STATE_INDEX_MAGIC] = STATE_MAGIC;
    header_block[STATE_INDEX_VERSION] = STATE_VERSION;
    header_block[STATE_INDEX_TOTAL_LEN] = total_size;
    header_block[STATE_INDEX_INFO_LEN] = info_object.length * 2;

    for(var i = 0; i < info_object.length; i++)
    {
        info_block[i] = info_object.charCodeAt(i);
    }

    for(var i = 0; i < arraybuffers.length; i++)
    {
        var buffer = arraybuffers[i];
        buffer_block.set(new Uint8Array(buffer), buffer_infos[i].offset);
    }

    return result;
};

CPU.prototype.restore_state = function(state)
{
    var len = state.byteLength;

    if(len < STATE_INFO_BLOCK_START)
    {
        throw new StateLoadError("Invalid length: " + len);
    }

    var header_block = new Int32Array(state, 0, 4);

    if(header_block[STATE_INDEX_MAGIC] !== STATE_MAGIC)
    {
        throw new StateLoadError("Invalid header: " + h(header_block[STATE_INDEX_MAGIC] >>> 0));
    }

    if(header_block[STATE_INDEX_VERSION] !== STATE_VERSION)
    {
        throw new StateLoadError(
                "Version mismatch: dump=" + header_block[STATE_INDEX_VERSION] +
                " we=" + STATE_VERSION);
    }

    if(header_block[STATE_INDEX_TOTAL_LEN] !== len)
    {
        throw new StateLoadError(
                "Length doesn't match header: " +
                "real=" + len + " header=" + header_block[STATE_INDEX_TOTAL_LEN]);
    }

    var info_block_len = header_block[STATE_INDEX_INFO_LEN];

    if(info_block_len < 0 ||
       info_block_len + 12 >= len ||
       info_block_len % 2)
    {
        throw new StateLoadError("Invalid info block length: " + info_block_len);
    }

    var info_block_str_len = info_block_len / 2;
    var info_block_buffer = new Uint16Array(state, STATE_INFO_BLOCK_START, info_block_str_len);
    var info_block = "";

    for(var i = 0; i < info_block_str_len - 8; )
    {
        info_block += String.fromCharCode(
            info_block_buffer[i++], info_block_buffer[i++],
            info_block_buffer[i++], info_block_buffer[i++],
            info_block_buffer[i++], info_block_buffer[i++],
            info_block_buffer[i++], info_block_buffer[i++]
        );
    }

    for(; i < info_block_str_len; )
    {
        info_block += String.fromCharCode(info_block_buffer[i++]);
    }

    var info_block_obj = JSON.parse(info_block);
    var buffer_block_start = STATE_INFO_BLOCK_START + info_block_len;
    var buffer_infos = info_block_obj.buffer_infos;

    for(var i = 0; i < buffer_infos.length; i++)
    {
        buffer_infos[i].offset += buffer_block_start;
    }

    var buffers = {
        full: state,
        infos: buffer_infos,
    };

    restore_object(this, info_block_obj.state, buffers);
};
<commit_msg>more useful assert messages<commit_after>"use strict";

/** @const */
var STATE_VERSION = 0;

/** @const */
var STATE_MAGIC = 0x86768676|0;

/** @const */
var STATE_INDEX_MAGIC = 0;

/** @const */
var STATE_INDEX_VERSION = 1;

/** @const */
var STATE_INDEX_TOTAL_LEN = 2;

/** @const */
var STATE_INDEX_INFO_LEN = 3;

/** @const */
var STATE_INFO_BLOCK_START = 16;

/** @constructor */
function StateLoadError(msg)
{
    this.message = msg;
}
StateLoadError.prototype = new Error;

function save_object(obj, arraybuffers)
{
    // recursively create a structure that can be json-dumped, pushing
    // arraybuffers into the second argument

    if(typeof obj !== "object" || obj === null || obj instanceof Array)
    {
        return obj;
    }

    if(obj.constructor === Object)
    {
        var keys = Object.keys(obj);
        var result = {};

        for(var i = 0; i < keys.length; i++)
        {
            var key = keys[i];
            result[key] = save_object(obj[key], arraybuffers);
        }

        return result;
    }

    if(obj.BYTES_PER_ELEMENT)
    {
        // Uint8Array, etc.
        return {
            __state_type__: obj.constructor.name,
            buffer_id: arraybuffers.push(obj.buffer) - 1,
        };
    }

    if(obj instanceof ArrayBuffer)
    {
        return {
            __state_type__: "ArrayBuffer",
            buffer_id: arraybuffers.push(obj) - 1,
        };
    }

    var skip = Array.setify(obj._state_skip || []);
    skip["_state_skip"] = true;

    var keys = Object.keys(obj);
    var result = {};

    for(var i = 0; i < keys.length; i++)
    {
        var key = keys[i];

        if(skip[key])
        {
            continue;
        }

        var value = obj[key];

        if(typeof value === "function")
        {
            continue;
        }

        result[key] = save_object(value, arraybuffers);
    }

    return result;
}

function restore_object(base, obj, buffers)
{
    // recurisvely restore obj into base

    if(typeof obj !== "object" || obj instanceof Array || obj === null)
    {
        return obj;
    }

    var type = obj.__state_type__;

    if(type === undefined)
    {
        var keys = Object.keys(obj);

        if(DEBUG && base === undefined)
        {
            console.log("Cannot restore (base doesn't exist)", obj);
            dbg_assert(false);
        }

        for(var i = 0; i < keys.length; i++)
        {
            var key = keys[i];
            base[key] = restore_object(base[key], obj[key], buffers);
        }

        if(base._state_restore)
        {
            base._state_restore();
        }

        return base;
    }
    else if(type === "ArrayBuffer")
    {
        var info = buffers.infos[obj.buffer_id];

        if(base && base.byteLength === info.length)
        {
            new Uint8Array(base).set(new Uint8Array(buffers.full, info.offset, info.length));
        }
        else
        {
            //base = buffers.full.slice(info.offset, info.offset + info.length);
            dbg_assert(false, base ? "buffer of different size" : "no buffer");
        }

        return base;
    }
    else
    {
        var table = {
            "Uint8Array": Uint8Array,
            "Int8Array": Int8Array,
            "Uint16Array": Uint16Array,
            "Int16Array": Int16Array,
            "Uint32Array": Uint32Array,
            "Int32Array": Int32Array,
            "Float32Array": Float32Array,
            "Float64Array": Float64Array,
        };

        var constructor = table[type];
        dbg_assert(constructor, "Unkown type: " + type);

        var info = buffers.infos[obj.buffer_id];

        // avoid a new allocation if possible
        if(base &&
           base.constructor === constructor &&
           base.byteOffset === 0 &&
           base.byteLength === info.length)
        {
            new Uint8Array(base.buffer).set(
                new Uint8Array(buffers.full, info.offset, info.length),
                base.byteOffset
            );
            return base;
        }
        else
        {
            var buf = buffers.full.slice(info.offset, info.offset + info.length);
            return new constructor(buf);
        }
    }
}

CPU.prototype.save_state = function()
{
    var arraybuffers = [];
    var state = save_object(this, arraybuffers);

    var buffer_infos = [];
    var total_buffer_size = 0;

    for(var i = 0; i < arraybuffers.length; i++)
    {
        var len = arraybuffers[i].byteLength;

        buffer_infos[i] = {
            offset: total_buffer_size,
            length: len,
        };

        total_buffer_size += len;

        // align
        total_buffer_size = total_buffer_size + 3 & ~3;
    }

    var info_object = JSON.stringify({
        buffer_infos: buffer_infos,
        state: state,
    });

    var buffer_block_start = STATE_INFO_BLOCK_START + 2 * info_object.length;
    var total_size = buffer_block_start + total_buffer_size;

    var result = new ArrayBuffer(total_size);

    var header_block = new Int32Array(
        result,
        0,
        STATE_INFO_BLOCK_START / 4
    );
    var info_block = new Uint16Array(
        result,
        STATE_INFO_BLOCK_START,
        info_object.length
    );
    var buffer_block = new Uint8Array(
        result,
        buffer_block_start
    );

    header_block[STATE_INDEX_MAGIC] = STATE_MAGIC;
    header_block[STATE_INDEX_VERSION] = STATE_VERSION;
    header_block[STATE_INDEX_TOTAL_LEN] = total_size;
    header_block[STATE_INDEX_INFO_LEN] = info_object.length * 2;

    for(var i = 0; i < info_object.length; i++)
    {
        info_block[i] = info_object.charCodeAt(i);
    }

    for(var i = 0; i < arraybuffers.length; i++)
    {
        var buffer = arraybuffers[i];
        buffer_block.set(new Uint8Array(buffer), buffer_infos[i].offset);
    }

    return result;
};

CPU.prototype.restore_state = function(state)
{
    var len = state.byteLength;

    if(len < STATE_INFO_BLOCK_START)
    {
        throw new StateLoadError("Invalid length: " + len);
    }

    var header_block = new Int32Array(state, 0, 4);

    if(header_block[STATE_INDEX_MAGIC] !== STATE_MAGIC)
    {
        throw new StateLoadError("Invalid header: " + h(header_block[STATE_INDEX_MAGIC] >>> 0));
    }

    if(header_block[STATE_INDEX_VERSION] !== STATE_VERSION)
    {
        throw new StateLoadError(
                "Version mismatch: dump=" + header_block[STATE_INDEX_VERSION] +
                " we=" + STATE_VERSION);
    }

    if(header_block[STATE_INDEX_TOTAL_LEN] !== len)
    {
        throw new StateLoadError(
                "Length doesn't match header: " +
                "real=" + len + " header=" + header_block[STATE_INDEX_TOTAL_LEN]);
    }

    var info_block_len = header_block[STATE_INDEX_INFO_LEN];

    if(info_block_len < 0 ||
       info_block_len + 12 >= len ||
       info_block_len % 2)
    {
        throw new StateLoadError("Invalid info block length: " + info_block_len);
    }

    var info_block_str_len = info_block_len / 2;
    var info_block_buffer = new Uint16Array(state, STATE_INFO_BLOCK_START, info_block_str_len);
    var info_block = "";

    for(var i = 0; i < info_block_str_len - 8; )
    {
        info_block += String.fromCharCode(
            info_block_buffer[i++], info_block_buffer[i++],
            info_block_buffer[i++], info_block_buffer[i++],
            info_block_buffer[i++], info_block_buffer[i++],
            info_block_buffer[i++], info_block_buffer[i++]
        );
    }

    for(; i < info_block_str_len; )
    {
        info_block += String.fromCharCode(info_block_buffer[i++]);
    }

    var info_block_obj = JSON.parse(info_block);
    var buffer_block_start = STATE_INFO_BLOCK_START + info_block_len;
    var buffer_infos = info_block_obj.buffer_infos;

    for(var i = 0; i < buffer_infos.length; i++)
    {
        buffer_infos[i].offset += buffer_block_start;
    }

    var buffers = {
        full: state,
        infos: buffer_infos,
    };

    restore_object(this, info_block_obj.state, buffers);
};
<|endoftext|>


<commit_before>'use strict';

import { load, save } from './save';

export const initial = () => ({ questions: [] });

const DATA_URL = 'http://seanastephens.github.io/javaranch-data/questions.v2.json';
export const loadQuestions = () => fetch(DATA_URL).then(d => d.json());

export const reset = () => save({});

export const markCorrect = ({ questions }) => {
  console.log(Object.keys(load()));
  save(Object.assign(load(), { [questions[0].id]: true }));
  return { questions: questions.slice(1) };
};

export const markWrong = ({ questions }) => ({
  questions: questions.slice(1).concat([questions[0]])
});
<commit_msg>Deduplicate question loading<commit_after>'use strict';

import { load, save } from './save';

export const initial = () => ({ questions: [] });

const DATA_URL = 'http://seanastephens.github.io/javaranch-data/questions.v2.json';
let questions = null;
export const loadQuestions = () => {
  if(!questions) {
    return fetch(DATA_URL)
      .then(d => d.json())
      .then(q => {
        questions = q;
        return Promise.resolve(questions);
      });
  }
  return Promise.resolve(questions);
};

export const reset = () => save({});

export const markCorrect = ({ questions }) => {
  console.log(Object.keys(load()));
  save(Object.assign(load(), { [questions[0].id]: true }));
  return { questions: questions.slice(1) };
};

export const markWrong = ({ questions }) => ({
  questions: questions.slice(1).concat([questions[0]])
});
<|endoftext|>


<commit_before>const env = require('../utils/env');
const should = env.should;
const Path = require('path');
const stubs = require('../utils/stubs');
const render = require('../../module/render.js');
const sinon = require('sinon');
const assert = require('assert');
const config = require('../../config.js');
const wmd = require('../../module/wmd');
const Static = require('../../app/static');

describe('static', function() {
    var mods, sttc, cfg;

    before(function() {
        cfg = config.factory(stubs.brickConfig);
        render.register('hbs', stubs.hbs);
    });

    it('should get simple CSS', function() {
        mods = [wmd.loadModule(Path.resolve(cfg.root, 'simple'), cfg)];
        sttc = Static(mods, cfg.static);
        var result = '/* module: simple */\n.brk-simple div {\n' +
            '  color: red;\n}\n\n';
        return sttc.getCss().should.eventually.equal(result);
    });

    it('should handle null CSS', function() {
        mods = [wmd.loadModule(Path.resolve(cfg.root, 'fs'), cfg)];
        sttc = Static(mods, cfg.static);
        var result = '/* module: fs */\n\n';
        return sttc.getCss().should.eventually.equal(result);
    });

    it('should get simple JS', function() {
        mods = [wmd.loadModule(Path.resolve(cfg.root, 'simple'), cfg)];
        sttc = Static(mods, cfg.static);
        var result = "// module: simple\nwindow.brk.simple=function(brk){\n"+
            "console.log('am loaded');\n};";
        return sttc.getJs().then(js => {
            return js.split('\n').slice(5).join('\n').trim();
        }).should.eventually.equal(result);
    });

    it('should handle null JS', function() {
        mods = [wmd.loadModule(Path.resolve(cfg.root, 'fs'), cfg)];
        sttc = Static(mods, cfg.static);
        var result = "// module: fs\nwindow.brk.fs=function(brk){\n};";
        return sttc.getJs().then(js => {
            return js.split('\n').slice(5).join('\n').trim();
        }).should.eventually.equal(result);
    });
});

<commit_msg>update test: module -> brick<commit_after>const env = require('../utils/env');
const should = env.should;
const Path = require('path');
const stubs = require('../utils/stubs');
const render = require('../../module/render.js');
const sinon = require('sinon');
const assert = require('assert');
const config = require('../../config.js');
const wmd = require('../../module/wmd');
const Static = require('../../app/static');

describe('static', function() {
    var mods, sttc, cfg;

    before(function() {
        cfg = config.factory(stubs.brickConfig);
        render.register('hbs', stubs.hbs);
    });

    it('should get simple CSS', function() {
        mods = [wmd.loadModule(Path.resolve(cfg.root, 'simple'), cfg)];
        sttc = Static(mods, cfg.static);
        var result = '/* brick: simple */\n.brk-simple div {\n' +
            '  color: red;\n}\n\n';
        return sttc.getCss().should.eventually.equal(result);
    });

    it('should handle null CSS', function() {
        mods = [wmd.loadModule(Path.resolve(cfg.root, 'fs'), cfg)];
        sttc = Static(mods, cfg.static);
        var result = '/* brick: fs */\n\n';
        return sttc.getCss().should.eventually.equal(result);
    });

    it('should get simple JS', function() {
        mods = [wmd.loadModule(Path.resolve(cfg.root, 'simple'), cfg)];
        sttc = Static(mods, cfg.static);
        var result = "// brick: simple\nwindow.brk.simple=function(brk){\n"+
            "console.log('am loaded');\n};";
        return sttc.getJs().then(js => {
            return js.split('\n').slice(5).join('\n').trim();
        }).should.eventually.equal(result);
    });

    it('should handle null JS', function() {
        mods = [wmd.loadModule(Path.resolve(cfg.root, 'fs'), cfg)];
        sttc = Static(mods, cfg.static);
        var result = "// brick: fs\nwindow.brk.fs=function(brk){\n};";
        return sttc.getJs().then(js => {
            return js.split('\n').slice(5).join('\n').trim();
        }).should.eventually.equal(result);
    });
});

<|endoftext|>


<commit_before>// Test CRUD + append, prepend, item, slice for arrays

var assert = require('assert'),
    vows = require('vows'),
    databank = require('../lib/databank'),
    Databank = databank.Databank,
    driverParams = require('./driver-params').driverParams;

var arrayContext = function(driver, params) {

    var context = {};

    context["When we create a " + driver + " databank"] = {

        topic: function() {
            params.schema = {
                inbox: {
                    pkey: 'username'
                }
            };
            return Databank.get(driver, params);
        },
        'We can connect to it': {
            topic: function(bank) {
                bank.connect(params, this.callback);
            },
            'without an error': function(err) {
                assert.ifError(err);
            },
            'and we can insert an array': {
                topic: function(bank) {
                    bank.create('inbox', 'evanp', [1, 2, 3], this.callback);
                },
                'without an error': function(err, value) {
                    assert.ifError(err);
                    assert.isArray(value);
                    assert.equal(value.length, 3);
		    assert.deepEqual(value, [1, 2, 3]);
                },
                'and we can fetch it': {
                    topic: function(created, bank) {
                        bank.read('inbox', 'evanp', this.callback);
                    },
                    'without an error': function(err, value) {
			assert.ifError(err);
			assert.isArray(value);
			assert.equal(value.length, 3);
			assert.deepEqual(value, [1, 2, 3]);
                    },
                    'and we can update it': {
                        topic: function(read, created, bank) {
                            bank.update('inbox', 'evanp', [1, 2, 3, 4], this.callback);
                        },
                        'without an error': function(err, value) {
			    assert.ifError(err);
			    assert.isArray(value);
			    assert.equal(value.length, 4);
			    assert.deepEqual(value, [1, 2, 3, 4]);
                        },
                        'and we can read it again': {
                            topic: function(updated, read, created, bank) {
				bank.read('inbox', 'evanp', this.callback);
                            },
                            'without an error': function(err, value) {
				assert.ifError(err);
				assert.isArray(value);
				assert.equal(value.length, 4);
				assert.deepEqual(value, [1, 2, 3, 4]);
                            },
                            'and we can prepend to it': {
                                topic: function(readAgain, updated, read, created, bank) {
				    bank.prepend('inbox', 'evanp', 0, this.callback);
                                },
                                'without an error': function(err, value) {
				    assert.ifError(err);
				    assert.isArray(value);
				    assert.equal(value.length, 5);
				    assert.deepEqual(value, [0, 1, 2, 3, 4]);
				},
				'and we can append to it': {
                                    topic: function(prepended, readAgain, updated, read, created, bank) {
					bank.append('inbox', 'evanp', 5, this.callback);
                                    },
                                    'without an error': function(err, value) {
					assert.ifError(err);
					assert.isArray(value);
					assert.equal(value.length, 6);
					assert.deepEqual(value, [0, 1, 2, 3, 4, 5]);
				    },
				    'and we can get a single item': {
					topic: function(appended, prepended, readAgain, updated, read, created, bank) {
					    bank.item('inbox', 'evanp', 2, this.callback);
					},
					'without an error': function(err, value) {
					    assert.ifError(err);
					    assert.equal(value, 2);
					},
					'and we can get a slice': {
					    topic: function(item, appended, prepended, readAgain, updated, read, created, bank) {
					        bank.slice('inbox', 'evanp', 1, 3, this.callback);
					    },
					    'without an error': function(err, value) {
						assert.ifError(err);
					        assert.isArray(value);
					        assert.equal(value.length, 2);
					        assert.deepEqual(value, [1, 2]);
					    },
					    'and we can delete it': {
					        topic: function(slice, item, appended, prepended, readAgain, updated, read, created, bank) {
					            bank.del('inbox', 'evanp', this.callback);
					        },
					        'without an error': function(err) {
						    assert.ifError(err);
                                                },
                                                'and we can disconnect': {
					            topic: function(slice, item, appended, prepended, readAgain, updated, read, created, bank) {
					                bank.disconnect(this.callback);
                                                    },
					            'without an error': function(err) {
						        assert.ifError(err);
                                                    }
                                                }
                                            }
					}
				    }
                                }
                            }
                        }
                    }
                }
            }
        }
    };

    return context;
};

var suite = vows.describe('array values'),
    driver = null;

for (driver in driverParams) {
    suite.addBatch(arrayContext(driver, driverParams[driver]));
}

suite.export(module);
<commit_msg>Test indexOf() and remove()<commit_after>// Test CRUD + append, prepend, item, slice for arrays

var assert = require('assert'),
    vows = require('vows'),
    databank = require('../lib/databank'),
    Databank = databank.Databank,
    driverParams = require('./driver-params').driverParams;

var arrayContext = function(driver, params) {

    var context = {};

    context["When we create a " + driver + " databank"] = {

        topic: function() {
            params.schema = {
                inbox: {
                    pkey: 'username'
                }
            };
            return Databank.get(driver, params);
        },
        'We can connect to it': {
            topic: function(bank) {
                bank.connect(params, this.callback);
            },
            'without an error': function(err) {
                assert.ifError(err);
            },
            'and we can insert an array': {
                topic: function(bank) {
                    bank.create('inbox', 'evanp', [1, 2, 3], this.callback);
                },
                'without an error': function(err, value) {
                    assert.ifError(err);
                    assert.isArray(value);
                    assert.equal(value.length, 3);
		    assert.deepEqual(value, [1, 2, 3]);
                },
                'and we can fetch it': {
                    topic: function(created, bank) {
                        bank.read('inbox', 'evanp', this.callback);
                    },
                    'without an error': function(err, value) {
			assert.ifError(err);
			assert.isArray(value);
			assert.equal(value.length, 3);
			assert.deepEqual(value, [1, 2, 3]);
                    },
                    'and we can update it': {
                        topic: function(read, created, bank) {
                            bank.update('inbox', 'evanp', [1, 2, 3, 4], this.callback);
                        },
                        'without an error': function(err, value) {
			    assert.ifError(err);
			    assert.isArray(value);
			    assert.equal(value.length, 4);
			    assert.deepEqual(value, [1, 2, 3, 4]);
                        },
                        'and we can read it again': {
                            topic: function(updated, read, created, bank) {
				bank.read('inbox', 'evanp', this.callback);
                            },
                            'without an error': function(err, value) {
				assert.ifError(err);
				assert.isArray(value);
				assert.equal(value.length, 4);
				assert.deepEqual(value, [1, 2, 3, 4]);
                            },
                            'and we can prepend to it': {
                                topic: function(readAgain, updated, read, created, bank) {
				    bank.prepend('inbox', 'evanp', 0, this.callback);
                                },
                                'without an error': function(err, value) {
				    assert.ifError(err);
				    assert.isArray(value);
				    assert.equal(value.length, 5);
				    assert.deepEqual(value, [0, 1, 2, 3, 4]);
				},
				'and we can append to it': {
                                    topic: function(prepended, readAgain, updated, read, created, bank) {
					bank.append('inbox', 'evanp', 5, this.callback);
                                    },
                                    'without an error': function(err, value) {
					assert.ifError(err);
					assert.isArray(value);
					assert.equal(value.length, 6);
					assert.deepEqual(value, [0, 1, 2, 3, 4, 5]);
				    },
				    'and we can get a single item': {
					topic: function(appended, prepended, readAgain, updated, read, created, bank) {
					    bank.item('inbox', 'evanp', 2, this.callback);
					},
					'without an error': function(err, value) {
					    assert.ifError(err);
					    assert.equal(value, 2);
					},
					'and we can get a slice': {
					    topic: function(item, appended, prepended, readAgain, updated, read, created, bank) {
					        bank.slice('inbox', 'evanp', 1, 3, this.callback);
					    },
					    'without an error': function(err, value) {
						assert.ifError(err);
					        assert.isArray(value);
					        assert.equal(value.length, 2);
					        assert.deepEqual(value, [1, 2]);
					    },
                                            'and we can get the indexOf an item': {
                                                topic: function(slice, item, appended, prepended, readAgain, updated, read, created, bank) {
                                                    bank.indexOf('inbox', 'evanp', 2, this.callback);
                                                },
                                                'without an error': function(err, index) {
                                                    assert.ifError(err);
                                                    assert.equal(index, 2);
                                                },
                                                'and we can remove an item': {
					            topic: function(index, slice, item, appended, prepended, readAgain, updated, read, created, bank) {
                                                        bank.remove('inbox', 'evanp', 3, this.callback);
                                                    },
                                                    'without an error': function(err) {
                                                        assert.ifError(err);
                                                    },
                                                    'and we can read again': {
					                topic: function(index, slice, item, appended, prepended, readAgain, updated, read, created, bank) {
                                                            bank.read('inbox', 'evanp', this.callback);
                                                        },
                                                        'without an error': function(err, box) {
                                                            assert.ifError(err);
                                                            assert.deepEqual(box, [0, 1, 2, 4, 5]);
                                                        },
					                'and we can delete it': {
					                    topic: function(readAgainAgain, index, slice, item, appended, prepended, readAgain, updated, read, created, bank) {
					                        bank.del('inbox', 'evanp', this.callback);
					                    },
					                    'without an error': function(err) {
						                assert.ifError(err);
                                                            },
                                                            'and we can disconnect': {
					                        topic: function(readAgainAgain, index, slice, item, appended, prepended, readAgain, updated, read, created, bank) {
					                            bank.disconnect(this.callback);
                                                                },
					                        'without an error': function(err) {
						                    assert.ifError(err);
                                                                }
                                                            }
                                                        }
					            }
                                                }
				    }
                                }
                            }
                        }
                    }
                }
            }
        }
    };

    return context;
};

var suite = vows.describe('array values'),
    driver = null;

for (driver in driverParams) {
    suite.addBatch(arrayContext(driver, driverParams[driver]));
}

suite.export(module);
<|endoftext|>


<commit_before>/*global describe, it*/
var expect = require('../unexpected-with-plugins'),
    sinon = require('sinon'),
    AssetGraph = require('../../lib');

describe('assets/Css', function () {
    it('should handle a test case with a parse error in an inline Css asset', function (done) {
        var err;
        new AssetGraph({root: __dirname + '/../../testdata/assets/Css/parseErrors/'})
            .on('warn', function (_err) {
                err = _err;
            })
            .loadAssets('parseErrorInInlineCss.html')
            .queue(function () {
                expect(err, 'to be an', Error);
                expect(err.message, 'to match', /parseErrorInInlineCss\.html/);
            })
            .run(done);
    });

    it('should handle a test case with a parse error in an external Css asset', function (done) {
        var err;
        new AssetGraph({root: __dirname + '/../../testdata/assets/Css/parseErrors/'})
            .on('warn', function (_err) {
                err = _err;
            })
            .loadAssets('parseErrorInExternalCss.html')
            .populate()
            .queue(function (assetGraph) {
                expect(err, 'to be an', Error);
                expect(err.message, 'to match', /parseError\.css/);
            })
            .run(done);
    });

    it('should handle a test case that has multiple neighbour @font-face rules', function (done) {
        new AssetGraph({root: __dirname + '/../../testdata/assets/Css/multipleFontFaceRules/'})
            .loadAssets('index.css')
            .populate()
            .queue(function (assetGraph) {
                expect(assetGraph, 'to contain asset', 'Css');
                expect(assetGraph.findAssets({type: 'Css'})[0].text.match(/@font-face/g), 'to have length', 3);

                assetGraph.findAssets({type: 'Css'})[0].markDirty();
                expect(assetGraph.findAssets({type: 'Css'})[0].text.match(/@font-face/g), 'to have length', 3);
            })
            .run(done);
    });

    it('should get the default encoding when there is no other way to determine encoding', function () {
        var asset = new AssetGraph.Css({});

        expect(asset.encoding, 'to be', AssetGraph.Text.prototype.defaultEncoding);
    });

    it('should get set a new encoding correctly', function () {
        var asset = new AssetGraph.Css({
            encoding: 'utf-8',
            text: 'body:before { content: "🐮"; }'
        });

        var markDirtySpy = sinon.spy(asset, 'markDirty');

        asset.encoding = 'iso-8859-1';

        expect(markDirtySpy, 'was called once');
        expect(asset.encoding, 'to be', 'iso-8859-1');
    });

    it('should minify Css text', function () {
        var cssText = 'body {\n    background: red;\n}\n';
        var asset = new AssetGraph.Css({
            text: cssText
        });

        expect(asset.text, 'to be', cssText);

        asset.minify();
        expect(asset.text, 'to be', 'body{background:red}');
    });

    it('should pretty print Css text', function () {
        var cssText = 'body{background:red}';
        var asset = new AssetGraph.Css({
            text: cssText
        });

        expect(asset.text, 'to be', cssText);

        asset.prettyPrint();
        expect(asset.text, 'to be', 'body {background: red;}\n');
    });

    it('should throw an error on completely invalid CSS', function () {
        var asset = new AssetGraph.Css({
            text: 'body {}'
        });
        function getParseTree() {
            return asset.parseTree;
        }

        expect(getParseTree, 'not to throw');

        asset.text = '}';

        expect(getParseTree, 'to throw');
    });

    it('should emit an error on completely invalid CSS if the asset is part of an assetGraph', function () {
        var assetGraph = new AssetGraph();
        var asset = new AssetGraph.Css({
            text: 'body {}'
        });
        function getParseTree() {
            return asset.parseTree;
        }

        assetGraph.addAsset(asset);
        var emitter = sinon.spy(assetGraph, 'emit');

        expect(getParseTree, 'not to throw');
        expect(emitter, 'was not called');

        asset.text = '}';

        expect(emitter, 'was called once');
    });

    it('should update the text of a Css asset when setting parseTree', function () {
        var cssText = 'body {}';
        var first = new AssetGraph.Css({
            text: 'h1 {}'
        });
        var second = new AssetGraph.Css({
            text: cssText
        });

        var unloadSpy = sinon.spy(first, 'unload');
        var markDirtySpy = sinon.spy(first, 'markDirty');

        first.parseTree = second.parseTree;

        expect(unloadSpy, 'was called once');
        expect(markDirtySpy, 'was called once');

        console.log(first.parseTree.toString());
        expect(first.text, 'to be', cssText);
    });
});
<commit_msg>Fix Css parseTree setter test<commit_after>/*global describe, it*/
var expect = require('../unexpected-with-plugins'),
    sinon = require('sinon'),
    AssetGraph = require('../../lib');

describe('assets/Css', function () {
    it('should handle a test case with a parse error in an inline Css asset', function (done) {
        var err;
        new AssetGraph({root: __dirname + '/../../testdata/assets/Css/parseErrors/'})
            .on('warn', function (_err) {
                err = _err;
            })
            .loadAssets('parseErrorInInlineCss.html')
            .queue(function () {
                expect(err, 'to be an', Error);
                expect(err.message, 'to match', /parseErrorInInlineCss\.html/);
            })
            .run(done);
    });

    it('should handle a test case with a parse error in an external Css asset', function (done) {
        var err;
        new AssetGraph({root: __dirname + '/../../testdata/assets/Css/parseErrors/'})
            .on('warn', function (_err) {
                err = _err;
            })
            .loadAssets('parseErrorInExternalCss.html')
            .populate()
            .queue(function (assetGraph) {
                expect(err, 'to be an', Error);
                expect(err.message, 'to match', /parseError\.css/);
            })
            .run(done);
    });

    it('should handle a test case that has multiple neighbour @font-face rules', function (done) {
        new AssetGraph({root: __dirname + '/../../testdata/assets/Css/multipleFontFaceRules/'})
            .loadAssets('index.css')
            .populate()
            .queue(function (assetGraph) {
                expect(assetGraph, 'to contain asset', 'Css');
                expect(assetGraph.findAssets({type: 'Css'})[0].text.match(/@font-face/g), 'to have length', 3);

                assetGraph.findAssets({type: 'Css'})[0].markDirty();
                expect(assetGraph.findAssets({type: 'Css'})[0].text.match(/@font-face/g), 'to have length', 3);
            })
            .run(done);
    });

    it('should get the default encoding when there is no other way to determine encoding', function () {
        var asset = new AssetGraph.Css({});

        expect(asset.encoding, 'to be', AssetGraph.Text.prototype.defaultEncoding);
    });

    it('should get set a new encoding correctly', function () {
        var asset = new AssetGraph.Css({
            encoding: 'utf-8',
            text: 'body:before { content: "🐮"; }'
        });

        var markDirtySpy = sinon.spy(asset, 'markDirty');

        asset.encoding = 'iso-8859-1';

        expect(markDirtySpy, 'was called once');
        expect(asset.encoding, 'to be', 'iso-8859-1');
    });

    it('should minify Css text', function () {
        var cssText = 'body {\n    background: red;\n}\n';
        var asset = new AssetGraph.Css({
            text: cssText
        });

        expect(asset.text, 'to be', cssText);

        asset.minify();
        expect(asset.text, 'to be', 'body{background:red}');
    });

    it('should pretty print Css text', function () {
        var cssText = 'body{background:red}';
        var asset = new AssetGraph.Css({
            text: cssText
        });

        expect(asset.text, 'to be', cssText);

        asset.prettyPrint();
        expect(asset.text, 'to be', 'body {background: red;}\n');
    });

    it('should throw an error on completely invalid CSS', function () {
        var asset = new AssetGraph.Css({
            text: 'body {}'
        });
        function getParseTree() {
            return asset.parseTree;
        }

        expect(getParseTree, 'not to throw');

        asset.text = '}';

        expect(getParseTree, 'to throw');
    });

    it('should emit an error on completely invalid CSS if the asset is part of an assetGraph', function () {
        var assetGraph = new AssetGraph();
        var asset = new AssetGraph.Css({
            text: 'body {}'
        });
        function getParseTree() {
            return asset.parseTree;
        }

        assetGraph.addAsset(asset);
        var emitter = sinon.spy(assetGraph, 'emit');

        expect(getParseTree, 'not to throw');
        expect(emitter, 'was not called');

        asset.text = '}';

        expect(emitter, 'was called once');
    });

    it('should update the text of a Css asset when setting parseTree', function () {
        var cssText = 'h1{color:hotpink}';
        var first = new AssetGraph.Css({
            text: 'h1{color:red}'
        });
        var second = new AssetGraph.Css({
            text: cssText
        });

        var unloadSpy = sinon.spy(first, 'unload');
        var markDirtySpy = sinon.spy(first, 'markDirty');

        first.parseTree = second.parseTree;

        expect(unloadSpy, 'was called once');
        expect(markDirtySpy, 'was called once');

        expect(first.text, 'to be', cssText);
    });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var basic = require('./data/watershed');
var char11 = require('./data/watershed-11chars');
var specialChar = require('./data/watershed-specialCharacters');
var utf = require('./data/utf.json');
var dbf = require('../');
require('chai').should();
function toArrayBuffer(buffer) {
    return buffer;
}
describe('dbf',function(){
	it('should work',function(done){
		fs.readFile('./test/data/watershed.dbf',function(err,data){
			if(err){
				return done(err);
			}
			dbf(data).should.deep.equal(basic);
			done();
		});
	});
  it('should handle 11 charicter field names',function(done){
		fs.readFile('./test/data/watershed-11chars.dbf',function(err,data){
			if(err){
				return done(err);
			}
			dbf(data).should.deep.equal(char11);
			done();
		});
	});
  it('should handle special characters',function(done){
    fs.readFile('./test/data/watershed-specialCharacters.dbf',function(err,data){
      if(err){
        return done(err);
      }
      dbf(data).should.deep.equal(specialChar);
      done();
    });
  });
  it('should handle an empty / null dbf file',function(done){
    fs.readFile('./test/data/empty.dbf',function(err,data){
      if(err){
        return done(err);
      }
      dbf(data).should.deep.equal([{}, {}]);
      done();
    });
  });
  it('should handle utf charicters',function(done){
    fs.readFile('./test/data/utf.dbf',function(err,data){
      if(err){
        return done(err);
      }
      dbf(data).should.deep.equal(utf);
      dbf(data, 'UTF-8').should.deep.equal(utf);
      done();
    });
  });
  it('should handle other charicters',function(done){
    fs.readFile('./test/data/codepage.dbf',function(err,data){
      if(err){
        return done(err);
      }
      dbf(data)[1].should.not.deep.equal(utf[1]);
      dbf(data, '1250')[1].should.deep.equal(utf[1]);
      done();
    });
  });
});
<commit_msg>forgot a field<commit_after>var fs = require('fs');
var basic = require('./data/watershed');
var char11 = require('./data/watershed-11chars');
var specialChar = require('./data/watershed-specialCharacters');
var utf = [
  {
    field: '💩'
  },
  {
    field: 'Hněvošický háj'
  }
]
var dbf = require('../');
require('chai').should();
function toArrayBuffer(buffer) {
    return buffer;
}
describe('dbf',function(){
	it('should work',function(done){
		fs.readFile('./test/data/watershed.dbf',function(err,data){
			if(err){
				return done(err);
			}
			dbf(data).should.deep.equal(basic);
			done();
		});
	});
  it('should handle 11 charicter field names',function(done){
		fs.readFile('./test/data/watershed-11chars.dbf',function(err,data){
			if(err){
				return done(err);
			}
			dbf(data).should.deep.equal(char11);
			done();
		});
	});
  it('should handle special characters',function(done){
    fs.readFile('./test/data/watershed-specialCharacters.dbf',function(err,data){
      if(err){
        return done(err);
      }
      dbf(data).should.deep.equal(specialChar);
      done();
    });
  });
  it('should handle an empty / null dbf file',function(done){
    fs.readFile('./test/data/empty.dbf',function(err,data){
      if(err){
        return done(err);
      }
      dbf(data).should.deep.equal([{}, {}]);
      done();
    });
  });
  it('should handle utf charicters',function(done){
    fs.readFile('./test/data/utf.dbf',function(err,data){
      if(err){
        return done(err);
      }
      dbf(data).should.deep.equal(utf);
      dbf(data, 'UTF-8').should.deep.equal(utf);
      done();
    });
  });
  it('should handle other charicters',function(done){
    fs.readFile('./test/data/codepage.dbf',function(err,data){
      if(err){
        return done(err);
      }
      dbf(data)[1].should.not.deep.equal(utf[1]);
      dbf(data, '1250')[1].should.deep.equal(utf[1]);
      done();
    });
  });
});
<|endoftext|>


<commit_before>import test from 'ava'
import { resolve } from 'path'
import rp from 'request-promise-native'
import stdMocks from 'std-mocks'
import { Nuxt, Builder } from '../index.js'

const port = 4003
const url = (route) => 'http://localhost:' + port + route

let nuxt = null

// Init nuxt.js and create server listening on localhost:4000
test.before('Init Nuxt.js', async t => {
  const options = {
    rootDir: resolve(__dirname, 'fixtures/basic'),
    dev: false
  }
  nuxt = new Nuxt(options)
  await new Builder(nuxt).build()

  await nuxt.listen(port, 'localhost')
})

test('/stateless', async t => {
  const { html } = await nuxt.renderRoute('/stateless')
  t.true(html.includes('
My component!
'))
})

/*
** Example of testing via dom checking
*/
test('/css', async t => {
  const window = await nuxt.renderAndGetWindow(url('/css'))
  const element = window.document.querySelector('.red')
  t.not(element, null)
  t.is(element.textContent, 'This is red')
  t.is(element.className, 'red')
  t.is(window.getComputedStyle(element).color, 'red')
})

test('/stateful', async t => {
  const { html } = await nuxt.renderRoute('/stateful')
  t.true(html.includes('

The answer is 42

'))
})

test('/store', async t => {
  const { html } = await nuxt.renderRoute('/store')
  t.true(html.includes('
Vuex Nested Modules
'))
  t.true(html.includes('
1
'))
})

test('/head', async t => {
  const window = await nuxt.renderAndGetWindow(url('/head'), { virtualConsole: false })
  const html = window.document.body.innerHTML
  const metas = window.document.getElementsByTagName('meta')
  t.is(window.document.title, 'My title')
  t.is(metas[0].getAttribute('content'), 'my meta')
  t.true(html.includes('

I can haz meta tags

'))
})

test('/async-data', async t => {
  const { html } = await nuxt.renderRoute('/async-data')
  t.true(html.includes('
Nuxt.js
'))
})

test('/await-async-data', async t => {
  const { html } = await nuxt.renderRoute('/await-async-data')
  t.true(html.includes('
Await Nuxt.js
'))
})

test('/callback-async-data', async t => {
  const { html } = await nuxt.renderRoute('/callback-async-data')
  t.true(html.includes('
Callback Nuxt.js
'))
})

test('/users/1', async t => {
  const { html } = await nuxt.renderRoute('/users/1')
  t.true(html.includes('
User: 1
'))
})

test('/validate should display a 404', async t => {
  const { html } = await nuxt.renderRoute('/validate')
  t.true(html.includes('This page could not be found'))
})

test('/validate?valid=true', async t => {
  const { html } = await nuxt.renderRoute('/validate?valid=true')
  t.true(html.includes('
I am valid
'))
})

test('/redirect', async t => {
  const { html, redirected } = await nuxt.renderRoute('/redirect')
  t.true(html.includes('

'))
  t.true(redirected.path === '/')
  t.true(redirected.status === 302)
})

test('/redirect -> check redirected source', async t => {
  const window = await nuxt.renderAndGetWindow(url('/redirect'))
  const html = window.document.body.innerHTML
  t.true(html.includes('
Index page
'))
})

test('/special-state -> check window.__NUXT__.test = true', async t => {
  const window = await nuxt.renderAndGetWindow(url('/special-state'))
  t.is(window.__NUXT__.test, true)
})

test('/error', async t => {
  try {
    await nuxt.renderRoute('/error', { req: {}, res: {} })
  } catch (err) {
    t.true(err.message.includes('Error mouahahah'))
  }
})

test('/error status code', async t => {
  try {
    await rp(url('/error'))
  } catch (err) {
    t.true(err.statusCode === 500)
    t.true(err.response.body.includes('An error occurred in the application and your page could not be served'))
  }
})

test('/error2', async t => {
  const { html, error } = await nuxt.renderRoute('/error2')
  t.true(html.includes('Custom error'))
  t.true(error.message.includes('Custom error'))
  t.true(error.statusCode === undefined)
})

test('/error2 status code', async t => {
  try {
    await rp(url('/error2'))
  } catch (err) {
    t.is(err.statusCode, 500)
    t.true(err.response.body.includes('Custom error'))
  }
})

test('/redirect2', async t => {
  stdMocks.use()
  await rp(url('/redirect2')) // Should console.error
  stdMocks.restore()
  const output = stdMocks.flush()
  // Don't display error since redirect returns a noopApp
  t.true(output.stderr.length === 0)
})

test('/no-ssr', async t => {
  const { html } = await nuxt.renderRoute('/no-ssr')
  t.true(html.includes('
<p>Loading...</p>
'))
})

test('/no-ssr (clien-side)', async t => {
  const window = await nuxt.renderAndGetWindow(url('/no-ssr'))
  const html = window.document.body.innerHTML
  t.true(html.includes('
Displayed only on client-side
'))
})

test('ETag Header', async t => {
  const { headers: { etag } } = await rp(url('/stateless'), { resolveWithFullResponse: true })
  // Validate etag
  t.regex(etag, /W\/".*"$/)
  // Verify functionality
  const error = await t.throws(rp(url('/stateless'), { headers: { 'If-None-Match': etag } }))
  t.is(error.statusCode, 304)
})

test('/_nuxt/server-bundle.json should return 404', async t => {
  const err = await t.throws(rp(url('/_nuxt/server-bundle.json'), { resolveWithFullResponse: true }))
  t.is(err.statusCode, 404)
})

test('/_nuxt/ should return 404', async t => {
  const err = await t.throws(rp(url('/_nuxt/'), { resolveWithFullResponse: true }))
  t.is(err.statusCode, 404)
})

// Close server and ask nuxt to stop listening to file changes
test.after('Closing server and nuxt.js', t => {
  nuxt.close()
})
<commit_msg>fix no-ssr client side test<commit_after>import test from 'ava'
import { resolve } from 'path'
import rp from 'request-promise-native'
import stdMocks from 'std-mocks'
import { Nuxt, Builder } from '../index.js'

const port = 4003
const url = (route) => 'http://localhost:' + port + route

let nuxt = null

// Init nuxt.js and create server listening on localhost:4000
test.before('Init Nuxt.js', async t => {
  const options = {
    rootDir: resolve(__dirname, 'fixtures/basic'),
    dev: false
  }
  nuxt = new Nuxt(options)
  await new Builder(nuxt).build()

  await nuxt.listen(port, 'localhost')
})

test('/stateless', async t => {
  const { html } = await nuxt.renderRoute('/stateless')
  t.true(html.includes('
My component!
'))
})

/*
** Example of testing via dom checking
*/
test('/css', async t => {
  const window = await nuxt.renderAndGetWindow(url('/css'))
  const element = window.document.querySelector('.red')
  t.not(element, null)
  t.is(element.textContent, 'This is red')
  t.is(element.className, 'red')
  t.is(window.getComputedStyle(element).color, 'red')
})

test('/stateful', async t => {
  const { html } = await nuxt.renderRoute('/stateful')
  t.true(html.includes('

The answer is 42

'))
})

test('/store', async t => {
  const { html } = await nuxt.renderRoute('/store')
  t.true(html.includes('
Vuex Nested Modules
'))
  t.true(html.includes('
1
'))
})

test('/head', async t => {
  const window = await nuxt.renderAndGetWindow(url('/head'), { virtualConsole: false })
  const html = window.document.body.innerHTML
  const metas = window.document.getElementsByTagName('meta')
  t.is(window.document.title, 'My title')
  t.is(metas[0].getAttribute('content'), 'my meta')
  t.true(html.includes('

I can haz meta tags

'))
})

test('/async-data', async t => {
  const { html } = await nuxt.renderRoute('/async-data')
  t.true(html.includes('
Nuxt.js
'))
})

test('/await-async-data', async t => {
  const { html } = await nuxt.renderRoute('/await-async-data')
  t.true(html.includes('
Await Nuxt.js
'))
})

test('/callback-async-data', async t => {
  const { html } = await nuxt.renderRoute('/callback-async-data')
  t.true(html.includes('
Callback Nuxt.js
'))
})

test('/users/1', async t => {
  const { html } = await nuxt.renderRoute('/users/1')
  t.true(html.includes('
User: 1
'))
})

test('/validate should display a 404', async t => {
  const { html } = await nuxt.renderRoute('/validate')
  t.true(html.includes('This page could not be found'))
})

test('/validate?valid=true', async t => {
  const { html } = await nuxt.renderRoute('/validate?valid=true')
  t.true(html.includes('
I am valid
'))
})

test('/redirect', async t => {
  const { html, redirected } = await nuxt.renderRoute('/redirect')
  t.true(html.includes('

'))
  t.true(redirected.path === '/')
  t.true(redirected.status === 302)
})

test('/redirect -> check redirected source', async t => {
  const window = await nuxt.renderAndGetWindow(url('/redirect'))
  const html = window.document.body.innerHTML
  t.true(html.includes('
Index page
'))
})

test('/special-state -> check window.__NUXT__.test = true', async t => {
  const window = await nuxt.renderAndGetWindow(url('/special-state'))
  t.is(window.__NUXT__.test, true)
})

test('/error', async t => {
  try {
    await nuxt.renderRoute('/error', { req: {}, res: {} })
  } catch (err) {
    t.true(err.message.includes('Error mouahahah'))
  }
})

test('/error status code', async t => {
  try {
    await rp(url('/error'))
  } catch (err) {
    t.true(err.statusCode === 500)
    t.true(err.response.body.includes('An error occurred in the application and your page could not be served'))
  }
})

test('/error2', async t => {
  const { html, error } = await nuxt.renderRoute('/error2')
  t.true(html.includes('Custom error'))
  t.true(error.message.includes('Custom error'))
  t.true(error.statusCode === undefined)
})

test('/error2 status code', async t => {
  try {
    await rp(url('/error2'))
  } catch (err) {
    t.is(err.statusCode, 500)
    t.true(err.response.body.includes('Custom error'))
  }
})

test('/redirect2', async t => {
  stdMocks.use()
  await rp(url('/redirect2')) // Should console.error
  stdMocks.restore()
  const output = stdMocks.flush()
  // Don't display error since redirect returns a noopApp
  t.true(output.stderr.length === 0)
})

test('/no-ssr', async t => {
  const { html } = await nuxt.renderRoute('/no-ssr')
  t.true(html.includes('
<p>Loading...</p>
'))
})

test('/no-ssr (client-side)', async t => {
  const window = await nuxt.renderAndGetWindow(url('/no-ssr'))
  const html = window.document.body.innerHTML
  t.true(html.includes('Displayed only on client-side
'))
})

test('ETag Header', async t => {
  const { headers: { etag } } = await rp(url('/stateless'), { resolveWithFullResponse: true })
  // Validate etag
  t.regex(etag, /W\/".*"$/)
  // Verify functionality
  const error = await t.throws(rp(url('/stateless'), { headers: { 'If-None-Match': etag } }))
  t.is(error.statusCode, 304)
})

test('/_nuxt/server-bundle.json should return 404', async t => {
  const err = await t.throws(rp(url('/_nuxt/server-bundle.json'), { resolveWithFullResponse: true }))
  t.is(err.statusCode, 404)
})

test('/_nuxt/ should return 404', async t => {
  const err = await t.throws(rp(url('/_nuxt/'), { resolveWithFullResponse: true }))
  t.is(err.statusCode, 404)
})

// Close server and ask nuxt to stop listening to file changes
test.after('Closing server and nuxt.js', t => {
  nuxt.close()
})
<|endoftext|>