<commit_before>require('d3.cartodb');// TODO: The 'd3.cartodb' module doens't currently export L.CartoDBd3Layer
// and it's currently relying on window.L so weed to do the following trick.
// Check out: https://github.com/CartoDB/d3.cartodb/issues/93 for more info
var CartoDBd3Layer = window.L.CartoDBd3Layer;
var LeafletLayerView = require('./leaflet-layer-view');
var GeoJSONDataProviderFactory = require('../data-providers/geojson/geojson-data-provider-factory');

var LeafletCartoDBVectorLayerGroupView = CartoDBd3Layer.extend({
  includes: [
    LeafletLayerView.prototype
  ],

  // TODO: There's a conflict between LeafletLayerView.protoype.on
  // and L.CartoDBd3Layer.prototype.on. The GeoJSONDataProvider needs
  // to use the former one, so we have to add an alias.
  _on: CartoDBd3Layer.prototype.on,

  initialize: function (layerModel, leafletMap) {
    LeafletLayerView.call(this, layerModel, this, leafletMap);
    CartoDBd3Layer.prototype.initialize.call(this);

    // Bind changes to the urls of the model
    layerModel.bind('change:urls', this._onTileJSONChanged, this);

    layerModel.layers.bind('change:cartocss', function (child, style) {
      var index = child.get('order') - 1;
      this.setCartoCSS(index, style);
    }, this);

    layerModel.layers.each(function (layer) {
      this._onLayerAdded(layer, layerModel.layers);
    }, this);

    layerModel.layers.bind('add', this._onLayerAdded, this);

    this._on('featureClick', function (event, latlng, pos, data, layerIndex) {
      this.trigger('featureClick', event, latlng, pos, data, layerIndex);
    }.bind(this));

    this._on('featureOver', function (event, latlng, pos, data, layerIndex) {
      this.trigger('featureOver', event, latlng, pos, data, layerIndex);
    }.bind(this));
  },

  _onLayerAdded: function (layerModel, layersCollection) {
    var layerIndex = layersCollection.indexOf(layerModel);
    layerModel.setDataProvider(new GeoJSONDataProviderFactory(this, layerIndex));
  },

  _onTileJSONChanged: function () {
    var tilejson = this.model.get('urls');
    this.options.styles = this.model.layers.pluck('cartocss');
    this.setUrl(tilejson.tiles[0]);
  },

  onAdd: function (map) {
    CartoDBd3Layer.prototype.onAdd.call(this, map);
    this.trigger('added', this);
    this.added = true;
  },

  // Invoked by LeafletLayerView
  _modelUpdated: function () {}
});

module.exports = LeafletCartoDBVectorLayerGroupView;
<commit_msg>Trigger mouseover and mouseout events to make tooltips work<commit_after>require('d3.cartodb');// TODO: The 'd3.cartodb' module doens't currently export L.CartoDBd3Layer
// and it's currently relying on window.L so weed to do the following trick.
// Check out: https://github.com/CartoDB/d3.cartodb/issues/93 for more info
var CartoDBd3Layer = window.L.CartoDBd3Layer;
var LeafletLayerView = require('./leaflet-layer-view');
var GeoJSONDataProviderFactory = require('../data-providers/geojson/geojson-data-provider-factory');

var LeafletCartoDBVectorLayerGroupView = CartoDBd3Layer.extend({
  includes: [
    LeafletLayerView.prototype
  ],

  // TODO: There's a conflict between LeafletLayerView.protoype.on
  // and L.CartoDBd3Layer.prototype.on. The GeoJSONDataProvider needs
  // to use the former one, so we have to add an alias.
  _on: CartoDBd3Layer.prototype.on,

  initialize: function (layerModel, leafletMap) {
    LeafletLayerView.call(this, layerModel, this, leafletMap);
    CartoDBd3Layer.prototype.initialize.call(this);

    // Bind changes to the urls of the model
    layerModel.bind('change:urls', this._onTileJSONChanged, this);

    layerModel.layers.bind('change:cartocss', function (child, style) {
      var index = child.get('order') - 1;
      this.setCartoCSS(index, style);
    }, this);

    layerModel.layers.each(function (layer) {
      this._onLayerAdded(layer, layerModel.layers);
    }, this);

    layerModel.layers.bind('add', this._onLayerAdded, this);

    this._on('featureClick', function (event, latlng, pos, data, layerIndex) {
      this.trigger('featureClick', event, latlng, pos, data, layerIndex);
    }.bind(this));

    this._on('featureOver', function (event, latlng, pos, data, layerIndex) {
      this.trigger('featureOver', event, latlng, pos, data, layerIndex);

      // CartoDB.js tooltips depend on the mouseover event so we trigger it here
      this.trigger('mouseover', event, latlng, pos, data);
    }.bind(this));

    this._on('featureOut', function (event, latlng, pos, data, layerIndex) {
      // CartoDB.js tooltips depend on the mouseout event so we trigger it here
      this.trigger('mouseout');
    }.bind(this));
  },

  _onLayerAdded: function (layerModel, layersCollection) {
    var layerIndex = layersCollection.indexOf(layerModel);
    layerModel.setDataProvider(new GeoJSONDataProviderFactory(this, layerIndex));
  },

  _onTileJSONChanged: function () {
    var tilejson = this.model.get('urls');
    this.options.styles = this.model.layers.pluck('cartocss');
    this.setUrl(tilejson.tiles[0]);
  },

  onAdd: function (map) {
    CartoDBd3Layer.prototype.onAdd.call(this, map);
    this.trigger('added', this);
    this.added = true;
  },

  // Invoked by LeafletLayerView
  _modelUpdated: function () {}
});

module.exports = LeafletCartoDBVectorLayerGroupView;
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
/* global localStorage */

'use strict'

const supportLocalStorage = typeof localStorage !== 'undefined'
const SUCCESS = 'success'
const FAILED = 'failed'
const INVALID_PARAM = 'invalid_param'
const UNDEFINED = 'undefined'

const storage = {

  /**
   * When passed a key name and value, will add that key to the storage,
   * or update that key's value if it already exists.
   * @param {string} key
   * @param {string} value
   * @param {function} callbackId
   */
  setItem: function (key, value, callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    if (!key || (!value && value != 0)) {
      sender.performCallback(callbackId, {
        result: 'failed',
        data: INVALID_PARAM
      })
      return
    }
    try {
      localStorage.setItem(key, value)
      sender.performCallback(callbackId, {
        result: SUCCESS,
        data: UNDEFINED
      })
    }
    catch (e) {
      // accept any exception thrown during a storage attempt as a quota error
      sender.performCallback(callbackId, {
        result: FAILED,
        data: UNDEFINED
      })
    }
  },

  /**
   * When passed a key name, will return that key's value.
   * @param {string} key
   * @param {function} callbackId
   */
  getItem: function (key, callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    if (!key) {
      sender.performCallback(callbackId, {
        result: FAILED,
        data: INVALID_PARAM
      })
      return
    }
    const val = localStorage.getItem(key)
    sender.performCallback(callbackId, {
      result: val ? SUCCESS : FAILED,
      data: val || UNDEFINED
    })
  },

  /**
   *When passed a key name, will remove that key from the storage.
   * @param {string} key
   * @param {function} callbackId
   */
  removeItem: function (key, callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    if (!key) {
      sender.performCallback(callbackId, {
        result: FAILED,
        data: INVALID_PARAM
      })
      return
    }
    localStorage.removeItem(key)
    sender.performCallback(callbackId, {
      result: SUCCESS,
      data: UNDEFINED
    })
  },

  /**
   * Returns an integer representing the number of data items stored in the Storage object.
   * @param {function} callbackId
   */
  length: function (callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    const len = localStorage.length
    sender.performCallback(callbackId, {
      result: SUCCESS,
      data: len
    })
  },

  /**
   * Returns an array that contains all keys stored in Storage object.
   * @param {function} callbackId
   */
  getAllKeys: function (callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    const _arr = []
    for (let i = 0; i < localStorage.length; i++) {
      _arr.push(localStorage.key(i))
    }
    sender.performCallback(callbackId, {
      result: SUCCESS,
      data: _arr
    })
  }
}

const meta = {
  storage: [{
    name: 'setItem',
    args: ['string', 'string', 'function']
  }, {
    name: 'getItem',
    args: ['string', 'function']
  }, {
    name: 'removeItem',
    args: ['string', 'function']
  }, {
    name: 'length',
    args: ['function']
  }, {
    name: 'getAllKeys',
    args: ['function']
  }]
}

export default {
  init: function (Weex) {
    Weex.registerApiModule('storage', storage, meta)
  }
}
<commit_msg>[html5] !== lint<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
/* global localStorage */

'use strict'

const supportLocalStorage = typeof localStorage !== 'undefined'
const SUCCESS = 'success'
const FAILED = 'failed'
const INVALID_PARAM = 'invalid_param'
const UNDEFINED = 'undefined'

const storage = {

  /**
   * When passed a key name and value, will add that key to the storage,
   * or update that key's value if it already exists.
   * @param {string} key
   * @param {string} value
   * @param {function} callbackId
   */
  setItem: function (key, value, callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    if (!key || (!value && value !== 0)) {
      sender.performCallback(callbackId, {
        result: 'failed',
        data: INVALID_PARAM
      })
      return
    }
    try {
      localStorage.setItem(key, value)
      sender.performCallback(callbackId, {
        result: SUCCESS,
        data: UNDEFINED
      })
    }
    catch (e) {
      // accept any exception thrown during a storage attempt as a quota error
      sender.performCallback(callbackId, {
        result: FAILED,
        data: UNDEFINED
      })
    }
  },

  /**
   * When passed a key name, will return that key's value.
   * @param {string} key
   * @param {function} callbackId
   */
  getItem: function (key, callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    if (!key) {
      sender.performCallback(callbackId, {
        result: FAILED,
        data: INVALID_PARAM
      })
      return
    }
    const val = localStorage.getItem(key)
    sender.performCallback(callbackId, {
      result: val ? SUCCESS : FAILED,
      data: val || UNDEFINED
    })
  },

  /**
   *When passed a key name, will remove that key from the storage.
   * @param {string} key
   * @param {function} callbackId
   */
  removeItem: function (key, callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    if (!key) {
      sender.performCallback(callbackId, {
        result: FAILED,
        data: INVALID_PARAM
      })
      return
    }
    localStorage.removeItem(key)
    sender.performCallback(callbackId, {
      result: SUCCESS,
      data: UNDEFINED
    })
  },

  /**
   * Returns an integer representing the number of data items stored in the Storage object.
   * @param {function} callbackId
   */
  length: function (callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    const len = localStorage.length
    sender.performCallback(callbackId, {
      result: SUCCESS,
      data: len
    })
  },

  /**
   * Returns an array that contains all keys stored in Storage object.
   * @param {function} callbackId
   */
  getAllKeys: function (callbackId) {
    if (!supportLocalStorage) {
      console.error('your browser is not support localStorage yet.')
      return
    }
    const sender = this.sender
    const _arr = []
    for (let i = 0; i < localStorage.length; i++) {
      _arr.push(localStorage.key(i))
    }
    sender.performCallback(callbackId, {
      result: SUCCESS,
      data: _arr
    })
  }
}

const meta = {
  storage: [{
    name: 'setItem',
    args: ['string', 'string', 'function']
  }, {
    name: 'getItem',
    args: ['string', 'function']
  }, {
    name: 'removeItem',
    args: ['string', 'function']
  }, {
    name: 'length',
    args: ['function']
  }, {
    name: 'getAllKeys',
    args: ['function']
  }]
}

export default {
  init: function (Weex) {
    Weex.registerApiModule('storage', storage, meta)
  }
}
<|endoftext|>


<commit_before>$(function() {
    var $modal = $('#select-data-modal');

    /* Autocomplete */
    $modal.find('#data-filter-search').on('keyup', function() {
        var term = $(this).val().toLowerCase();

        // hide/show variables
        $.each($modal.find('.variable-section'), function(idx, section) {
            var $section = $(section);

            if ($section.text().toLowerCase().indexOf(term) >= 0) {
                $section.removeClass('hidden')
            } else {
                $section.addClass('hidden')
            }
        });

        // hide-show datasets
        $.each($modal.find('.dataset-section'), function(idx, section) {
            var $section = $(section);

            if ($section.find('.variable-section').length === $section.find('.variable-section.hidden').length) {
                $section.addClass('hidden')
            } else {
                $section.removeClass('hidden')
            }
        });

        // hide-show no results
        if ($modal.find('.variable-section:not(.hidden)').length === 0) {
            $modal.find('.no-results').removeClass('hidden')
        } else {
            $modal.find('.no-results').addClass('hidden')
        }
    });

    /* select variable */
    window.getDataSelection = function() {
        let dims = [];
        $('#group-by-select option').each(function () {
            dims.push({
                value: $(this).val(),
                title: $(this).text().split(',')[0]
            })
        });

        let datasetInfoDivElem = $('.dataset1_info_div');
        return {
            value: datasetInfoDivElem.find('.variable-section.selected').find('.variable-name').text(),
            title: datasetInfoDivElem.find('.variable-section.selected').find('.variable-title').text(),
            id: datasetInfoDivElem.find('.variable-section.selected').find('.variable-id').text(),
            unit: datasetInfoDivElem.find('.variable-section.selected').find('.variable-unit').text(),
            aggregate: $('#selection-aggregate').val(),
            groupBy: $('#group-by-select').val(),
            dimensions: dims
        }
    };

    $(".dataset-metadata-btn").click(function () {
        $(this).parent().parent().find('.dataset-metadata').collapse("toggle");
    });

     $(".dataset-title").click(function () {
         let $dataset1InfoDiv = $('.dataset1_info_div');
         $dataset1InfoDiv.find(".dataset-info").remove();
        // $(this).clone().appendTo('.dataset1_info_div');
        $(this).parent().parent().clone().appendTo('.dataset1_info_div');
        $dataset1InfoDiv.get(0).classList.remove('collapse');
         $dataset1InfoDiv.find(".dataset-info").find(".variables1").show();
         $dataset1InfoDiv.find(".dataset-info").find(".dataset-name").find(".dimensions").show();
    });

   $('.dataset1_info_div').on('click', ".variable-title", function() {

       $modal.find('.variable-section').removeClass('selected');
        $(this).parent().parent().addClass('selected');

       let $selectionCol = $('.selection-confirm > div');
       $selectionCol.removeClass('hidden');
        // $selectionCol.find('#selection-aggregate').val('AVG').trigger('change');
        $selectionCol.find('#selection-aggregate').val(null).trigger('change');

        // remove old group by
        $('#group-by-select').remove();

        // add group by options
        var $gSelect = $('<select />')
            .attr('id', 'group-by-select')
            .attr('multiple', 'multiple');

        $.each($(this).parent().parent().find('.dimensions > span'), function(idx, dimension) {
            var $dimension = $(dimension);

            var $opt = $('<option />')
                .attr('value', $dimension.data('type'))
                .text($dimension.text());

            if ($dimension.text().toLowerCase().indexOf('time') >= 0) {
                $opt.attr('selected', 'selected');
            }

            $gSelect.append($opt);
        });

        // add & config plugin
        $('.selection-group-by').append($gSelect);
        $("#group-by-select").val(null).trigger('change');
        $gSelect.select2();
    });
});<commit_msg>fixes for operators unsupported from the current js version<commit_after>$(function() {
    var $modal = $('#select-data-modal');

    /* Autocomplete */
    $modal.find('#data-filter-search').on('keyup', function() {
        var term = $(this).val().toLowerCase();

        // hide/show variables
        $.each($modal.find('.variable-section'), function(idx, section) {
            var $section = $(section);

            if ($section.text().toLowerCase().indexOf(term) >= 0) {
                $section.removeClass('hidden')
            } else {
                $section.addClass('hidden')
            }
        });

        // hide-show datasets
        $.each($modal.find('.dataset-section'), function(idx, section) {
            var $section = $(section);

            if ($section.find('.variable-section').length === $section.find('.variable-section.hidden').length) {
                $section.addClass('hidden')
            } else {
                $section.removeClass('hidden')
            }
        });

        // hide-show no results
        if ($modal.find('.variable-section:not(.hidden)').length === 0) {
            $modal.find('.no-results').removeClass('hidden')
        } else {
            $modal.find('.no-results').addClass('hidden')
        }
    });

    /* select variable */
    window.getDataSelection = function() {
        var dims = [];
        $('#group-by-select option').each(function () {
            dims.push({
                value: $(this).val(),
                title: $(this).text().split(',')[0]
            })
        });

        var datasetInfoDivElem = $('.dataset1_info_div');
        return {
            value: datasetInfoDivElem.find('.variable-section.selected').find('.variable-name').text(),
            title: datasetInfoDivElem.find('.variable-section.selected').find('.variable-title').text(),
            id: datasetInfoDivElem.find('.variable-section.selected').find('.variable-id').text(),
            unit: datasetInfoDivElem.find('.variable-section.selected').find('.variable-unit').text(),
            aggregate: $('#selection-aggregate').val(),
            groupBy: $('#group-by-select').val(),
            dimensions: dims
        }
    };

    $(".dataset-metadata-btn").click(function () {
        $(this).parent().parent().find('.dataset-metadata').collapse("toggle");
    });

     $(".dataset-title").click(function () {
         var $dataset1InfoDiv = $('.dataset1_info_div');
         $dataset1InfoDiv.find(".dataset-info").remove();
        // $(this).clone().appendTo('.dataset1_info_div');
        $(this).parent().parent().clone().appendTo('.dataset1_info_div');
        $dataset1InfoDiv.get(0).classList.remove('collapse');
         $dataset1InfoDiv.find(".dataset-info").find(".variables1").show();
         $dataset1InfoDiv.find(".dataset-info").find(".dataset-name").find(".dimensions").show();
    });

   $('.dataset1_info_div').on('click', ".variable-title", function() {

       $modal.find('.variable-section').removeClass('selected');
        $(this).parent().parent().addClass('selected');

       var $selectionCol = $('.selection-confirm > div');
       $selectionCol.removeClass('hidden');
        // $selectionCol.find('#selection-aggregate').val('AVG').trigger('change');
        $selectionCol.find('#selection-aggregate').val(null).trigger('change');

        // remove old group by
        $('#group-by-select').remove();

        // add group by options
        var $gSelect = $('<select />')
            .attr('id', 'group-by-select')
            .attr('multiple', 'multiple');

        $.each($(this).parent().parent().find('.dimensions > span'), function(idx, dimension) {
            var $dimension = $(dimension);

            var $opt = $('<option />')
                .attr('value', $dimension.data('type'))
                .text($dimension.text());

            if ($dimension.text().toLowerCase().indexOf('time') >= 0) {
                $opt.attr('selected', 'selected');
            }

            $gSelect.append($opt);
        });

        // add & config plugin
        $('.selection-group-by').append($gSelect);
        $("#group-by-select").val(null).trigger('change');
        $gSelect.select2();
    });
});<|endoftext|>


<commit_before>angular
module('Cadastrar').
  component('registrarDepartamento', {
    templateUrl: '/app/Cadastrar/cadastrar.template.html',
    controller: ['ApiDepartamento','$http','$location', 'MatWebGlobals',function registrarDepartamento(ApiDepartamento,$http,$location,MatWebGlobals) {
        var ctrl = this;
       this.formulario = {'depName':'','idNumber':''};
        ctrl.cadastrar = cadastrar;

        function cadastrar() {
            ctrl.mensagem = true;
            ApiDepartamento.Create(ctrl.formulario)
                .then(function (data) {
                    if (data.success) {
                        MatWebGlobals.Success('Registration successful', true);
                        $location.path('/Cadastrar');
                    } else {
                        MatWebGlobals.Error(data.mensagem);
                        ctrl.mensagem = false;
                    }
                })
        }
  }];<commit_msg>lol 2017-05-17<commit_after>angular.
module('Cadastrar').
  component('registrarDepartamento', {
    templateUrl: '/app/Cadastrar/cadastrar.template.html',
    controller: ['ApiDepartamento','$http','$location', 'MatWebGlobals',function registrarDepartamento(ApiDepartamento,$http,$location,MatWebGlobals) {
        var ctrl = this;
       this.formulario = {'depName':'','idNumber':''};
        ctrl.cadastrar = cadastrar;

        function cadastrar() {
            ctrl.mensagem = true;
            ApiDepartamento.Create(ctrl.formulario)
                .then(function (data) {
                    if (data.success) {
                        MatWebGlobals.Success('Registration successful', true);
                        $location.path('/Cadastrar');
                    } else {
                        MatWebGlobals.Error(data.mensagem);
                        ctrl.mensagem = false;
                    }
                })
          };
    }]
});<|endoftext|>


<commit_before>define([
	'goo/fsmpack/statemachine/actions/Action'
],
/** @lends */
function (
	Action
) {
	'use strict';

	function TweenOpacityAction(/*id, settings*/) {
		Action.apply(this, arguments);
	}

	TweenOpacityAction.prototype = Object.create(Action.prototype);
	TweenOpacityAction.prototype.constructor = TweenOpacityAction;

	TweenOpacityAction.external = {
		name: 'Tween Opacity',
		type: 'texture',
		description: 'Tweens the opacity of a material',
		parameters: [{
			name: 'Opacity',
			key: 'to',
			type: 'number',
			description: 'Opacity',
			'default': 1
		}, {
			name: 'Time (ms)',
			key: 'time',
			type: 'number',
			description: 'Time it takes for the transition to complete',
			'default': 1000
		}, {
			name: 'Easing type',
			key: 'easing1',
			type: 'dropdown',
			description: 'Easing type',
			'default': 'Linear',
			options: ['Linear', 'Quadratic', 'Exponential', 'Circular', 'Bounce']
		}, {
			name: 'Direction',
			key: 'easing2',
			type: 'dropdown',
			description: 'Easing direction',
			'default': 'In',
			options: ['In', 'Out', 'InOut']
		}],
		transitions: [{
			key: 'complete',
			name: 'On Completion',
			description: 'State to transition to when the transition completes'
		}]
	};

	TweenOpacityAction.prototype.configure = function (settings) {
		this.to = settings.to;
		this.time = settings.time;
		if (settings.easing1 === 'Linear') {
			this.easing = window.TWEEN.Easing.Linear.None;
		} else {
			this.easing = window.TWEEN.Easing[settings.easing1][settings.easing2];
		}
		this.eventToEmit = { channel: settings.transitions.complete };
	};

	TweenOpacityAction.prototype._setup = function (fsm) {
		this.tween = new window.TWEEN.Tween();

        var entity = fsm.getOwnerEntity();
        var meshRendererComponent = entity.meshRendererComponent;

        this.material = meshRendererComponent.materials[0];
        this.oldBlending = this.material.blendState.blending;
        this.oldQueue = this.material.renderQueue;
        this.oldOpacity = this.material.shader.uniforms.opacity;

        this.material.blendState.blending = 'CustomBlending';
        if (this.material.renderQueue < 2000) {
            this.material.renderQueue = 2000;
        }

        if (this.material.shader.uniforms.opacity === undefined) {
            this.material.shader.uniforms.opacity = 1;
        }
	};

	TweenOpacityAction.prototype.cleanup = function (/*fsm*/) {
		if (this.tween) {
			this.tween.stop();
		}
        this.material.blendState.blending = this.oldBlending;
        this.material.renderQueue = this.oldQueue;
        this.material.shader.uniforms.opacity = this.oldOpacity;
	};

	TweenOpacityAction.prototype._run = function (fsm) {
		var entity = fsm.getOwnerEntity();
		if (entity.meshRendererComponent) {
			var uniforms = this.material.shader.uniforms;
			var time = entity._world.time * 1000;

			var fakeFrom = { opacity: uniforms.opacity };
			var fakeTo = { opacity: this.to };

			var old = { opacity: fakeFrom.opacity };

			this.tween.from(fakeFrom).to(fakeTo, +this.time).easing(this.easing).onUpdate(function () {
				uniforms.opacity += this.opacity - old.opacity;

				old.opacity = this.opacity;
			}).onComplete(function () {
				fsm.send(this.eventToEmit.channel);
			}.bind(this)).start(time);
		}
	};

	return TweenOpacityAction;
});<commit_msg>Fixed https://trello.com/c/axFODd0y/1635-normal-tween-opacity-makes-other-entities-dissappear<commit_after>define([
	'goo/fsmpack/statemachine/actions/Action'
],
/** @lends */
function (
	Action
) {
	'use strict';

	function TweenOpacityAction(/*id, settings*/) {
		Action.apply(this, arguments);
	}

	TweenOpacityAction.prototype = Object.create(Action.prototype);
	TweenOpacityAction.prototype.constructor = TweenOpacityAction;

	TweenOpacityAction.external = {
		name: 'Tween Opacity',
		type: 'texture',
		description: 'Tweens the opacity of a material',
		parameters: [{
			name: 'Opacity',
			key: 'to',
			type: 'number',
			description: 'Opacity',
			'default': 1
		}, {
			name: 'Time (ms)',
			key: 'time',
			type: 'number',
			description: 'Time it takes for the transition to complete',
			'default': 1000
		}, {
			name: 'Easing type',
			key: 'easing1',
			type: 'dropdown',
			description: 'Easing type',
			'default': 'Linear',
			options: ['Linear', 'Quadratic', 'Exponential', 'Circular', 'Bounce']
		}, {
			name: 'Direction',
			key: 'easing2',
			type: 'dropdown',
			description: 'Easing direction',
			'default': 'In',
			options: ['In', 'Out', 'InOut']
		}],
		transitions: [{
			key: 'complete',
			name: 'On Completion',
			description: 'State to transition to when the transition completes'
		}]
	};

	TweenOpacityAction.prototype.configure = function (settings) {
		this.to = settings.to;
		this.time = settings.time;
		if (settings.easing1 === 'Linear') {
			this.easing = window.TWEEN.Easing.Linear.None;
		} else {
			this.easing = window.TWEEN.Easing[settings.easing1][settings.easing2];
		}
		this.eventToEmit = { channel: settings.transitions.complete };
	};

	TweenOpacityAction.prototype._setup = function (fsm) {
		this.tween = new window.TWEEN.Tween();

        var entity = fsm.getOwnerEntity();
        var meshRendererComponent = entity.meshRendererComponent;

        this.material = meshRendererComponent.materials[0];
        this.oldBlending = this.material.blendState.blending;
        this.oldQueue = this.material.renderQueue;
        this.oldOpacity = this.material.uniforms.opacity;

        this.material.blendState.blending = 'CustomBlending';
        if (this.material.renderQueue < 2000) {
            this.material.renderQueue = 2000;
        }

        if (this.material.uniforms.opacity === undefined) {
            this.material.uniforms.opacity = 1;
        }
	};

	TweenOpacityAction.prototype.cleanup = function (/*fsm*/) {
		if (this.tween) {
			this.tween.stop();
		}
        this.material.blendState.blending = this.oldBlending;
        this.material.renderQueue = this.oldQueue;
        this.material.uniforms.opacity = this.oldOpacity;
	};

	TweenOpacityAction.prototype._run = function (fsm) {
		var entity = fsm.getOwnerEntity();
		if (entity.meshRendererComponent) {
			var uniforms = this.material.uniforms;

			var time = entity._world.time * 1000;

			var fakeFrom = { opacity: uniforms.opacity };
			var fakeTo = { opacity: this.to };

			var old = { opacity: fakeFrom.opacity };

			this.tween.from(fakeFrom).to(fakeTo, +this.time).easing(this.easing).onUpdate(function () {
				uniforms.opacity += this.opacity - old.opacity;

				old.opacity = this.opacity;
			}).onComplete(function () {
				fsm.send(this.eventToEmit.channel);
			}.bind(this)).start(time);
		}
	};

	return TweenOpacityAction;
});<|endoftext|>


<commit_before>elation.elements.define('janus.ui.buttons', class extends elation.elements.base {
  create() {
    this.innerHTML = elation.template.get('janus.ui.buttons');
  }
});
elation.elements.define('janus-buttons-display', class extends elation.elements.ui.dropdownbutton {
  init() {
    super.init();

    var detect = {
      fullscreen: () => this.supportsFullscreen(),
      webvr: () => this.supportsWebVR(),
      chromecast: () => this.supportsChromecast(),
      equirectangular: () => this.supportsEquirectangular(),
      sbs3d: () => this.supportsSBS3D(),
      ou3d: () => this.supportsOU3D(),
      peppersghost: () => this.supportsPeppersGhost(),
    };

  }
  supportsFullscreen() {
  }
  supportsWebVR() {
  }
  supportsChromecast() {
  }
  supportsEquirectangular() {
  }
  supportsSBS3D() {
  }
  supportsOU3D() {
  }
  supportsPeppersGhost() {
  }
});

elation.elements.define('janus-button-fullscreen', class extends elation.elements.ui.togglebutton {
  create() {
    super.create();
    elation.events.add(document, 'fullscreenchange', (ev) => {
      if (document.fullscreen) {
        this.active = true;
      } else {
        this.active = false;
      }
    });
  }
  onactivate(ev) {
    this.client.fullscreen(true);
  }
  ondeactivate(ev) {
    this.client.fullscreen(false);
  }
});
elation.elements.define('janus-button-webvr', class extends elation.elements.ui.togglebutton {
  create() {
    this.xr = false;
    this.activelabel = 'WebVR';
    this.inactivelabel = 'WebVR';

    this.label = this.activelabel;
    super.create();
    this.view = janus.engine.client.view;

    if ('xr' in navigator) {
      this.activelabel = 'WebXR';
      this.inactivelabel = 'WebXR';
      this.label = this.inactivelabel;
      this.xr = true;
    } else if ('getVRDevices' in navigator) {
      window.addEventListener( 'vrdisplayconnect', (ev) => {
        this.show();
      }, false );

      window.addEventListener( 'vrdisplaydisconnect', (ev) => {
        this.hide();
      }, false );

      window.addEventListener( 'vrdisplaypresentchange', (ev) => {
        if (this.view.vrdisplay.isPresenting) {
        } else {
        }
      }, false );
    }
  }
  onactivate(ev) {
    this.label = this.activelabel;
    if (this.xr) {
      this.view.startXR();
    } else {
      this.view.toggleVR(true);
    }
  }
  ondeactivate(ev) {
    this.label = this.inactivelabel;
    if (this.xr) {
      this.view.stopXR();
    } else {
      this.view.toggleVR(false);
    }
  }
});
elation.elements.define('janus-buttons-chromecast', class extends elation.elements.ui.togglebutton {
});
elation.elements.define('janus-buttons-equirectangular', class extends elation.elements.ui.togglebutton {
});
elation.elements.define('janus-buttons-sbs3d', class extends elation.elements.ui.togglebutton {
});
elation.elements.define('janus-buttons-ou3d', class extends elation.elements.ui.togglebutton {
});
elation.elements.define('janus-buttons-peppersghost', class extends elation.elements.ui.togglebutton {
});
<commit_msg>Use new method of entering XR<commit_after>elation.elements.define('janus.ui.buttons', class extends elation.elements.base {
  create() {
    this.innerHTML = elation.template.get('janus.ui.buttons');
  }
});
elation.elements.define('janus-buttons-display', class extends elation.elements.ui.dropdownbutton {
  init() {
    super.init();

    var detect = {
      fullscreen: () => this.supportsFullscreen(),
      webvr: () => this.supportsWebVR(),
      chromecast: () => this.supportsChromecast(),
      equirectangular: () => this.supportsEquirectangular(),
      sbs3d: () => this.supportsSBS3D(),
      ou3d: () => this.supportsOU3D(),
      peppersghost: () => this.supportsPeppersGhost(),
    };

  }
  supportsFullscreen() {
  }
  supportsWebVR() {
  }
  supportsChromecast() {
  }
  supportsEquirectangular() {
  }
  supportsSBS3D() {
  }
  supportsOU3D() {
  }
  supportsPeppersGhost() {
  }
});

elation.elements.define('janus-button-fullscreen', class extends elation.elements.ui.togglebutton {
  create() {
    super.create();
    elation.events.add(document, 'fullscreenchange', (ev) => {
      if (document.fullscreen) {
        this.active = true;
      } else {
        this.active = false;
      }
    });
  }
  onactivate(ev) {
    this.client.fullscreen(true);
  }
  ondeactivate(ev) {
    this.client.fullscreen(false);
  }
});
elation.elements.define('janus-button-webvr', class extends elation.elements.ui.togglebutton {
  create() {
    this.xr = false;
    this.activelabel = 'WebVR';
    this.inactivelabel = 'WebVR';

    this.label = this.activelabel;
    super.create();
    this.view = janus.engine.client.view;

    if ('xr' in navigator) {
      this.activelabel = 'WebXR';
      this.inactivelabel = 'WebXR';
      this.label = this.inactivelabel;
      this.xr = true;
    } else if ('getVRDevices' in navigator) {
      window.addEventListener( 'vrdisplayconnect', (ev) => {
        this.show();
      }, false );

      window.addEventListener( 'vrdisplaydisconnect', (ev) => {
        this.hide();
      }, false );

      window.addEventListener( 'vrdisplaypresentchange', (ev) => {
        if (this.view.vrdisplay.isPresenting) {
        } else {
        }
      }, false );
    }
  }
  onactivate(ev) {
    this.label = this.activelabel;
    if (this.xr) {
      janus.engine.client.startXR();
    } else {
      this.view.toggleVR(true);
    }
  }
  ondeactivate(ev) {
    this.label = this.inactivelabel;
    if (this.xr) {
      this.view.stopXR();
    } else {
      this.view.toggleVR(false);
    }
  }
});
elation.elements.define('janus-buttons-chromecast', class extends elation.elements.ui.togglebutton {
});
elation.elements.define('janus-buttons-equirectangular', class extends elation.elements.ui.togglebutton {
});
elation.elements.define('janus-buttons-sbs3d', class extends elation.elements.ui.togglebutton {
});
elation.elements.define('janus-buttons-ou3d', class extends elation.elements.ui.togglebutton {
});
elation.elements.define('janus-buttons-peppersghost', class extends elation.elements.ui.togglebutton {
});
<|endoftext|>


<commit_before>var fs = require('fs'),
    fu = require('../../lib/fileUtil'),
    lib = require('./index'),
    lumbar = require('../../lib/lumbar'),
    should = require('should'),
    wrench = require('wrench');

exports.canWatch = function() {
  // Watch is unsupported on 0.4 and earlier
  return !!fs.watch;
};

exports.append = function(path, content) {
  setTimeout(function() {
    var fd = fs.openSync(path, 'a');
    fs.writeSync(fd, content);
    fs.closeSync(fd);
  }, 500);
};
exports.appendSpace = function(path) {
  exports.append(path, ' ');
};

exports.appendRapidSpace = function(path1, path2) {
  setTimeout(function() {
    var fd = fs.openSync(path1, 'a');
    fs.writeSync(fd, ' ');
    fs.closeSync(fd);

    var fd = fs.openSync(path2, 'a');
    fs.writeSync(fd, ' ');
    fs.closeSync(fd);
  }, 500);
};

exports.runWatchTest = function(srcdir, config, operations, expectedFiles, options, done) {
  // Mocha: this.test.title
  // Expresso: this.title
  var title = (this.test && this.test.title) || this.title || config,
      testdir = lib.testDir(title, 'example'),
      outdir = lib.testDir(title, 'test');
  if (this.title) {
    this.title += ' ' + outdir;
  }

  wrench.copyDirSyncRecursive(srcdir, testdir);

  function complete(err) {
    process.removeListener('uncaughtException', complete);
    done();
  }
  process.on('uncaughtException', complete);

  options.outdir = outdir;
  var arise = lumbar.init(testdir + '/' + config, options);
  arise.on('output', checkOutput(operations, expectedFiles, arise, options, function() {
    // Cleanup (Do cleanup here so the files remain for the failure case)
    wrench.rmdirSyncRecursive(testdir);
    wrench.rmdirSyncRecursive(outdir);

    complete();
  }));

  arise.watch(undefined, function(err) {
    err = err || new Error('Callback called without fatal error');
    throw err;
  });
};

function checkOutput(operations, expectedFiles, arise, options, cleanup) {
  var seenFiles = [];

  return function(status) {
    var statusFile = status.fileName.substring(options.outdir.length);
    if (!expectedFiles.some(function(fileName) { return statusFile === fileName; })) {
      arise.unwatch();
      should.fail(undefined, status.fileName,  'watchFile:' + statusFile + ': missing from expected list');
    } else {
      seenFiles.push(statusFile);
    }
    var seen = seenFiles.length;
    setTimeout(function() {
      operations[seen] && operations[seen](fu.lookupPath());
    }, 0);
    if (seenFiles.length < expectedFiles.length) {
      return;
    }

    arise.unwatch();

    seenFiles = seenFiles.sort();
    expectedFiles = expectedFiles.sort();
    seenFiles.should.eql(expectedFiles, 'watchFile: seen file list matches');

    if (options.expectedDir) {
      lib.assertExpected(options.outdir, options.expectedDir, 'watchfile: ' + options.outdir);
    }

    cleanup();
  };
}
<commit_msg>watch.mockWatch test util<commit_after>var fs = require('fs'),
    fu = require('../../lib/fileUtil'),
    lib = require('./index'),
    lumbar = require('../../lib/lumbar'),
    should = require('should'),
    watcher = require('../../lib/watcher'),
    wrench = require('wrench');

exports.canWatch = function() {
  // Watch is unsupported on 0.4 and earlier
  return !!fs.watch;
};

exports.append = function(path, content) {
  setTimeout(function() {
    var fd = fs.openSync(path, 'a');
    fs.writeSync(fd, content);
    fs.closeSync(fd);
  }, 500);
};
exports.appendSpace = function(path) {
  exports.append(path, ' ');
};

exports.appendRapidSpace = function(path1, path2) {
  setTimeout(function() {
    var fd = fs.openSync(path1, 'a');
    fs.writeSync(fd, ' ');
    fs.closeSync(fd);

    var fd = fs.openSync(path2, 'a');
    fs.writeSync(fd, ' ');
    fs.closeSync(fd);
  }, 500);
};

exports.mockWatch = function() {
  var original = watcher.watchFile;

  watcher.watchFile = function(filename, dependencies, callback) {
    function makeVirtual(filename) {
      if (!filename.virtual) {
        filename = {virtual: filename};
      }
      return filename;
    }
    filename = makeVirtual(filename);
    dependencies = dependencies.map(makeVirtual);
    return original.call(this, filename, dependencies, callback);
  };

  return {
    trigger: function(type, filename) {
      watcher.trigger(type, filename);
    },
    cleanup: function() {
      watcher.watchFile = original;
    }
  };
};

exports.runWatchTest = function(srcdir, config, operations, expectedFiles, options, done) {
  // Mocha: this.test.title
  // Expresso: this.title
  var title = (this.test && this.test.title) || this.title || config,
      testdir = lib.testDir(title, 'example'),
      outdir = lib.testDir(title, 'test');
  if (this.title) {
    this.title += ' ' + outdir;
  }

  wrench.copyDirSyncRecursive(srcdir, testdir);

  function complete(err) {
    process.removeListener('uncaughtException', complete);
    done();
  }
  process.on('uncaughtException', complete);

  options.outdir = outdir;
  var arise = lumbar.init(testdir + '/' + config, options);
  arise.on('output', checkOutput(operations, expectedFiles, arise, options, function() {
    // Cleanup (Do cleanup here so the files remain for the failure case)
    wrench.rmdirSyncRecursive(testdir);
    wrench.rmdirSyncRecursive(outdir);

    complete();
  }));

  arise.watch(undefined, function(err) {
    err = err || new Error('Callback called without fatal error');
    throw err;
  });
};

function checkOutput(operations, expectedFiles, arise, options, cleanup) {
  var seenFiles = [];

  return function(status) {
    var statusFile = status.fileName.substring(options.outdir.length);
    if (!expectedFiles.some(function(fileName) { return statusFile === fileName; })) {
      arise.unwatch();
      should.fail(undefined, status.fileName,  'watchFile:' + statusFile + ': missing from expected list');
    } else {
      seenFiles.push(statusFile);
    }
    var seen = seenFiles.length;
    setTimeout(function() {
      operations[seen] && operations[seen](fu.lookupPath());
    }, 0);
    if (seenFiles.length < expectedFiles.length) {
      return;
    }

    arise.unwatch();

    seenFiles = seenFiles.sort();
    expectedFiles = expectedFiles.sort();
    seenFiles.should.eql(expectedFiles, 'watchFile: seen file list matches');

    if (options.expectedDir) {
      lib.assertExpected(options.outdir, options.expectedDir, 'watchfile: ' + options.outdir);
    }

    cleanup();
  };
}
<|endoftext|>


<commit_before>
// keywords: js, javascript, is date tester

/**
 * Test if the a value is a date
 *
 * @method <method_name>
 * @param  {String,Number,Date} date The date to test
 * @return {Boolean} true if success, else false
 */
function isDate(date) {
  if (!isNaN((new Date(date)).getTime())) {
    return true;
  }
  return false;
}

console.log(isDate('2013'));
console.log(isDate(new Date('2013')));
console.log(isDate(1234));
<commit_msg>isDate.js +1<commit_after>
// keywords: js, javascript, is date tester

/**
 * Test if the a value is a date
 *
 * @param  {String,Number,Date} date The date to test
 * @return {Boolean} true if success, else false
 */
function isDate(date) {
  if (!isNaN((new Date(date)).getTime())) {
    return true;
  }
  return false;
}

//////////////////////////////
// Tests
if (!module.parent) {
  console.log(isDate('2013') === true);
  console.log(isDate(new Date('2013')) === true);
  console.log(isDate(1234) === true);
}
<|endoftext|>


<commit_before>var SmSc = SmSc || {};

SmSc.Sensor = class Sensor{
    /*
    * Create a sensor instance
    * @param {number} id The id of the sensor, null if not in database
    * @param {string} location The location of the sensor
    * @param {string} type The type of the sensor
    */
    constructor(id, location, type) {
        this.id = id;
        this.location = location;
        this.type = type;
        this.readings = [];
    }

    /*
    * Add the sensor to the database and set the id of the sensor
    * @param {function} callback The callback, will be executed when done
    */
    insert(callback) {
        var sensor = this;
        callback = callback || function(){};
        $.ajax(SmSc.url + "/addSensor.php", {
            method:"GET",
            dataType:"JSON",
            data:SmSc.addCredentials({
                location:this.location,
                type:this.type
            }),
            success:function(response) {
                var nSensor = response.sensor || {};
                sensor.id = nSensor.id;

                var err = response.err || null;

                if(response.err) callback(null, err);
                else callback(sensor, err);
            },
            error:function() {
                console.log(arguments);
                callback(sensor, "the http request failed");
            }
        });
    }

    get reading() {
        return _.last(_.sortBy(this.readings, "dateTime"));
    }

    set reading(value) {
        if(typeof value == "number") {
            var reading = new SmSc.Reading(this, value, 0);
            reading.insert();
            this.readings.push(reading);
        }
    }
}

SmSc.getSensors = function getSensors(callback) {
    $.ajax(SmSc.url + "/getSensors.php", {
        method:"GET",
        dataType:"JSON",
        data:SmSc.credentials,
        success:function(response) {
            var sensors = [];
            for(var x in response.sensors) {
                var object = response.sensors[x].sensor;
                var sensor = new SmSc.Sensor(object.id, object.location, object.type);
                for(var y in response.sensors[x].readings){
                    var object2 = response.sensors[x].readings[y];
                    var reading = new SmSc.Reading(sensor, object2.value, object2.dateTime);
                    sensor.readings.push(reading);
                }
                sensors.push(sensor);
            }
            callback(sensors);
        }
    })
}
<commit_msg>Fixed bugs<commit_after>var SmSc = SmSc || {};

SmSc.Sensor = class Sensor{
    /*
    * Create a sensor instance
    * @param {number} id The id of the sensor, null if not in database
    * @param {string} location The location of the sensor
    * @param {string} type The type of the sensor
    */
    constructor(id, location, type) {
        this.id = id;
        this.location = location;
        this.type = type;
        this.readings = [];
    }

    /*
    * Add the sensor to the database and set the id of the sensor
    * @param {function} callback The callback, will be executed when done
    */
    insert(callback) {
        var sensor = this;
        callback = callback || function(){};
        $.ajax(SmSc.url + "/addSensor.php", {
            method:"GET",
            dataType:"JSON",
            data:SmSc.addCredentials({
                location:sensor.location,
                type:sensor.type
            }),
            success:function(response) {
                var nSensor = response.sensor || {};
                sensor.id = nSensor.id;

                var err = response.err || null;

                if(response.err) callback(null, err);
                else callback(sensor, err);
            },
            error:function() {
                console.log(arguments);
                callback(sensor, "the http request failed");
            }
        });
    }

    get reading() {
        return _.last(_.sortBy(this.readings, "dateTime"));
    }

    set reading(value) {
        if(typeof value == "number") {
            var reading = new SmSc.Reading(this, value, 0);
            reading.insert();
            this.readings.push(reading);
        } else {
            var reading = value;
            reading.insert();
            this.readings.push(reading);
        }
    }
}

SmSc.getSensors = function getSensors(callback) {
    $.ajax(SmSc.url + "/getSensors.php", {
        method:"GET",
        dataType:"JSON",
        data:SmSc.credentials,
        success:function(response) {
            console.log(response);
            var sensors = [];
            for(var x in response.sensors) {
                var object = response.sensors[x].sensor;
                var sensor = new SmSc.Sensor(object.id, object.location, object.type);
                for(var y in response.sensors[x].readings){
                    var object2 = response.sensors[x].readings[y];
                    var reading = new SmSc.Reading(sensor, object2.value, object2.dateTime);
                    sensor.readings.push(reading);
                }
                sensors.push(sensor);
            }
            callback(sensors);
        }
    })
}
<|endoftext|>


<commit_before>'use strict'

// Dependencies (tests)
const chai = require('chai');
chai.should();

// Dependencies (application)
const Wrapper = require('../src/wrapper');
const Linker = require('../src/linker');
const Parser = require('../src/parser');
const ReaderError = require('../src/error');

// Dependencies (local)
let reader;
const rand = Date.now();
const data = require('./mocha.data');
const entryId = '***REMOVED***';
const circularEntryId = '***REMOVED***';
const spaceId = '***REMOVED***';
const qaEntry = 'qaEntry';
const entryTitle = 'Test Entry';

// create reader to use for tests
before(done => {
    reader = new Wrapper(
        spaceId,
        '***REMOVED***');
    done();
});

describe('Wrapper', () => {

    describe('getSpace', () => {

        it('should return data about the registered space', done => {
            return reader.getSpace().then(res => {
                res.sys.id.should.equal(spaceId);
                done();
            }, err => {
                done(err);
            });
        });

    });

    describe('getEntries', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.getEntries().then(res => {
                res.should.have.property('total');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            return reader.getEntries({
                content_type: qaEntry
            }).then(res => {
                res.should.have.property('items');
                res.total.should.equal(1);
                res.items[0].sys.contentType.sys.should.have.property('id', qaEntry);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.getEntries({
                content_type: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });

    });

    describe('getAssets', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.getAssets().then(res => {
                res.should.have.property('total');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            const assetCriteria = 'image/jpeg';
            return reader.getAssets({
                'fields.file.contentType': assetCriteria
            }).then(res => {
                res.should.have.property('items');
                res.total.should.be.above(0);
                res.items[0].fields.file.contentType.should.equal(assetCriteria);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no assets match', done => {
            return reader.getEntries({
                'fields.file.contentType': 'image/nope'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });
    });

    describe('getEntry', () => {

        it('should return first entry when no criteria is passed', done => {
            return reader.getEntry().then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return first entry that matches criteria specified', done => {
            return reader.getEntry({
                content_type: qaEntry
            }).then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.getEntry({
                content_type: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });
    });

    describe('getAsset', () => {

        it('should return first asset when no criteria is passed', done => {
            return reader.getAsset().then(res => {
                res.sys.should.have.property('type', 'Asset');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return first asset that matches criteria specified', done => {
            const assetCriteria = 'image/jpeg';
            return reader.getAsset({
                'fields.file.contentType': assetCriteria
            }).then(res => {
                res.sys.should.have.property('type', 'Asset');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no assets match', done => {
            return reader.getAsset({
                'fields.file.contentType': 'image/nope'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });

    });

    describe('getEntryById', () => {

        it('should return an single entry when requesting by id', done => {
            return reader.getEntryById(entryId).then(entry => {
                entry.sys.should.have.property('id');
                entry.sys.id.should.equal(entryId);
                done();
            }, err => {
                done(err);
            });
        });

    });

    describe('getAssetById', () => {

        it('should return an single asset when requesting by id', done => {
            const assetId = '6JCShApjO0O4CUkUKAKAaS';
            return reader.getAssetById(assetId).then(entry => {
                entry.sys.should.have.property('id');
                entry.sys.id.should.equal(assetId);
                done();
            }, err => {
                done(err);
            });
        });
    });

    describe('getEntriesByType', () => {
        it('should return entries by content type', done => {
            return reader.getEntriesByType(qaEntry).then(entries => {
                entries.should.have.property('items');
                entries.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });
    });

    describe('findEntryByType', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.findEntryByType(qaEntry).then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            return reader.findEntryByType(qaEntry, {
                title: entryTitle
            }).then(res => {
                res.sys.should.have.property('type', 'Entry');
                res.fields.title.should.equal(entryTitle);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.findEntryByType(qaEntry, {
                title: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });
    });

    describe('findEntriesByType', () => {

        it('should return all entries that match the criteria', done => {
            return reader.findEntriesByType(qaEntry, {
                title: entryTitle
            }).then(res => {
                res.should.have.property('items');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.findEntriesByType(qaEntry, {
                title: 'qaEntryNOPE'
            }).then(res => {
                res.total.should.equal(0);
                done();
            }, err => {
                done(err);
            });
        });
    });

});

describe('Parser', () => {

    describe('one', () => {

        it('should parse a single object', () => {
            const parsed = Parser.one(data.unparsed);
            parsed.should.deep.equal(data.parsed);
        });

        it('should reject an array', () => {
            const parsed = Parser.one(data.unparsedArr);
            parsed.should.deep.equal(data.unparsedArr);
        });

    });

    describe('all', () => {

        it('should parse an array', () => {
            const parsed = Parser.all(data.unparsedArr);
            parsed.should.deep.equal(data.parsedArr);
        });

        it('should put a single object in the form of a parsed array', () => {
            const parsed = Parser.all(data.unparsed);
            parsed.meta.should.have.property('total').that.equals(1);
            parsed.should.have.property('items').that.is.an('array');
            parsed.items[0].should.deep.equal(data.parsed);
        });

    });

    describe('it', () => {

        it('should parse a single object', () => {
            const parsed = Parser.it(data.unparsed);
            parsed.should.deep.equal(data.parsed);
        });

        it('should parse an array', () => {
            const parsed = Parser.it(data.unparsed);
            parsed.should.deep.equal(data.parsed);
        });

    });

});

describe('Linker', () => {

    describe('then', () => {

        it('should still run then functions', done => {
            return new Linker(Promise.resolve(rand)).then(res => {
                res.should.equal(rand);
                done();
            });
        });

    });

    describe('catch', () => {

        it('should still run catch statements with then statements', done => {
            return new Linker(Promise.reject(rand)).then(res => {
                // shouldn't get here...
            }, err => {
                err.should.equal(rand);
                done();
            });
        });

        it('should still run catch statements standalone', done => {
            return new Linker(Promise.reject(rand)).catch(res => {
                res.should.equal(rand);
                done();
            });
        });

    });

    describe('parse', () => {

        it('should parse in place of then', done => {
            return new Linker(Promise.resolve(data.unparsed)).parse(res => {
                res.should.deep.equal(data.parsed);
                done();
            }, err => {
                done(err);
            });
        });

        it('should parse as a chain before then', done => {
            return new Linker(Promise.resolve(data.unparsed)).parse().then(res => {
                res.should.deep.equal(data.parsed);
                done();
            }, err => {
                done(err);
            });
        });

        it('should be able to parse a circularly referenced object', done => {
            return reader.getEntryById(circularEntryId).parse(entry => {
                let nested = entry.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref;
                nested.id.should.equal(circularEntryId);
                nested.should.not.have.property('sys');
                done();
            }, err => {
                done(err);
            });
        });

    });

});

describe('Error', () => {

    describe('ReaderError', () => {

        var err = new ReaderError(rand);

        it('should be of custom type', () => {
            err.constructor.name.should.equal('ReaderError');
        });

        it('should have a message', () => {
            err.message.should.equal(rand);
        });

    });

});
<commit_msg>Update to tests<commit_after>'use strict'

// Dependencies (tests)
const chai = require('chai');
chai.should();

// Dependencies (application)
const Wrapper = require('../src/wrapper');
const Linker = require('../src/linker');
const Parser = require('../src/parser');
const ReaderError = require('../src/error');
const cloneDeep = require('lodash.clonedeep');

// Dependencies (local)
let reader;
const rand = Date.now();
const data = require('./mocha.data');
const entryId = '***REMOVED***';
const circularEntryId = '***REMOVED***';
const spaceId = '***REMOVED***';
const qaEntry = 'qaEntry';
const entryTitle = 'Test Entry';

// create reader to use for tests
before(done => {
    reader = new Wrapper(
        spaceId,
        '***REMOVED***');
    done();
});

describe('Wrapper', () => {

    describe('getSpace', () => {

        it('should return data about the registered space', done => {
            return reader.getSpace().then(res => {
                res.sys.id.should.equal(spaceId);
                done();
            }, err => {
                done(err);
            });
        });

    });

    describe('getEntries', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.getEntries().then(res => {
                res.should.have.property('total');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            return reader.getEntries({
                content_type: qaEntry
            }).then(res => {
                res.should.have.property('items');
                res.total.should.equal(1);
                res.items[0].sys.contentType.sys.should.have.property('id', qaEntry);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.getEntries({
                content_type: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });

    });

    describe('getAssets', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.getAssets().then(res => {
                res.should.have.property('total');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            const assetCriteria = 'image/jpeg';
            return reader.getAssets({
                'fields.file.contentType': assetCriteria
            }).then(res => {
                res.should.have.property('items');
                res.total.should.be.above(0);
                res.items[0].fields.file.contentType.should.equal(assetCriteria);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no assets match', done => {
            return reader.getEntries({
                'fields.file.contentType': 'image/nope'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });
    });

    describe('getEntry', () => {

        it('should return first entry when no criteria is passed', done => {
            return reader.getEntry().then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return first entry that matches criteria specified', done => {
            return reader.getEntry({
                content_type: qaEntry
            }).then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.getEntry({
                content_type: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });
    });

    describe('getAsset', () => {

        it('should return first asset when no criteria is passed', done => {
            return reader.getAsset().then(res => {
                res.sys.should.have.property('type', 'Asset');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return first asset that matches criteria specified', done => {
            const assetCriteria = 'image/jpeg';
            return reader.getAsset({
                'fields.file.contentType': assetCriteria
            }).then(res => {
                res.sys.should.have.property('type', 'Asset');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no assets match', done => {
            return reader.getAsset({
                'fields.file.contentType': 'image/nope'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });

    });

    describe('getEntryById', () => {

        it('should return an single entry when requesting by id', done => {
            return reader.getEntryById(entryId).then(entry => {
                entry.sys.should.have.property('id');
                entry.sys.id.should.equal(entryId);
                done();
            }, err => {
                done(err);
            });
        });

    });

    describe('getAssetById', () => {

        it('should return an single asset when requesting by id', done => {
            const assetId = '6JCShApjO0O4CUkUKAKAaS';
            return reader.getAssetById(assetId).then(entry => {
                entry.sys.should.have.property('id');
                entry.sys.id.should.equal(assetId);
                done();
            }, err => {
                done(err);
            });
        });
    });

    describe('getEntriesByType', () => {
        it('should return entries by content type', done => {
            return reader.getEntriesByType(qaEntry).then(entries => {
                entries.should.have.property('items');
                entries.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });
    });

    describe('findEntryByType', () => {

        it('should return all entries when no criteria is passed', done => {
            return reader.findEntryByType(qaEntry).then(res => {
                res.sys.should.have.property('type', 'Entry');
                done();
            }, err => {
                done(err);
            });
        });

        it('should return entries that match criteria specified', done => {
            return reader.findEntryByType(qaEntry, {
                title: entryTitle
            }).then(res => {
                res.sys.should.have.property('type', 'Entry');
                res.fields.title.should.equal(entryTitle);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.findEntryByType(qaEntry, {
                title: 'qaEntryNOPE'
            }).then(res => {
                done(new Error("Expected an error..."));
            }, err => {
                err.message.should.be.a('string');
                done();
            });
        });
    });

    describe('findEntriesByType', () => {

        it('should return all entries that match the criteria', done => {
            return reader.findEntriesByType(qaEntry, {
                title: entryTitle
            }).then(res => {
                res.should.have.property('items');
                res.total.should.be.above(0);
                done();
            }, err => {
                done(err);
            });
        });

        it('should return nothing if no entries match', done => {
            return reader.findEntriesByType(qaEntry, {
                title: 'qaEntryNOPE'
            }).then(res => {
                res.total.should.equal(0);
                done();
            }, err => {
                done(err);
            });
        });
    });

});

describe('Parser', () => {

    describe('one', () => {

        it('should parse a single object', () => {
            const parsed = Parser.one(cloneDeep(data.unparsed));
            parsed.should.deep.equal(data.parsed);
        });

        it('should reject an array', () => {
            const parsed = Parser.one(cloneDeep(data.unparsedArr));
            parsed.should.deep.equal(data.unparsedArr);
        });

    });

    describe('all', () => {

        it('should parse an array', () => {
            const parsed = Parser.all(cloneDeep(data.unparsedArr));
            parsed.should.deep.equal(data.parsedArr);
        });

        it('should put a single object in the form of a parsed array', () => {
            const parsed = Parser.all(cloneDeep(data.unparsed));
            parsed.meta.should.have.property('total').that.equals(1);
            parsed.should.have.property('items').that.is.an('array');
            parsed.items[0].should.deep.equal(data.parsed);
        });

    });

    describe('it', () => {

        it('should parse a single object', () => {
            const parsed = Parser.it(data.unparsed);
            parsed.should.deep.equal(data.parsed);
        });

        it('should parse an array', () => {
            const parsed = Parser.it(data.unparsed);
            parsed.should.deep.equal(data.parsed);
        });

    });

});

describe('Linker', () => {

    describe('then', () => {

        it('should still run then functions', done => {
            return new Linker(Promise.resolve(rand)).then(res => {
                res.should.equal(rand);
                done();
            });
        });

    });

    describe('catch', () => {

        it('should still run catch statements with then statements', done => {
            return new Linker(Promise.reject(rand)).then(res => {
                // shouldn't get here...
            }, err => {
                err.should.equal(rand);
                done();
            });
        });

        it('should still run catch statements standalone', done => {
            return new Linker(Promise.reject(rand)).catch(res => {
                res.should.equal(rand);
                done();
            });
        });

    });

    describe('parse', () => {

        it('should parse in place of then', done => {
            return new Linker(Promise.resolve(data.unparsed)).parse(res => {
                res.should.deep.equal(data.parsed);
                done();
            }, err => {
                done(err);
            });
        });

        it('should parse as a chain before then', done => {
            return new Linker(Promise.resolve(data.unparsed)).parse().then(res => {
                res.should.deep.equal(data.parsed);
                done();
            }, err => {
                done(err);
            });
        });

        it('should be able to parse a circularly referenced object', done => {
            return reader.getEntryById(circularEntryId).parse(entry => {
                let nested = entry.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref.fields.ref;
                nested.id.should.equal(circularEntryId);
                nested.should.not.have.property('sys');
                done();
            }, err => {
                done(err);
            });
        });

    });

});

describe('Error', () => {

    describe('ReaderError', () => {

        var err = new ReaderError(rand);

        it('should be of custom type', () => {
            err.constructor.name.should.equal('ReaderError');
        });

        it('should have a message', () => {
            err.message.should.equal(rand);
        });

    });

});
<|endoftext|>


<commit_before>'use strict';

var moar = require('../lib/moar.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['moar'] = {
  setUp: function(done) {
    // setup here
    done();
  },
  'functions': function(test) {
    test.expect(2);
    // tests here
    test.ok(typeof moar.get === "function", 'should define a get function.');
    test.ok(typeof moar.search === "function", 'should define a search function.');
    test.done();
  },
  'get': function(test) {
    test.expect(1);
    moar.get({"board": "v"}, function(data) {
      test.ok(data,"should make a request to 4chan\'s API, sending either a json response or an error object to the callback.");
      test.done();
    });
  },
  'get exceptions': function(test) {
    test.expect(3);
    try {
      moar.get();
    } catch (err) {
      test.equal(err.message, "ArgumentError: Wrong number of arguments: 0 for [1 - 2].", "should throw errors on incorrect usage. (too few arguments)");
    }
    try {
      moar.get("one", "two", "three");
    } catch (err) {
      test.equal(err.message, "ArgumentError: Wrong number of arguments: 3 for [1 - 2].", "should throw errors on incorrect usage. (too many arguments)");
    }
    try {
      moar.get("wrong", "arguments");
    } catch (err) {
      test.equal(err.message, "ArgumentError: Must provide a callback function.", "should throw errors on incorrect usage. (no callback)");
    }
    test.done();
  },
  'search': function(test) {
    test.expect(1);
    moar.search({"board": "v", "term": "pokemon"}, function(data) {
      test.ok(data, "should make a request to 4chan\'s API, sending either a json response or an error object to the callback.");
      test.done();
    });
  }
};
<commit_msg>Refactor get test function<commit_after>'use strict';

var moar = require('../lib/moar.js'),
    _ = require('lodash');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['moar'] = {
  setUp: function(done) {
    // setup here
    done();
  },
  'functions': function(test) {
    test.expect(2);
    // tests here
    test.ok(typeof moar.get === "function", 'should define a get function.');
    test.ok(typeof moar.search === "function", 'should define a search function.');
    test.done();
  },
  'get': function(test) {
    test.expect(1);
    moar.get({"board": "v"}, function(data) {
      test.ok(_(data).some(function(el) { return el.threads; }) || data.error ,"should make a request to 4chan\'s API, sending either a json response or an error object to the callback.");
      test.done();
    });
  },
  'get exceptions': function(test) {
    test.expect(3);
    try {
      moar.get();
    } catch (err) {
      test.equal(err.message, "ArgumentError: Wrong number of arguments: 0 for [1 - 2].", "should throw errors on incorrect usage. (too few arguments)");
    }
    try {
      moar.get("one", "two", "three");
    } catch (err) {
      test.equal(err.message, "ArgumentError: Wrong number of arguments: 3 for [1 - 2].", "should throw errors on incorrect usage. (too many arguments)");
    }
    try {
      moar.get("wrong", "arguments");
    } catch (err) {
      test.equal(err.message, "ArgumentError: Must provide a callback function.", "should throw errors on incorrect usage. (no callback)");
    }
    test.done();
  },
  'search': function(test) {
    test.expect(1);
    moar.search({"board": "v", "term": "pokemon"}, function(data) {
      test.ok(data, "should make a request to 4chan\'s API, sending either a json response or an error object to the callback.");
      test.done();
    });
  }
};
<|endoftext|>


<commit_before>'use strict'

const getTiming = require('./timing')
const post = require('./post')
const getPosition = require('./position')
const getNav = require('./nav')
const getNetwork = require('./network')
const getLastImgTiming = require('./resource_timing/last_img_timing')
const getAjaxTiming = require('./resource_timing/ajax_timing.js')

document.addEventListener('DOMContentLoaded', () => {
  post({hello: 'world!'})
})

window.onload = () => {
  const ua = navigator.userAgent
  const timing = getTiming()
  const url = window.location.href
  const nav = getNav()
  const lang = navigator.language
  const resolution = {width: screen.width, height: screen.height}
  const network = getNetwork()
  const resourceTiming = performance.getEntriesByType('resource')

  const lastImgTiming = getLastImgTiming(resourceTiming)
  const ajaxTiming = getAjaxTiming(resourceTiming)

  let data = { ua, timing, url, nav, lang, resolution, network, lastImgTiming, ajaxTiming }

  navigator.geolocation.getCurrentPosition((postion) => {
    const ps = getPosition(postion)
    post(Object.assign(data, {ps}))
  }, () => {
    post(data)
  })
}
<commit_msg>add referrer<commit_after>'use strict'

const getTiming = require('./timing')
const post = require('./post')
const getPosition = require('./position')
const getNav = require('./nav')
const getNetwork = require('./network')
const getLastImgTiming = require('./resource_timing/last_img_timing')
const getAjaxTiming = require('./resource_timing/ajax_timing.js')

document.addEventListener('DOMContentLoaded', () => {
  post({hello: 'world!'})
})

window.onload = () => {
  const ua = navigator.userAgent
  const timing = getTiming()
  const url = window.location.href
  const ref = document.referrer
  const nav = getNav()
  const lang = navigator.language
  const resolution = {width: screen.width, height: screen.height}
  const network = getNetwork()
  const resourceTiming = performance.getEntriesByType('resource')

  const lastImgTiming = getLastImgTiming(resourceTiming)
  const ajaxTiming = getAjaxTiming(resourceTiming)

  let data = { ua, timing, url, nav, lang, resolution, network,
    lastImgTiming, ajaxTiming, ref}

  navigator.geolocation.getCurrentPosition((postion) => {
    const ps = getPosition(postion)
    post(Object.assign(data, {ps}))
  }, () => {
    post(data)
  })
}
<|endoftext|>


<commit_before>
var connect = require('../')
  , should = require('./shared');

var app = connect();

app.use(connect.multipart({ limit: '20mb' }));

app.use(function(req, res){
  res.end(JSON.stringify(req.body));
});

describe('connect.multipart()', function(){
  should['default request body'](app);
  should['limit body to']('20mb', 'multipart/form-data', app);

  it('should ignore GET', function(done){
    app.request()
    .get('/')
    .set('Content-Type', 'multipart/form-data; boundary=foo')
    .write('--foo\r\n')
    .write('Content-Disposition: form-data; name="user"\r\n')
    .write('\r\n')
    .write('Tobi')
    .write('\r\n--foo--')
    .end(function(res){
      res.body.should.equal('{}');
      done();
    });
  })

  describe('with multipart/form-data', function(){
    it('should populate req.body', function(done){
      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user"\r\n')
      .write('\r\n')
      .write('Tobi')
      .write('\r\n--foo--')
      .end(function(res){
        res.body.should.equal('{"user":"Tobi"}');
        done();
      });
    })

    it('should support files', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        req.body.user.should.eql({ name: 'Tobi' });
        req.files.text.path.should.not.include('.txt');
        req.files.text.constructor.name.should.equal('File');
        res.end(req.files.text.name);
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user[name]"\r\n')
      .write('\r\n')
      .write('Tobi')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="text"; filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('\r\n--foo--')
      .end(function(res){
        res.body.should.equal('foo.txt');
        done();
      });
    })

    it('should expose options to formidable', function(done){
      var app = connect();

      app.use(connect.multipart({
        keepExtensions: true
      }));

      app.use(function(req, res){
        req.body.user.should.eql({ name: 'Tobi' });
        req.files.text.path.should.include('.txt');
        req.files.text.constructor.name.should.equal('File');
        res.end(req.files.text.name);
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user[name]"\r\n')
      .write('\r\n')
      .write('Tobi')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="text"; filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('\r\n--foo--')
      .end(function(res){
        res.body.should.equal('foo.txt');
        done();
      });
    })

    it('should work with multiple fields', function(done){
      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user"\r\n')
      .write('\r\n')
      .write('Tobi')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="age"\r\n')
      .write('\r\n')
      .write('1')
      .write('\r\n--foo--')
      .end(function(res){
        res.body.should.equal('{"user":"Tobi","age":"1"}');
        done();
      });
    })

    it('should support nesting', function(done){
      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user[name][first]"\r\n')
      .write('\r\n')
      .write('tobi')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="user[name][last]"\r\n')
      .write('\r\n')
      .write('holowaychuk')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="user[age]"\r\n')
      .write('\r\n')
      .write('1')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="species"\r\n')
      .write('\r\n')
      .write('ferret')
      .write('\r\n--foo--')
      .end(function(res){
        var obj = JSON.parse(res.body);
        obj.user.age.should.equal('1');
        obj.user.name.should.eql({ first: 'tobi', last: 'holowaychuk' });
        obj.species.should.equal('ferret');
        done();
      });
    })

    it('should support multiple files of the same name', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        req.files.text.should.have.length(2);
        req.files.text[0].constructor.name.should.equal('File');
        req.files.text[1].constructor.name.should.equal('File');
        res.end();
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="text"; filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="text"; filename="bar.txt"\r\n')
      .write('\r\n')
      .write('some more text stuff')
      .write('\r\n--foo--')
      .end(function(res){
        res.statusCode.should.equal(200);
        done();
      });
    })

    it('should support nested files', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        Object.keys(req.files.docs).should.have.length(2);
        req.files.docs.foo.name.should.equal('foo.txt');
        req.files.docs.bar.name.should.equal('bar.txt');
        res.end();
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="docs[foo]"; filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="docs[bar]"; filename="bar.txt"\r\n')
      .write('\r\n')
      .write('some more text stuff')
      .write('\r\n--foo--')
      .end(function(res){
        res.statusCode.should.equal(200);
        done();
      });
    })

    it('should next(err) on multipart failure', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        res.end('whoop');
      });

      app.use(function(err, req, res, next){
        err.message.should.equal('parser error, 16 of 28 bytes parsed');
        next(err);
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('Content-Disposition: form-data; name="text"; filename="bar.txt"\r\n')
      .write('\r\n')
      .write('some more text stuff')
      .write('\r\n--foo--')
      .end(function(res){
        res.statusCode.should.equal(400);
        done();
      });
    })

    it('should default req.files to {}', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        res.end(JSON.stringify(req.files));
      });

      app.request()
      .post('/')
      .end(function(res){
        res.body.should.equal('{}');
        done();
      });
    })

  })
})<commit_msg>add body test for invalid multipart<commit_after>
var connect = require('../')
  , should = require('./shared');

var app = connect();

app.use(connect.multipart({ limit: '20mb' }));

app.use(function(req, res){
  res.end(JSON.stringify(req.body));
});

describe('connect.multipart()', function(){
  should['default request body'](app);
  should['limit body to']('20mb', 'multipart/form-data', app);

  it('should ignore GET', function(done){
    app.request()
    .get('/')
    .set('Content-Type', 'multipart/form-data; boundary=foo')
    .write('--foo\r\n')
    .write('Content-Disposition: form-data; name="user"\r\n')
    .write('\r\n')
    .write('Tobi')
    .write('\r\n--foo--')
    .end(function(res){
      res.body.should.equal('{}');
      done();
    });
  })

  describe('with multipart/form-data', function(){
    it('should populate req.body', function(done){
      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user"\r\n')
      .write('\r\n')
      .write('Tobi')
      .write('\r\n--foo--')
      .end(function(res){
        res.body.should.equal('{"user":"Tobi"}');
        done();
      });
    })

    it('should support files', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        req.body.user.should.eql({ name: 'Tobi' });
        req.files.text.path.should.not.include('.txt');
        req.files.text.constructor.name.should.equal('File');
        res.end(req.files.text.name);
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user[name]"\r\n')
      .write('\r\n')
      .write('Tobi')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="text"; filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('\r\n--foo--')
      .end(function(res){
        res.body.should.equal('foo.txt');
        done();
      });
    })

    it('should expose options to formidable', function(done){
      var app = connect();

      app.use(connect.multipart({
        keepExtensions: true
      }));

      app.use(function(req, res){
        req.body.user.should.eql({ name: 'Tobi' });
        req.files.text.path.should.include('.txt');
        req.files.text.constructor.name.should.equal('File');
        res.end(req.files.text.name);
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user[name]"\r\n')
      .write('\r\n')
      .write('Tobi')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="text"; filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('\r\n--foo--')
      .end(function(res){
        res.body.should.equal('foo.txt');
        done();
      });
    })

    it('should work with multiple fields', function(done){
      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user"\r\n')
      .write('\r\n')
      .write('Tobi')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="age"\r\n')
      .write('\r\n')
      .write('1')
      .write('\r\n--foo--')
      .end(function(res){
        res.body.should.equal('{"user":"Tobi","age":"1"}');
        done();
      });
    })

    it('should support nesting', function(done){
      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="user[name][first]"\r\n')
      .write('\r\n')
      .write('tobi')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="user[name][last]"\r\n')
      .write('\r\n')
      .write('holowaychuk')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="user[age]"\r\n')
      .write('\r\n')
      .write('1')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="species"\r\n')
      .write('\r\n')
      .write('ferret')
      .write('\r\n--foo--')
      .end(function(res){
        var obj = JSON.parse(res.body);
        obj.user.age.should.equal('1');
        obj.user.name.should.eql({ first: 'tobi', last: 'holowaychuk' });
        obj.species.should.equal('ferret');
        done();
      });
    })

    it('should support multiple files of the same name', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        req.files.text.should.have.length(2);
        req.files.text[0].constructor.name.should.equal('File');
        req.files.text[1].constructor.name.should.equal('File');
        res.end();
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="text"; filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="text"; filename="bar.txt"\r\n')
      .write('\r\n')
      .write('some more text stuff')
      .write('\r\n--foo--')
      .end(function(res){
        res.statusCode.should.equal(200);
        done();
      });
    })

    it('should support nested files', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        Object.keys(req.files.docs).should.have.length(2);
        req.files.docs.foo.name.should.equal('foo.txt');
        req.files.docs.bar.name.should.equal('bar.txt');
        res.end();
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-Disposition: form-data; name="docs[foo]"; filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('\r\n--foo\r\n')
      .write('Content-Disposition: form-data; name="docs[bar]"; filename="bar.txt"\r\n')
      .write('\r\n')
      .write('some more text stuff')
      .write('\r\n--foo--')
      .end(function(res){
        res.statusCode.should.equal(200);
        done();
      });
    })

    it('should next(err) on multipart failure', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        res.end('whoop');
      });

      app.use(function(err, req, res, next){
        err.message.should.equal('parser error, 16 of 28 bytes parsed');
        res.statusCode = err.status;
        res.end('bad request');
      });

      app.request()
      .post('/')
      .set('Content-Type', 'multipart/form-data; boundary=foo')
      .write('--foo\r\n')
      .write('Content-filename="foo.txt"\r\n')
      .write('\r\n')
      .write('some text here')
      .write('Content-Disposition: form-data; name="text"; filename="bar.txt"\r\n')
      .write('\r\n')
      .write('some more text stuff')
      .write('\r\n--foo--')
      .end(function(res){
        res.statusCode.should.equal(400);
        res.body.should.equal('bad request');
        done();
      });
    })

    it('should default req.files to {}', function(done){
      var app = connect();

      app.use(connect.multipart());

      app.use(function(req, res){
        res.end(JSON.stringify(req.files));
      });

      app.request()
      .post('/')
      .end(function(res){
        res.body.should.equal('{}');
        done();
      });
    })

  })
})<|endoftext|>