<commit_before>(function(root) {

  'use strict';

  root.app = root.app || {};

  root.app.Router = Backbone.Router.extend({

    routes: {
      // HOME
      '': 'home',
      // MAP BUILDER
      'map-builder(/)': 'map-builder',
      // GALLERY
      'gallery(/)': 'gallery',
      // DEVELOP YOUR OWN APP
      'develop-your-own-app(/)': 'develop',
    },

    ParamsModel: Backbone.Model.extend({}),

    initialize: function(settings) {
      var opts = settings && settings.options ? settings.options : {};
      this.options = _.extend({}, this.defaults, opts);

      this.params = new this.ParamsModel(); // This object save the URL params
      this.setListeners();
    },

    setListeners: function() {
      Backbone.Events.on('route/update', function(params) {
        _.each(params,function(v,k){
          this.setParams(k,v);
        }.bind(this));
        this.updateUrl();
      }.bind(this));
    },

    /**
     * Set params and update model
     * @param {String} name
     * @param {String|Object|Array} value
     * @param {Array[String]} keys
     */
    setParams: function(name, value, keys) {
      if (typeof value === 'string' || typeof value === 'number') {
        this.params.set(name, value);
      } else if (typeof value === 'object' && !_.isArray(value)) {
        if (keys && _.isArray(keys)) {
          // var params = _.pick(value, 'id', 'opacity', 'order');
          // this.params.set(name, JSON.stringify(params));
        } else {
          if (!!value) {
            this.params.set(name, JSON.stringify(value));
          } else {
            this.params.set(name, value);
          }
        }
      } else if (typeof value === 'object' && _.isArray(value)) {
        if (keys && _.isArray(keys)) {
          var params = _.map(value, function(v) {
            return _.pick(v, keys);
          });
          this.params.set(name, JSON.stringify(params));
        } else {
          this.params.set(name, JSON.stringify(value));
        }
      }
    },

    /**
     * Change url with params
     */
    updateUrl: function() {
      var serializedParams = (!!this._serializeParams()) ? '?' + this._serializeParams() : '';
      console.log(location.pathname);
      var url = location.hostname + location.pathname + serializedParams;
      console.log(url);
      this.navigate(url, { trigger: false });
    },

    /**
     * This method will update this.params object when URL change
     * @param  {String} routeName
     * @param  {Array} params
     */
    updateParams: function(params, routeName) {
      if (this.options.decoded && params[0]) {
        try {
          params = this._decodeParams(params[0]);
        } catch(err) {
          console.error('Invalid params. ' + err);
          params = null;
          return this.navigate('');
        }
        this.params.clear({ silent: true }).set({ config: params });
      } else {
        var p = this._unserializeParams();
        this.params.clear({ silent: true }).set(this._unserializeParams());
      }
    },

    /**
     * Transform URL string params to object
     * @return {Object}
     */
    _unserializeParams: function() {
      var params = {};
      if (location.search.length) {
        var paramsArr = decodeURIComponent(location.search.slice(1)).split('&'),
          temp = [];
        for (var p = paramsArr.length; p--;) {
          temp = paramsArr[p].split('=');
          if (temp[1] && !_.isNaN(Number(temp[1]))) {
            params[temp[0]] = Number(temp[1]);
          } else if (temp[1]) {
            params[temp[0]] = temp[1];
          }
        }
      }
      return params;
    },

    /**
     * Transform object params to URL string
     * @return {String}
     */
    _serializeParams: function() {
      if (!!this.params) {
        var str = [];
        var obj = this.params.attributes;
        for(var p in obj) {
          if (obj.hasOwnProperty(p) && !!obj[p]) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
          }
        }
        return str.join("&");
      }
    }

  });

})(this);
<commit_msg>Static: router static in PRO mode<commit_after>(function(root) {

  'use strict';

  root.app = root.app || {};

  root.app.Router = Backbone.Router.extend({

    routes: {
      // HOME
      '': 'home',
      // MAP BUILDER
      'map-builder(/)': 'map-builder',
      // GALLERY
      'gallery(/)': 'gallery',
      // DEVELOP YOUR OWN APP
      'develop-your-own-app(/)': 'develop',
    },

    ParamsModel: Backbone.Model.extend({}),

    initialize: function(settings) {
      var opts = settings && settings.options ? settings.options : {};
      this.options = _.extend({}, this.defaults, opts);

      this.params = new this.ParamsModel(); // This object save the URL params
      this.setListeners();
    },

    setListeners: function() {
      Backbone.Events.on('route/update', function(params) {
        _.each(params,function(v,k){
          this.setParams(k,v);
        }.bind(this));
        this.updateUrl();
      }.bind(this));
    },

    /**
     * Set params and update model
     * @param {String} name
     * @param {String|Object|Array} value
     * @param {Array[String]} keys
     */
    setParams: function(name, value, keys) {
      if (typeof value === 'string' || typeof value === 'number') {
        this.params.set(name, value);
      } else if (typeof value === 'object' && !_.isArray(value)) {
        if (keys && _.isArray(keys)) {
          // var params = _.pick(value, 'id', 'opacity', 'order');
          // this.params.set(name, JSON.stringify(params));
        } else {
          if (!!value) {
            this.params.set(name, JSON.stringify(value));
          } else {
            this.params.set(name, value);
          }
        }
      } else if (typeof value === 'object' && _.isArray(value)) {
        if (keys && _.isArray(keys)) {
          var params = _.map(value, function(v) {
            return _.pick(v, keys);
          });
          this.params.set(name, JSON.stringify(params));
        } else {
          this.params.set(name, JSON.stringify(value));
        }
      }
    },

    /**
     * Change url with params
     */
    updateUrl: function() {
      var serializedParams = (!!this._serializeParams()) ? '?' + this._serializeParams() : '';
      var url = location.pathname.replace(baseurl,'') + serializedParams;
      this.navigate(url, { trigger: false });
    },

    /**
     * This method will update this.params object when URL change
     * @param  {String} routeName
     * @param  {Array} params
     */
    updateParams: function(params, routeName) {
      if (this.options.decoded && params[0]) {
        try {
          params = this._decodeParams(params[0]);
        } catch(err) {
          console.error('Invalid params. ' + err);
          params = null;
          return this.navigate('');
        }
        this.params.clear({ silent: true }).set({ config: params });
      } else {
        var p = this._unserializeParams();
        this.params.clear({ silent: true }).set(this._unserializeParams());
      }
    },

    /**
     * Transform URL string params to object
     * @return {Object}
     */
    _unserializeParams: function() {
      var params = {};
      if (location.search.length) {
        var paramsArr = decodeURIComponent(location.search.slice(1)).split('&'),
          temp = [];
        for (var p = paramsArr.length; p--;) {
          temp = paramsArr[p].split('=');
          if (temp[1] && !_.isNaN(Number(temp[1]))) {
            params[temp[0]] = Number(temp[1]);
          } else if (temp[1]) {
            params[temp[0]] = temp[1];
          }
        }
      }
      return params;
    },

    /**
     * Transform object params to URL string
     * @return {String}
     */
    _serializeParams: function() {
      if (!!this.params) {
        var str = [];
        var obj = this.params.attributes;
        for(var p in obj) {
          if (obj.hasOwnProperty(p) && !!obj[p]) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
          }
        }
        return str.join("&");
      }
    }

  });

})(this);
<|endoftext|>


<commit_before>/**
 * Created by mcellmi on 30/08/2016.
 */

'use strict';

// Add configuration management
const   fs      = require('fs'),
        path    = require('path'),
        nconf   = require('nconf');

// Create a main logging instance which can be used to co-ordinate logging
// across all modules
const   bunyan          = require('bunyan'),
        PrettyStream    = require('bunyan-prettystream'),
        prettyStdOut    = new PrettyStream();
prettyStdOut.pipe(process.stdout);

nconf.argv().env().file({file: './config/configuration.json'});

const   log             = bunyan.createLogger({
                            name: nconf.get('log:name'),
                            serializers: {
                                reason: bunyan.stdSerializers.err
                            },
                            streams: [{
                                level: nconf.get('log:logLevel'),
                                type: 'raw',
                                stream: prettyStdOut
                            }]
                        });

const Graph = require('../src/graph');
const Search = require('../src/graphSearch');

let graph = new Graph({
        log: log,
        dataFile: nconf.get('data:file'),
        maxDepth: nconf.get('search:maxDepth'),
        firstHitOnly: nconf.get('search:firstHitOnly')
    });

graph.readData()
    .then((result) => {

        let search = new Search(graph,{log: log});

        search.getPaths({source:"DOUG_BARTOLOMEO", destination:"*"});
    })
    .catch((error) => {
        log.error(error);
    });

<commit_msg>Added web server<commit_after>/**
 * Created by mcellmi on 30/08/2016.
 */

'use strict';

// Add configuration management
const   fs      = require('fs'),
        path    = require('path'),
        nconf   = require('nconf'),
        _       = require('lodash');

// Create a main logging instance which can be used to co-ordinate logging
// across all modules
const   bunyan          = require('bunyan'),
        PrettyStream    = require('bunyan-prettystream'),
        prettyStdOut    = new PrettyStream();
prettyStdOut.pipe(process.stdout);

nconf.argv().env().file({file: './config/configuration.json'});

const   log             = bunyan.createLogger({
                            name: nconf.get('log:name'),
                            serializers: {
                                reason: bunyan.stdSerializers.err
                            },
                            streams: [{
                                level: nconf.get('log:logLevel'),
                                type: 'raw',
                                stream: prettyStdOut
                            }]
                        });

const Graph = require('../src/graph');
const Search = require('../src/graphSearch');

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('public'));

let graph = new Graph({
        log: log,
        dataFile: nconf.get('data:file'),
        maxDepth: nconf.get('search:maxDepth'),
        firstHitOnly: nconf.get('search:firstHitOnly')
    });

graph.readData()
    .then((result) => {

        let search = new Search(graph,{log: log});

        app.get('/index.html', function (req, res) {
            res.sendFile( __dirname + "/" + "index.html" );
        })
        app.get('/bundle.js', function (req, res) {
            res.sendFile( __dirname + "/" + "bundle.js" );
        })

        app.get('/search', function (req, res) {

            // Prepare output in JSON format
            let searchConditions = {
                source:req.query.source,
                destination:req.query.destination,
                searchType:"shortestPath"
            };
            let results = search.getPaths(searchConditions);
            let response = "";
            for (let x = 0; x < results.length; ++x) {
                response = _.join(results[x], "->") + "
";
            }
            console.log(response);
            res.end(JSON.stringify(results));
        })

        app.get('/searchAll', function (req, res) {
            let results = search.revealContacts(req.query.source);
            let response = "";
            for (let x = 0; x < results.length; ++x) {
                response = _.join(results[x], "->") + "
";
            }
            console.log(response);
            res.end(JSON.stringify(results));
        })

        var server = app.listen(8081, function () {

            var host = server.address().address
            var port = server.address().port

            console.log("Example app listening at http://%s:%s", host, port)

        })

        //
        //
        // search.getPaths({source:"DOUG_BARTOLOMEO", destination:"*"});
        //
        // search.revealContacts("DOUG_BARTOLOMEO");
        //
        // let results = search.getPaths({source:"DOUG_BARTOLOMEO", destination:"JOSPEH_MONTUORI", searchType:"shortestPath"});
        //
        // for (let x = 0; x < results.length; ++x) {
        //     console.log(_.join(results[x],"->"));
        // }
    })
    .catch((error) => {
        log.error(error);
    });

<|endoftext|>


<commit_before><commit_msg>Add tests for saga `getAlbumImages`<commit_after>import axios from 'axios';
import expect from 'expect';
import { put, select } from 'redux-saga/effects';

import getAlbumImages from '../get-album-images';
import { selectToken } from 'interactions/user/selectors';

describe('saga getAlbumImages', () => {
  const initialAction = { payload: { id: 'albumId' } };

  it('should select the token from the state', () => {
    const gen = getAlbumImages(initialAction);
    const next = gen.next();

    expect(next.value).toEqual(select(selectToken));
  });

  it('should call function axios.get', () => {
    const gen = getAlbumImages(initialAction);

    gen.next();
    const next = gen.next();

    expect(next.value.CALL.fn).toEqual(axios.get);
  });

  it('should put action GET_ALBUM_SUCCESS on success', () => {
    const gen = getAlbumImages(initialAction);
    const response = {
      data: {
        data: { id: 'ID1', images: [{ id: 'ID' }] },
      },
    };
    const action = {
      type: 'GET_ALBUM_SUCCESS',
      payload: {
        id: 'ID1',
        images: { ID: { id: 'ID' } },
      },
    };

    gen.next();
    gen.next();
    const next = gen.next(response);

    expect(next.value).toEqual(put(action));
  });

  it('should put action GET_ALBUM_FAILED on failure', () => {
    const gen = getAlbumImages(initialAction);
    const action = { type: 'GET_ALBUM_FAILED', message: 'error message' };
    const error = new Error('error message');

    gen.next();
    const next = gen.throw(error);

    expect(next.value).toEqual(put(action));
  });
});
<|endoftext|>


<commit_before>const date_map = {
    'Wednesday': '2017-08-16',
    'Thursday': '2017-08-17',
    'Friday': '2017-08-18',
    'Saturday': '2017-08-19',
    'Sunday': '2017-08-20'
};

const time_zone = 'America/Indiana/Indianapolis';
const short_time_zone = 'EDT';

const date_re = /^(\w+) at {2}(\d+):(\d\d) ([AP])M$/;
const cost_re = /^\$(\d+).(\d\d)$/;

function storeEvent() {
    let event_details = collectEventFromPage();
    let expanded_details = expandEventDetails(event_details);
    let event_id = expanded_details['Game ID'];
    let event = convertEvent(expanded_details);
    console.log('Collected Event', event);
    document.dispatchEvent(new CustomEvent('Store_Event', {
        'detail': {
            'event_details': event,
            'event_id' : event_id
        }
    }));
}

function collectEventFromPage() {
    const attributes = [
        'Game ID',
        'Title',
        'Description',
        'Short Description',
        'Long Description',
        'Start Date & Time',
        'End Date & Time',
        'Location',
        'Web Address for more information',
        'Tournament',
        'Cost'
    ];

    let event_details = getAttributeValues(attributes);
    event_details['URL'] = document.location.href;

    return event_details;
}

function getAttributeValues(desired_attributes) {
    let attribute_values = {};
    $('div.attr > div.name').each(function (index, element) {
        let attribute = $(element).text().trim().replace(/:$/, '').replace(/\s+/g, ' ');
        // console.log("Found " + attribute);
        if (desired_attributes.includes(attribute)) {
            attribute_values[attribute] = $(element).next().text().trim().replace(/\n/g, '');
            // console.log(attribute + ': ' + attribute_values[attribute]);
        }
    });
    return attribute_values;
}

function convertEvent(event_details) {
    let event = {
        'summary': generateEventSummary(event_details),
        'location': event_details['Location'],
        'description': generateEventDescription(event_details),
        'start': {
            'dateTime': generateDateTime(event_details['Start Date & Time']).toISOString(),
            'timeZone': time_zone
        },
        'end': {
            'dateTime': generateDateTime(event_details['End Date & Time']).toISOString(),
            'timeZone': time_zone
        },
        'extendedProperties': {
            'shared': {}
        }
    }
    event['extendedProperties']['shared']['gen_con_event_'+event_details['Game ID']] = 1;

    return event;
}

function expandEventDetails(event_details) {
    event_details['Short Timeframe'] = generateShortTimeframe(
        event_details['Start Date & Time'], event_details['End Date & Time']
    );

    event_details['Short Cost'] = generateShortCost(event_details['Cost']);

    event_details['Is Tournament'] = isTournament(event_details['Tournament']);

    return event_details;
}

function generateShortTimeframe(start, end) {
    let [, , start_hour, start_minute, start_ampm] = date_re.exec(start);
    let [, , end_hour, end_minute, end_ampm] = date_re.exec(end);
    start_ampm = start_ampm.toLowerCase();
    end_ampm = end_ampm.toLowerCase();

    let start_part = '';
    if (start_hour === '12' && start_minute === '00') {
        if (start_ampm === 'a') {
            start_part = 'M';
        } else if (start_ampm === 'p') {
            start_part = 'N';
        }
    } else if (start_part === '' && start_minute === '00') {
        start_part = start_hour;
    } else {
        start_part = start_hour + start_minute;
    }

    let end_part = '';
    if (end_hour === '12' && end_minute === '00') {
        if (end_ampm === 'a') {
            end_part = 'M';
        } else if (end_ampm === 'p') {
            end_part = 'N';
        }
    } else if (end_part === '' && end_minute === '00') {
        end_part = end_hour + end_ampm;
    } else {
        end_part = end_hour + end_minute + end_ampm;
    }

    if (start_part !== 'M' && start_part !== 'N' && start_ampm !== end_ampm) {
        start_part += start_ampm;
    }

    return start_part + '-' + end_part;
}

function generateShortCost(cost) {
    [, dollars, cents] = cost_re.exec(cost);
    if (dollars === '0' && cents === '00') {
        return 'FREE';
    }
    return (cents === '00') ? '$' + dollars : cost;
}

function isTournament(tournament) {
    return (tournament.substr(0, 3) === 'Yes');
}

function generateEventSummary(event_details) {
    return [
        event_details['Short Timeframe'],
        event_details['Title'],
        '(' + event_details['Game ID'] + ')'
    ].join(' ');
}

function generateEventDescription(event_details) {
    // Generate web links
    let web_links = [event_details['URL']];
    if (event_details['Web Address for more information']) {
        web_links.push(event_details['Web Address for more information']);
    }

    // Start with web links
    let description_parts = [web_links.join("\n")];

    // Add Descriptions
    if (event_details['Short Description']) {
        description_parts.push(event_details['Short Description']);
    }
    if (event_details['Description']) {
        description_parts.push(event_details['Description']);
    }
    if (event_details['Long Description']) {
        description_parts.push(event_details['Long Description']);
    }

    // Add cost/tournament info
    if (event_details['Is Tournament']) {
        description_parts.push(event_details['Short Cost'] + ' Tournament');
    } else {
        description_parts.push(event_details['Short Cost']);
    }

    return description_parts.join("\n\n");
}

function generateDateTime(time) {
    let [, day_of_week, hour, minute, ampm] = date_re.exec(time);
    let date = date_map[day_of_week];
    return new Date(date + ' ' + hour + ':' + minute + ' ' + ampm + 'M' + ' ' + short_time_zone);
}
<commit_msg>Some start/end times don't have extra spaces in them<commit_after>const date_map = {
    'Wednesday': '2017-08-16',
    'Thursday': '2017-08-17',
    'Friday': '2017-08-18',
    'Saturday': '2017-08-19',
    'Sunday': '2017-08-20'
};

const time_zone = 'America/Indiana/Indianapolis';
const short_time_zone = 'EDT';

const date_re = /^(\w+) at +(\d+):(\d\d) ([AP])M$/;
const cost_re = /^\$(\d+).(\d\d)$/;

function storeEvent() {
    let event_details = collectEventFromPage();
    let expanded_details = expandEventDetails(event_details);
    let event_id = expanded_details['Game ID'];
    let event = convertEvent(expanded_details);
    console.log('Collected Event', event);
    document.dispatchEvent(new CustomEvent('Store_Event', {
        'detail': {
            'event_details': event,
            'event_id' : event_id
        }
    }));
}

function collectEventFromPage() {
    const attributes = [
        'Game ID',
        'Title',
        'Description',
        'Short Description',
        'Long Description',
        'Start Date & Time',
        'End Date & Time',
        'Location',
        'Web Address for more information',
        'Tournament',
        'Cost'
    ];

    let event_details = getAttributeValues(attributes);
    event_details['URL'] = document.location.href;

    return event_details;
}

function getAttributeValues(desired_attributes) {
    let attribute_values = {};
    $('div.attr > div.name').each(function (index, element) {
        let attribute = $(element).text().trim().replace(/:$/, '').replace(/\s+/g, ' ');
        // console.log("Found " + attribute);
        if (desired_attributes.includes(attribute)) {
            attribute_values[attribute] = $(element).next().text().trim().replace(/\n/g, '');
            // console.log(attribute + ': ' + attribute_values[attribute]);
        }
    });
    return attribute_values;
}

function convertEvent(event_details) {
    let event = {
        'summary': generateEventSummary(event_details),
        'location': event_details['Location'],
        'description': generateEventDescription(event_details),
        'start': {
            'dateTime': generateDateTime(event_details['Start Date & Time']).toISOString(),
            'timeZone': time_zone
        },
        'end': {
            'dateTime': generateDateTime(event_details['End Date & Time']).toISOString(),
            'timeZone': time_zone
        },
        'extendedProperties': {
            'shared': {}
        }
    }
    event['extendedProperties']['shared']['gen_con_event_'+event_details['Game ID']] = 1;

    return event;
}

function expandEventDetails(event_details) {
    event_details['Short Timeframe'] = generateShortTimeframe(
        event_details['Start Date & Time'], event_details['End Date & Time']
    );

    event_details['Short Cost'] = generateShortCost(event_details['Cost']);

    event_details['Is Tournament'] = isTournament(event_details['Tournament']);

    return event_details;
}

function generateShortTimeframe(start, end) {
    console.log(date_re, start, end);
    let [, , start_hour, start_minute, start_ampm] = date_re.exec(start);
    let [, , end_hour, end_minute, end_ampm] = date_re.exec(end);
    start_ampm = start_ampm.toLowerCase();
    end_ampm = end_ampm.toLowerCase();

    let start_part = '';
    if (start_hour === '12' && start_minute === '00') {
        if (start_ampm === 'a') {
            start_part = 'M';
        } else if (start_ampm === 'p') {
            start_part = 'N';
        }
    } else if (start_part === '' && start_minute === '00') {
        start_part = start_hour;
    } else {
        start_part = start_hour + start_minute;
    }

    let end_part = '';
    if (end_hour === '12' && end_minute === '00') {
        if (end_ampm === 'a') {
            end_part = 'M';
        } else if (end_ampm === 'p') {
            end_part = 'N';
        }
    } else if (end_part === '' && end_minute === '00') {
        end_part = end_hour + end_ampm;
    } else {
        end_part = end_hour + end_minute + end_ampm;
    }

    if (start_part !== 'M' && start_part !== 'N' && start_ampm !== end_ampm) {
        start_part += start_ampm;
    }

    return start_part + '-' + end_part;
}

function generateShortCost(cost) {
    [, dollars, cents] = cost_re.exec(cost);
    if (dollars === '0' && cents === '00') {
        return 'FREE';
    }
    return (cents === '00') ? '$' + dollars : cost;
}

function isTournament(tournament) {
    return (tournament.substr(0, 3) === 'Yes');
}

function generateEventSummary(event_details) {
    return [
        event_details['Short Timeframe'],
        event_details['Title'],
        '(' + event_details['Game ID'] + ')'
    ].join(' ');
}

function generateEventDescription(event_details) {
    // Generate web links
    let web_links = [event_details['URL']];
    if (event_details['Web Address for more information']) {
        web_links.push(event_details['Web Address for more information']);
    }

    // Start with web links
    let description_parts = [web_links.join("\n")];

    // Add Descriptions
    if (event_details['Short Description']) {
        description_parts.push(event_details['Short Description']);
    }
    if (event_details['Description']) {
        description_parts.push(event_details['Description']);
    }
    if (event_details['Long Description']) {
        description_parts.push(event_details['Long Description']);
    }

    // Add cost/tournament info
    if (event_details['Is Tournament']) {
        description_parts.push(event_details['Short Cost'] + ' Tournament');
    } else {
        description_parts.push(event_details['Short Cost']);
    }

    return description_parts.join("\n\n");
}

function generateDateTime(time) {
    let [, day_of_week, hour, minute, ampm] = date_re.exec(time);
    let date = date_map[day_of_week];
    return new Date(date + ' ' + hour + ':' + minute + ' ' + ampm + 'M' + ' ' + short_time_zone);
}
<|endoftext|>


<commit_before>var grunt = require('grunt');
var nconf = require('nconf');

nconf.file('build-env.json');

var electron_disturl = nconf.get('electron:disturl');
var electron_version = nconf.get('electron:version');

var app_name = nconf.get('app:name');
var app_description = nconf.get('app:description');
var app_version = nconf.get('app:version');
var app_icons = nconf.get('app:icons');

require('load-grunt-tasks')(grunt);

grunt.initConfig({

  clean: {
    build: ['build']
  },

  copy: {
    osxBuild: {
      expand: true,
      cwd: 'app',
      src: ['**', '!node_modules/**/*'],
      dest: 'build/osx/'
    },
    win32Build: {
      expand: true,
      cwd: 'app',
      src: ['**', '!node_modules/**/*'],
      dest: 'build/win32/'
    },
    linuxBuild: {
      expand: true,
      cwd: 'app',
      src: ['**', '!node_modules/**/*'],
      dest: 'build/linux/'
    }
  },

  'npm-install': {
    osxBuild: {
      options: {
        cwd: 'build/osx',
        disturl: electron_disturl,
        distver: electron_version,
        target: 'darwin',
        arch: 'x64'
      }
    },
    win32Build: {
      options: {
        cwd: 'build/win32',
        disturl: electron_disturl,
        distver: electron_version,
        target: 'win32',
        arch: 'ia32'
      }
    },
    linuxBuild: {
      options: {
        cwd: 'build/linux',
        disturl: electron_disturl,
        distver: electron_version,
        target: 'linux',
        arch: 'x64'
      }
    }
  },

  electron: {
    osxBuild: {
      options: {
        name: app_name,
        dir: 'build/osx',
        out: 'build',
        version: electron_version,
        platform: 'darwin',
        arch: 'x64',
        icon: app_icons.icns,
        prune: true,
        asar: false
      }
    },
    win32Build: {
      options: {
        name: app_name,
        dir: 'build/win32',
        out: 'build',
        version: electron_version,
        platform: 'win32',
        arch: 'ia32',
        icon: app_icons.ico,
        prune: true,
        asar: true
      }
    },
    linuxBuild: {
      options: {
        name: 'boilerplate',
        dir: 'build/linux',
        out: 'build',
        version: electron_version,
        platform: 'linux',
        arch: 'x64',
        icon: app_icons.png,
        prune: true,
        asar: true
      }
    }
  },

  appdmg: {
    options: {
      basepath: '.',
      title: app_name,
      icon: app_icons.icns,
      background: 'app/assets/background.png',
      'icon-size': 80,
      contents: [{
        x: 300,
        y: 250,
        type: 'link',
        path: '/Applications'
      }, {
        x: 120,
        y: 130,
        type: 'file',
        path: 'build/' + app_name + '-darwin-x64/' + app_name + '.app/'
      }]
    },
    target: {
      dest: 'build/pkg/' + app_name + '.dmg'
    }
  },

  'electron-redhat-installer': {
    options: {
      productName: app_name,
      productDescription: app_description,
      productVersion: app_version,
      icon: app_icons.png,
      categories: [
        'Utility'
      ],
      rename: function(dest, src) {
        return dest + '<%= name %>-<%= version %>-<%= revision %>.<%= arch %>.rpm';
      }
    },
    linux64: {
      options: {
        arch: 'x86_64'
      },
      src: 'build/' + app_name + '-linux-x64/',
      dest: 'build/pkg/'
    }
  },

  'electron-debian-installer': {
    options: {
      productName: app_name,
      productDescription: app_description,
      productVersion: app_version,
      icon: app_icons.png,
      section: 'devel',
      priority: 'optional',
      lintianOverrides: [
        'changelog-file-missing-in-native-package',
        'executable-not-elf-or-script',
        'extra-license-file'
      ],
      categories: [
        'Utility'
      ],
      rename: function(dest, src) {
        return dest + '<%= name %>_<%= version %>-<%= revision %>_<%= arch %>.deb';
      }
    },
    linux64: {
      options: {
        arch: 'amd64'
      },
      src: 'build/' + app_name + '-linux-x64/',
      dest: 'build/pkg/'
    }
  },

  'electron-windows-installer': {
    options: {
      productName: app_name,
      productDescription: app_description,
      productVersion: app_version,
      icon: app_icons.ico,
      rename: function(dest, src) {
        if (/\.exe$/.test(src)) {
          src = '<%= name %>-<%= version %>-setup.exe';
        }
        return dest + src;
      }
    },
    win32: {
      src: 'build/' + app_name + '-win32-ia32/',
      dest: 'build/pkg/'
    }
  }

});

grunt.registerTask('osx', ['clean:build', 'copy:osxBuild', 'npm-install:osxBuild', 'electron:osxBuild', 'appdmg']);
grunt.registerTask('win32', ['clean:build', 'copy:win32Build', 'npm-install:win32Build', 'electron:win32Build', 'electron-windows-installer']);
grunt.registerTask('linux', ['clean:build', 'copy:linuxBuild', 'npm-install:linuxBuild', 'electron:linuxBuild', 'electron-redhat-installer', 'electron-debian-installer']);
<commit_msg>corrected output path for linux-electron-build<commit_after>var grunt = require('grunt');
var nconf = require('nconf');

nconf.file('build-env.json');

var electron_disturl = nconf.get('electron:disturl');
var electron_version = nconf.get('electron:version');

var app_name = nconf.get('app:name');
var app_description = nconf.get('app:description');
var app_version = nconf.get('app:version');
var app_icons = nconf.get('app:icons');

require('load-grunt-tasks')(grunt);

grunt.initConfig({

  clean: {
    build: ['build']
  },

  copy: {
    osxBuild: {
      expand: true,
      cwd: 'app',
      src: ['**', '!node_modules/**/*'],
      dest: 'build/osx/'
    },
    win32Build: {
      expand: true,
      cwd: 'app',
      src: ['**', '!node_modules/**/*'],
      dest: 'build/win32/'
    },
    linuxBuild: {
      expand: true,
      cwd: 'app',
      src: ['**', '!node_modules/**/*'],
      dest: 'build/linux/'
    }
  },

  'npm-install': {
    osxBuild: {
      options: {
        cwd: 'build/osx',
        disturl: electron_disturl,
        distver: electron_version,
        target: 'darwin',
        arch: 'x64'
      }
    },
    win32Build: {
      options: {
        cwd: 'build/win32',
        disturl: electron_disturl,
        distver: electron_version,
        target: 'win32',
        arch: 'ia32'
      }
    },
    linuxBuild: {
      options: {
        cwd: 'build/linux',
        disturl: electron_disturl,
        distver: electron_version,
        target: 'linux',
        arch: 'x64'
      }
    }
  },

  electron: {
    osxBuild: {
      options: {
        name: app_name,
        dir: 'build/osx',
        out: 'build',
        version: electron_version,
        platform: 'darwin',
        arch: 'x64',
        icon: app_icons.icns,
        prune: true,
        asar: false
      }
    },
    win32Build: {
      options: {
        name: app_name,
        dir: 'build/win32',
        out: 'build',
        version: electron_version,
        platform: 'win32',
        arch: 'ia32',
        icon: app_icons.ico,
        prune: true,
        asar: true
      }
    },
    linuxBuild: {
      options: {
        name: app_name,
        dir: 'build/linux',
        out: 'build',
        version: electron_version,
        platform: 'linux',
        arch: 'x64',
        icon: app_icons.png,
        prune: true,
        asar: true
      }
    }
  },

  appdmg: {
    options: {
      basepath: '.',
      title: app_name,
      icon: app_icons.icns,
      background: 'app/assets/background.png',
      'icon-size': 80,
      contents: [{
        x: 300,
        y: 250,
        type: 'link',
        path: '/Applications'
      }, {
        x: 120,
        y: 130,
        type: 'file',
        path: 'build/' + app_name + '-darwin-x64/' + app_name + '.app/'
      }]
    },
    target: {
      dest: 'build/pkg/' + app_name + '.dmg'
    }
  },

  'electron-redhat-installer': {
    options: {
      productName: app_name,
      productDescription: app_description,
      productVersion: app_version,
      icon: app_icons.png,
      categories: [
        'Utility'
      ],
      rename: function(dest, src) {
        return dest + '<%= name %>-<%= version %>-<%= revision %>.<%= arch %>.rpm';
      }
    },
    linux64: {
      options: {
        arch: 'x86_64'
      },
      src: 'build/' + app_name + '-linux-x64/',
      dest: 'build/pkg/'
    }
  },

  'electron-debian-installer': {
    options: {
      productName: app_name,
      productDescription: app_description,
      productVersion: app_version,
      icon: app_icons.png,
      section: 'devel',
      priority: 'optional',
      lintianOverrides: [
        'changelog-file-missing-in-native-package',
        'executable-not-elf-or-script',
        'extra-license-file'
      ],
      categories: [
        'Utility'
      ],
      rename: function(dest, src) {
        return dest + '<%= name %>_<%= version %>-<%= revision %>_<%= arch %>.deb';
      }
    },
    linux64: {
      options: {
        arch: 'amd64'
      },
      src: 'build/' + app_name + '-linux-x64/',
      dest: 'build/pkg/'
    }
  },

  'electron-windows-installer': {
    options: {
      productName: app_name,
      productDescription: app_description,
      productVersion: app_version,
      icon: app_icons.ico,
      rename: function(dest, src) {
        if (/\.exe$/.test(src)) {
          src = '<%= name %>-<%= version %>-setup.exe';
        }
        return dest + src;
      }
    },
    win32: {
      src: 'build/' + app_name + '-win32-ia32/',
      dest: 'build/pkg/'
    }
  }

});

grunt.registerTask('osx', ['clean:build', 'copy:osxBuild', 'npm-install:osxBuild', 'electron:osxBuild', 'appdmg']);
grunt.registerTask('win32', ['clean:build', 'copy:win32Build', 'npm-install:win32Build', 'electron:win32Build', 'electron-windows-installer']);
grunt.registerTask('linux', ['clean:build', 'copy:linuxBuild', 'npm-install:linuxBuild', 'electron:linuxBuild', 'electron-redhat-installer', 'electron-debian-installer']);
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    connect: {
      server: {
        options: {
          port: 9000,
          hostname: '*',
          keepalive: true
        }
      }
    },
    open: {
      server: {
        url: 'http://localhost:<%= connect.server.options.port %>/index.html'
      }
    },
    react: {
      dynamic_mappings: {
        files: [
        {
          expand: true,
          cwd: 'scripts/',
          src: ['**/*.jsx'],
          dest: 'modules/',
          ext: '.jsx.js'
        }
      ]
    },
  },
  jshint: {
    all: {
      src: ['Gruntfile.js', 'scripts/**/*.jsx', 'scripts/**/*.js'],
      options: {
        jshintrc: '.jshintrc'
      }
    }
  }
  });

  grunt.loadNpmTasks('grunt-open');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-react');
  grunt.loadNpmTasks('grunt-jsxhint');

  grunt.registerTask('serve', function (target) {
    grunt.task.run([
      'open',
      'connect'
    ]);
  });

  // Default task(s).
  grunt.registerTask('default', ['serve']);
};
<commit_msg>stray comma<commit_after>module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    connect: {
      server: {
        options: {
          port: 9000,
          hostname: '*',
          keepalive: true
        }
      }
    },
    open: {
      server: {
        url: 'http://localhost:<%= connect.server.options.port %>/index.html'
      }
    },
    react: {
      dynamic_mappings: {
        files: [
        {
          expand: true,
          cwd: 'scripts/',
          src: ['**/*.jsx'],
          dest: 'modules/',
          ext: '.jsx.js'
        }
      ]
    }
  },
  jshint: {
    all: {
      src: ['Gruntfile.js', 'scripts/**/*.jsx', 'scripts/**/*.js'],
      options: {
        jshintrc: '.jshintrc'
      }
    }
  }
  });

  grunt.loadNpmTasks('grunt-open');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-react');
  grunt.loadNpmTasks('grunt-jsxhint');

  grunt.registerTask('serve', function (target) {
    grunt.task.run([
      'open',
      'connect'
    ]);
  });

  // Default task(s).
  grunt.registerTask('default', ['serve']);
};
<|endoftext|>


<commit_before>/*!
 *
 *  Copyright 2016 Yann Massard (https://github.com/yamass) and other contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var copyrightHeader = "/*!\n"
    + "*\n"
    + "*  Copyright 2016 Yann Massard (https://github.com/yamass) and other contributors\n"
    + "*\n"
    + "*  Licensed under the Apache License, Version 2.0 (the \"License\");\n"
    + "*  you may not use this file except in compliance with the License.\n"
    + "*  You may obtain a copy of the License at\n"
    + "*\n"
    + "*  http://www.apache.org/licenses/LICENSE-2.0\n"
    + "*\n"
    + "*  Unless required by applicable law or agreed to in writing, software\n"
    + "*  distributed under the License is distributed on an \"AS IS\" BASIS,\n"
    + "*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
    + "*  See the License for the specific language governing permissions and\n"
    + "*  limitations under the License.\n"
    + "*\n"
    + "*/\n";
var minCopyrightHeader = "/*! Trivial Components | (c) 2015 Yann Massard and others | Apache License, Version 2.0 (https://raw.githubusercontent.com/trivial-components/trivial-components/master/LICENSE) */\n";

var RELEASE_NOTES = 'Migrated to typescript!';

var gulp = require('gulp');
var bower = require('gulp-bower');
var less = require('gulp-less');
var mirror = require('gulp-mirror');
var rename = require('gulp-rename');
var pipe = require('multipipe');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var plumber = require('gulp-plumber');
var livereload = require('gulp-livereload');
var sourcemaps = require('gulp-sourcemaps');
var del = require('del');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer-core');
var concat = require('gulp-concat');
var zip = require('gulp-zip');
var tar = require('gulp-tar');
var gzip = require('gulp-gzip');
var stripDebug = require('gulp-strip-debug');
var karma = require('karma').server;
var header = require('gulp-header');
var strip = require('gulp-strip-comments');
var stripCssComments = require('gulp-strip-css-comments');
var sizereport = require('gulp-sizereport');
var ts = require('gulp-typescript');
var gulpTypings = require("gulp-typings");
var release = require('gulp-github-release');
var merge = require('merge-stream');

gulp.task('clean', function () {
    return del(['dist']);
});

gulp.task('bower', function () {
    return bower()
        .pipe(gulp.dest('bower_components/'))
});

gulp.task('copyLibs2dist', ['bower'], function () {
    return gulp.src([
        'bower_components/jquery/dist/jquery.js',
        'bower_components/Caret.js/dist/jquery.caret.js',
        'bower_components/jquery-ui/ui/position.js',
        'bower_components/mustache/mustache.js',
        'bower_components/levenshtein/lib/levenshtein.js'
    ])
        .pipe(rename(function (path) {
            // rename position to jquery.position...
            if (path.basename.indexOf('position') === 0) {
                path.basename = "jquery." + path.basename;
            }
        }))
        .pipe(mirror(
            pipe(
                rename(function (path) {
                    path.basename += ".min";
                }),
                uglify()
            )
        ))
        .pipe(gulp.dest('./dist/lib'));
});

function compileLess(src, dest) {
    return gulp.src(src)
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(postcss([
            require('autoprefixer')({browsers: ['> 2%']})
        ]))
        .pipe(stripCssComments())
        .pipe(header(copyrightHeader))
        .pipe(pipe(sourcemaps.write('.')))
        .pipe(gulp.dest(dest))
        .pipe(livereload());
}

gulp.task('less', ['bower'], function () {
    return compileLess(['less/trivial-components.less'], 'dist/css');
});

gulp.task('less-bootstrap', ['bower'], function () {
    return compileLess(['less/trivial-components-bootstrap.less'], 'dist/css');
});

gulp.task('less-demo', ['bower'], function () {
    return compileLess(['demo/less/demo.less'], 'demo/css');
});

gulp.task('minify-css', ['less', 'less-bootstrap'], function () {
    return gulp.src(["dist/css/*.css", "!dist/css/*.min.css", "!dist/css/*.sourcemaps.css"])
        .pipe(rename(function (path) {
            path.basename += ".min"
        }))
        .pipe(postcss([
            require('cssnano')
        ]))
        .pipe(header(minCopyrightHeader))
        .pipe(gulp.dest("dist/css"));
});

gulp.task('js-single', ['typescript', 'typescript-declarations'], function () {
    return gulp.src(['dist/js/single/TrivialCore.js', 'dist/js/single/*.js', '!**/*.min.*'])
        .pipe(stripDebug())
        .pipe(rename(function (path) {
            path.basename += ".min";
        }))
        .pipe(uglify())
        .pipe(header(minCopyrightHeader))
        .pipe(gulp.dest('./dist/js/single'));
});

gulp.task('js-bundle', ['js-single'], function () {
    return gulp.src(['dist/js/single/TrivialCore.js', 'dist/js/single/*.js', '!**/*.min.js'])
        .pipe(stripDebug())
        .pipe(strip())
        .pipe(concat('trivial-components.js'))
        .pipe(header(copyrightHeader))
        .pipe(mirror(
            pipe(
                rename(function (path) {
                    path.basename += ".min";
                }),
                uglify(),
                header(minCopyrightHeader)
            )
        ))
        .pipe(gulp.dest('./dist/js/bundle'))
});

gulp.task('ts-declarations-bundle', ['typescript-declarations'], function () {
    return gulp.src(['dist/js/single/*.d.ts'])
	    .pipe(strip())
        .pipe(concat('trivial-components.d.ts'))
        .pipe(header(copyrightHeader))
        .pipe(gulp.dest('./dist/js/bundle'))
});

gulp.task('test', ['bower'], function (done) {
    karma.start({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done);
});

gulp.task('prepare-dist', ['bower', 'less', 'less-bootstrap', 'minify-css', 'js-single', 'js-bundle', 'ts-declarations-bundle', 'copyLibs2dist']);

gulp.task('zip', ["prepare-dist"], function () {
    return gulp.src(['README.md', 'LICENSE', 'less*/*', 'ts*/*', 'dist/**/*', "!dist/*.gz", "!dist/*.zip"])
        .pipe(zip('trivial-components.zip'))
        .pipe(rename(function (path) {
            path.basename += '-' + VERSION;
        }))
        .pipe(gulp.dest('dist'));
});
gulp.task('tar', ['prepare-dist'], function () {
    return gulp.src(['README.md', 'LICENSE', 'less*/*', 'ts*/*', 'dist/**/*', "!dist/*.gz", "!dist/*.zip"])
        .pipe(tar('trivial-components.tar'))
        .pipe(rename(function (path) {
            path.basename += '-' + VERSION;
        }))
        .pipe(gzip())
        .pipe(gulp.dest('dist'));
});

gulp.task('size-report', ["js-bundle", "minify-css"], function () {
    return gulp.src(['dist/js/bundle/trivial-components.min.js', 'dist/css/trivial-components.min.css'])
        .pipe(sizereport({
            gzip: true,
            'trivial-components.min.js': {
                'maxSize': 100000,
                'maxGzippedSize': 20000
            },
            'trivial-components.min.css': {
                'maxSize': 25000,
                'maxGzippedSize': 5000
            },
            '*': {
                maxTotalSize: 125000,
                maxTotalGzippedSize: 25000
            }
        }));
});

gulp.task('default', ['zip', 'tar', "less-demo", "size-report"]);

gulp.task('watch', function () {
    livereload.listen();
    gulp.watch(['less/*.less', 'demo/less/*.less'], ["less-demo", 'less', 'less-bootstrap']);
});

gulp.task('watch-ts', function () {
    gulp.watch(['ts/*.ts'], ['js-bundle']);
});

var tsProject = ts.createProject('tsconfig.json');

gulp.task('typescript', ['install-typings'], function () {
    return tsProject.src()
        .pipe(tsProject())
        .js.pipe(gulp.dest("dist/js/single"));
});

gulp.task('typescript-declarations', ['typescript'], function () {
	return tsProject.src()
		.pipe(tsProject())
		.pipe(gulp.dest("dist/js/single"));
});

gulp.task("install-typings", function () {
    return gulp.src("./typings.json")
        .pipe(gulpTypings());
});

gulp.task('github-release', ['default'], function () {
	var VERSION = require('./package.json').version;
    return gulp.src(['dist/trivial-components-' + VERSION + '.zip', 'dist/trivial-components-' + VERSION + '.tar.gz'])
        .pipe(release({
            tag: 'v' + VERSION,
            name: VERSION,
            notes: RELEASE_NOTES,
            prerelease: true,
            manifest: require('./package.json')
        }));
});<commit_msg>gulp github-release: read version from package.json<commit_after>/*!
 *
 *  Copyright 2016 Yann Massard (https://github.com/yamass) and other contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var copyrightHeader = "/*!\n"
    + "*\n"
    + "*  Copyright 2016 Yann Massard (https://github.com/yamass) and other contributors\n"
    + "*\n"
    + "*  Licensed under the Apache License, Version 2.0 (the \"License\");\n"
    + "*  you may not use this file except in compliance with the License.\n"
    + "*  You may obtain a copy of the License at\n"
    + "*\n"
    + "*  http://www.apache.org/licenses/LICENSE-2.0\n"
    + "*\n"
    + "*  Unless required by applicable law or agreed to in writing, software\n"
    + "*  distributed under the License is distributed on an \"AS IS\" BASIS,\n"
    + "*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
    + "*  See the License for the specific language governing permissions and\n"
    + "*  limitations under the License.\n"
    + "*\n"
    + "*/\n";
var minCopyrightHeader = "/*! Trivial Components | (c) 2015 Yann Massard and others | Apache License, Version 2.0 (https://raw.githubusercontent.com/trivial-components/trivial-components/master/LICENSE) */\n";

var VERSION = require('./package.json').version;

var gulp = require('gulp');
var bower = require('gulp-bower');
var less = require('gulp-less');
var mirror = require('gulp-mirror');
var rename = require('gulp-rename');
var pipe = require('multipipe');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var plumber = require('gulp-plumber');
var livereload = require('gulp-livereload');
var sourcemaps = require('gulp-sourcemaps');
var del = require('del');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer-core');
var concat = require('gulp-concat');
var zip = require('gulp-zip');
var tar = require('gulp-tar');
var gzip = require('gulp-gzip');
var stripDebug = require('gulp-strip-debug');
var karma = require('karma').server;
var header = require('gulp-header');
var strip = require('gulp-strip-comments');
var stripCssComments = require('gulp-strip-css-comments');
var sizereport = require('gulp-sizereport');
var ts = require('gulp-typescript');
var gulpTypings = require("gulp-typings");
var release = require('gulp-github-release');
var merge = require('merge-stream');

gulp.task('clean', function () {
    return del(['dist']);
});

gulp.task('bower', function () {
    return bower()
        .pipe(gulp.dest('bower_components/'))
});

gulp.task('copyLibs2dist', ['bower'], function () {
    return gulp.src([
        'bower_components/jquery/dist/jquery.js',
        'bower_components/Caret.js/dist/jquery.caret.js',
        'bower_components/jquery-ui/ui/position.js',
        'bower_components/mustache/mustache.js',
        'bower_components/levenshtein/lib/levenshtein.js'
    ])
        .pipe(rename(function (path) {
            // rename position to jquery.position...
            if (path.basename.indexOf('position') === 0) {
                path.basename = "jquery." + path.basename;
            }
        }))
        .pipe(mirror(
            pipe(
                rename(function (path) {
                    path.basename += ".min";
                }),
                uglify()
            )
        ))
        .pipe(gulp.dest('./dist/lib'));
});

function compileLess(src, dest) {
    return gulp.src(src)
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(postcss([
            require('autoprefixer')({browsers: ['> 2%']})
        ]))
        .pipe(stripCssComments())
        .pipe(header(copyrightHeader))
        .pipe(pipe(sourcemaps.write('.')))
        .pipe(gulp.dest(dest))
        .pipe(livereload());
}

gulp.task('less', ['bower'], function () {
    return compileLess(['less/trivial-components.less'], 'dist/css');
});

gulp.task('less-bootstrap', ['bower'], function () {
    return compileLess(['less/trivial-components-bootstrap.less'], 'dist/css');
});

gulp.task('less-demo', ['bower'], function () {
    return compileLess(['demo/less/demo.less'], 'demo/css');
});

gulp.task('minify-css', ['less', 'less-bootstrap'], function () {
    return gulp.src(["dist/css/*.css", "!dist/css/*.min.css", "!dist/css/*.sourcemaps.css"])
        .pipe(rename(function (path) {
            path.basename += ".min"
        }))
        .pipe(postcss([
            require('cssnano')
        ]))
        .pipe(header(minCopyrightHeader))
        .pipe(gulp.dest("dist/css"));
});

gulp.task('js-single', ['typescript', 'typescript-declarations'], function () {
    return gulp.src(['dist/js/single/TrivialCore.js', 'dist/js/single/*.js', '!**/*.min.*'])
        .pipe(stripDebug())
        .pipe(rename(function (path) {
            path.basename += ".min";
        }))
        .pipe(uglify())
        .pipe(header(minCopyrightHeader))
        .pipe(gulp.dest('./dist/js/single'));
});

gulp.task('js-bundle', ['js-single'], function () {
    return gulp.src(['dist/js/single/TrivialCore.js', 'dist/js/single/*.js', '!**/*.min.js'])
        .pipe(stripDebug())
        .pipe(strip())
        .pipe(concat('trivial-components.js'))
        .pipe(header(copyrightHeader))
        .pipe(mirror(
            pipe(
                rename(function (path) {
                    path.basename += ".min";
                }),
                uglify(),
                header(minCopyrightHeader)
            )
        ))
        .pipe(gulp.dest('./dist/js/bundle'))
});

gulp.task('ts-declarations-bundle', ['typescript-declarations'], function () {
    return gulp.src(['dist/js/single/*.d.ts'])
	    .pipe(strip())
        .pipe(concat('trivial-components.d.ts'))
        .pipe(header(copyrightHeader))
        .pipe(gulp.dest('./dist/js/bundle'))
});

gulp.task('test', ['bower'], function (done) {
    karma.start({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done);
});

gulp.task('prepare-dist', ['bower', 'less', 'less-bootstrap', 'minify-css', 'js-single', 'js-bundle', 'ts-declarations-bundle', 'copyLibs2dist']);

gulp.task('zip', ["prepare-dist"], function () {
    return gulp.src(['README.md', 'LICENSE', 'less*/*', 'ts*/*', 'dist/**/*', "!dist/*.gz", "!dist/*.zip"])
        .pipe(zip('trivial-components.zip'))
        .pipe(rename(function (path) {
            path.basename += '-' + VERSION;
        }))
        .pipe(gulp.dest('dist'));
});
gulp.task('tar', ['prepare-dist'], function () {
    return gulp.src(['README.md', 'LICENSE', 'less*/*', 'ts*/*', 'dist/**/*', "!dist/*.gz", "!dist/*.zip"])
        .pipe(tar('trivial-components.tar'))
        .pipe(rename(function (path) {
            path.basename += '-' + VERSION;
        }))
        .pipe(gzip())
        .pipe(gulp.dest('dist'));
});

gulp.task('size-report', ["js-bundle", "minify-css"], function () {
    return gulp.src(['dist/js/bundle/trivial-components.min.js', 'dist/css/trivial-components.min.css'])
        .pipe(sizereport({
            gzip: true,
            'trivial-components.min.js': {
                'maxSize': 100000,
                'maxGzippedSize': 20000
            },
            'trivial-components.min.css': {
                'maxSize': 25000,
                'maxGzippedSize': 5000
            },
            '*': {
                maxTotalSize: 125000,
                maxTotalGzippedSize: 25000
            }
        }));
});

gulp.task('default', ['zip', 'tar', "less-demo", "size-report"]);

gulp.task('watch', function () {
    livereload.listen();
    gulp.watch(['less/*.less', 'demo/less/*.less'], ["less-demo", 'less', 'less-bootstrap']);
});

gulp.task('watch-ts', function () {
    gulp.watch(['ts/*.ts'], ['js-bundle']);
});

var tsProject = ts.createProject('tsconfig.json');

gulp.task('typescript', ['install-typings'], function () {
    return tsProject.src()
        .pipe(tsProject())
        .js.pipe(gulp.dest("dist/js/single"));
});

gulp.task('typescript-declarations', ['typescript'], function () {
	return tsProject.src()
		.pipe(tsProject())
		.pipe(gulp.dest("dist/js/single"));
});

gulp.task("install-typings", function () {
    return gulp.src("./typings.json")
        .pipe(gulpTypings());
});

gulp.task('github-release', ['default'], function () {
	var VERSION = require('./package.json').version;
    return gulp.src(['dist/trivial-components-' + VERSION + '.zip', 'dist/trivial-components-' + VERSION + '.tar.gz'])
        .pipe(release({
            tag: 'v' + VERSION,
            name: VERSION,
            prerelease: true,
            manifest: require('./package.json')
        }));
});<|endoftext|>


<commit_before>var slice = [].slice;
var { appendChild: _appendChild, insertBefore: _insertBefore } = document.createElement('a');
var isWorseIE = /msie\s+[2-8]/i.test(navigator.userAgent);

function release(node) {
    if (node === null || node === undefined) return node;
    return isFunction(node) ? node() : isNode(node) ? node : document.createTextNode(node);
}

function hasEnterStyle(e) {
    return e.initialStyle || e.enterStyle || e.leavingStyle || e.leaveStyle;
}

function _onappend(node, event) {
    if (node.isMounted) return;
    if (node.nodeType === 1 || node.nodeType === 8) node.isMounted = true;
    if (!event) {
        event = createEvent("append");
    }
    dispatch(node, event);
    var onappend = node.onappend;
    if (isArray(onappend)) {
        onappend.map(function (append_handler) {
            append_handler.call(this, event);
        }, node);
    }
    if (isFunction(onappend)) {
        onappend.call(node, event);
    }
    var children = [].concat.apply([], node.childNodes);
    if (children) for (var cx = 0, dx = children.length; cx < dx; cx++) {
        _onappend(children[cx], event);
    }
}
function appendChild(parent, obj, transition) {
    if (transition === false) {
        var children = [].concat(obj);
    } else {
        var children = isArray(obj) ? slice.call(obj, 0) : slice.call(arguments, 1);
    }
    if (parent.appendChild) {
        for (var cx = 0, dx = children.length; cx < dx; cx++) {
            var o = release(children[cx]);
            if (!o) continue;
            if (o.removeTimer) clearTimeout(o.removeTimer);
            if (hasEnterStyle(o) && transition !== false) {
                isFunction(appendChild.transition) && appendChild.transition(o);
            }
            if (isWorseIE) {
                try {
                    _appendChild.call(parent, o);
                } catch (e) {
                    console.error("appendChild", parent.tagName, o.tagName);
                }
            } else {
                _appendChild.call(parent, o);
            }
            o.with && appendChild(parent, o.with, transition);
            if (isMounted(parent)) _onappend(o);
        }
    }
    return parent;
}
function insertBefore(alreadyMounted, obj, transition) {
    var parent = alreadyMounted && alreadyMounted.parentNode;
    if (!parent || !parent.insertBefore) return;
    if (transition === false) {
        var children = [].concat(obj);
    } else {
        var children = isArray(obj) ? slice.call(obj, 0) : slice.call(arguments, 1);
    }
    for (var cx = 0, dx = children.length; cx < dx; cx++) {
        var o = release(children[cx]);
        if (!o) continue;
        if (o.removeTimer) clearTimeout(o.removeTimer);
        _insertBefore.call(parent, o, alreadyMounted);
        o.with && insertBefore(alreadyMounted, o.with, transition);
        if (isMounted(parent)) _onappend(o);
        if (hasEnterStyle(o) && transition !== false) {
            isFunction(appendChild.transition) && appendChild.transition(o);
        }
    }
}
function insertAfter(alreadyMounted, obj, transition) {
    var parent = alreadyMounted && alreadyMounted.parentNode;
    if (!parent || !parent.insertBefore) return;
    if (transition === false) {
        var children = [].concat(obj);
    } else {
        var children = isArray(obj) ? slice.call(obj, 0) : slice.call(arguments, 1);
    }
    children = children.reverse();
    for (var cx = 0, dx = children.length; cx < dx; cx++) {
        var o = release(children[cx]);
        if (o.removeTimer) clearTimeout(o.removeTimer);
        _insertBefore.call(parent, o, alreadyMounted.nextSibling);
        o.with && insertBefore(alreadyMounted.nextSibling, o.with, transition);
        if (isMounted(parent))
            _onappend(o);
        if (hasEnterStyle(o) && transition !== false) {
            isFunction(appendChild.transition) && appendChild.transition(o);
        }
    }
}

appendChild.before = insertBefore;
appendChild.after = insertAfter;
/**
 * 相当于 insertBefore
 */
appendChild.insert = function (parent, element, relative = parent.childNodes[0] || null) {
    if (!relative) {
        appendChild(parent, element);
    } else {
        insertBefore(relative, element);
    }
};
appendChild.replace = function (alreadyMounted, element) {
    if (!alreadyMounted || !alreadyMounted.parentNode) return;
    insertBefore(alreadyMounted, element);
    remove(alreadyMounted);
};<commit_msg>appendChild.replace两个参数传入同一个元素不再移除元素<commit_after>var slice = [].slice;
var { appendChild: _appendChild, insertBefore: _insertBefore } = document.createElement('a');
var isWorseIE = /msie\s+[2-8]/i.test(navigator.userAgent);

function release(node) {
    if (node === null || node === undefined) return node;
    return isFunction(node) ? node() : isNode(node) ? node : document.createTextNode(node);
}

function hasEnterStyle(e) {
    return e.initialStyle || e.enterStyle || e.leavingStyle || e.leaveStyle;
}

function _onappend(node, event) {
    if (node.isMounted) return;
    if (node.nodeType === 1 || node.nodeType === 8) node.isMounted = true;
    if (!event) {
        event = createEvent("append");
    }
    dispatch(node, event);
    var onappend = node.onappend;
    if (isArray(onappend)) {
        onappend.map(function (append_handler) {
            append_handler.call(this, event);
        }, node);
    }
    if (isFunction(onappend)) {
        onappend.call(node, event);
    }
    var children = [].concat.apply([], node.childNodes);
    if (children) for (var cx = 0, dx = children.length; cx < dx; cx++) {
        _onappend(children[cx], event);
    }
}
function appendChild(parent, obj, transition) {
    if (transition === false) {
        var children = [].concat(obj);
    } else {
        var children = isArray(obj) ? slice.call(obj, 0) : slice.call(arguments, 1);
    }
    if (parent.appendChild) {
        for (var cx = 0, dx = children.length; cx < dx; cx++) {
            var o = release(children[cx]);
            if (!o) continue;
            if (o.removeTimer) clearTimeout(o.removeTimer);
            if (hasEnterStyle(o) && transition !== false) {
                isFunction(appendChild.transition) && appendChild.transition(o);
            }
            if (isWorseIE) {
                try {
                    _appendChild.call(parent, o);
                } catch (e) {
                    console.error("appendChild", parent.tagName, o.tagName);
                }
            } else {
                _appendChild.call(parent, o);
            }
            o.with && appendChild(parent, o.with, transition);
            if (isMounted(parent)) _onappend(o);
        }
    }
    return parent;
}
function insertBefore(alreadyMounted, obj, transition) {
    var parent = alreadyMounted && alreadyMounted.parentNode;
    if (!parent || !parent.insertBefore) return;
    if (transition === false) {
        var children = [].concat(obj);
    } else {
        var children = isArray(obj) ? slice.call(obj, 0) : slice.call(arguments, 1);
    }
    for (var cx = 0, dx = children.length; cx < dx; cx++) {
        var o = release(children[cx]);
        if (!o) continue;
        if (o.removeTimer) clearTimeout(o.removeTimer);
        _insertBefore.call(parent, o, alreadyMounted);
        o.with && insertBefore(alreadyMounted, o.with, transition);
        if (isMounted(parent)) _onappend(o);
        if (hasEnterStyle(o) && transition !== false) {
            isFunction(appendChild.transition) && appendChild.transition(o);
        }
    }
}
function insertAfter(alreadyMounted, obj, transition) {
    var parent = alreadyMounted && alreadyMounted.parentNode;
    if (!parent || !parent.insertBefore) return;
    if (transition === false) {
        var children = [].concat(obj);
    } else {
        var children = isArray(obj) ? slice.call(obj, 0) : slice.call(arguments, 1);
    }
    children = children.reverse();
    for (var cx = 0, dx = children.length; cx < dx; cx++) {
        var o = release(children[cx]);
        if (o.removeTimer) clearTimeout(o.removeTimer);
        _insertBefore.call(parent, o, alreadyMounted.nextSibling);
        o.with && insertBefore(alreadyMounted.nextSibling, o.with, transition);
        if (isMounted(parent))
            _onappend(o);
        if (hasEnterStyle(o) && transition !== false) {
            isFunction(appendChild.transition) && appendChild.transition(o);
        }
    }
}

appendChild.before = insertBefore;
appendChild.after = insertAfter;
/**
 * 相当于 insertBefore
 */
appendChild.insert = function (parent, element, relative = parent.childNodes[0] || null) {
    if (!relative) {
        appendChild(parent, element);
    } else {
        insertBefore(relative, element);
    }
};
appendChild.replace = function (alreadyMounted, element) {
    if (alreadyMounted === element) return;
    if (!alreadyMounted || !alreadyMounted.parentNode) return;
    insertBefore(alreadyMounted, element);
    remove(alreadyMounted);
};<|endoftext|>


<commit_before>const angular = require('angular');
const ngRoute = require('angular-route');

const app = angular.module('app', ['ngRoute']);

app.config(['$routeProvider', function routeProvider($routeProvider) {
  $routeProvider
  .when('/home', {
    templateUrl: './views/login.html',
    controller: 'LoginController'
  })
  .when('/list', {
    templateUrl: './views/list.html',
  })
  .otherwise({
    redirectTo: '/home',
  });
}]);

app.controller('LoginController', ['$scope', function($scope) {

  // $scope.userLogin = function userLogin() {
  //   $scope.userLog.push(
  //     {
  //       email: $scope.user.email,
  //       password: $scope.user.password
  //     }
  //   );
  //   console.log($scope.userLog); // NOTE: 4debug;
  // };

  $scope.userLog = [];
}]);

module.exports = app;
<commit_msg>Login creates object with login data<commit_after>const angular = require('angular');
const ngRoute = require('angular-route');

const app = angular.module('app', ['ngRoute']);

app.config(['$routeProvider', function routeProvider($routeProvider) {
  $routeProvider
  .when('/home', {
    templateUrl: './views/login.html',
    controller: 'LoginController'
  })
  .when('/list', {
    templateUrl: './views/list.html',
  })
  .otherwise({
    redirectTo: '/home',
  });
}]);

app.controller('LoginController', ['$scope', function($scope) {

  $scope.userLogin = function userLogin() {
    $scope.userLog.push(
      {
        email: $scope.user.email,
        password: $scope.user.password
      }
    );
    console.log($scope.userLog); // NOTE: 4debug;
  };

  $scope.userLog = [];
}]);

module.exports = app;
<|endoftext|>


<commit_before>window.HLRDESK.init.editCatalog = function() {
    var socket = window.io();
    var origCall;
    var oldItem;
    var type;

    document.getElementById('newItem').addEventListener('click', addItem);

    function reserveAlert(){
      if (document.getElementById('onReserve').checked == true)
      {
        alert("Because this is a reserve item, make sure to include the owner of the reserve item in the desctiption and the date to return the item to the owner in the notes section");
        $('#notes').attr('required', 'required');
      }
    }

    function addItem()
    {
      var newItem = document.getElementById('editItem');
      openModal = window.patternlibrary.displayModal(newItem);
      type = 'inv.create';
      $('#quantity').val(1);
      $('#quantity').attr('placeholder', 1);
      document.getElementById('headText').textContent='Add Item';
      $('#checkoutLength').val(1);
      $('#checkoutLength').attr('placeholder', 1);
      document.getElementById('onReserve').addEventListener('change', reserveAlert);
      document.getElementById('delete-item').addEventListener('click', deleteItem);
      document.getElementById('save-item').addEventListener('click', updateDatabase);
    }
    function deleteItem()
    {
      var delInfo = {origCall, token: window.HLRDESK.token}
      socket.emit('deleteItem', delInfo);
    }
    function updateDatabase(){
      var newCall = $('#callNumber').val();
      var title = $('#title').val();
      var media = $('#media').val();
      var languages = $('#language').val();
      var quantity = parseInt($('#quantity').val(),10);
      var checkout_period = parseInt($('#checkoutLength').val(),10);
      var is_reserve = document.getElementById('onReserve').checked;
      var on_hummedia = document.getElementById('HLROnline').checked;
      var is_duplicatable = document.getElementById('duplicatable').checked;
      var notes = $('#notes').val();
      var edited = {
        data: {
          call: origCall,
          newCall,
          title,
          media,
          languages,
          quantity,
          checkout_period,
          is_reserve,
          on_hummedia,
          is_duplicatable,
          notes
        },
        token: window.HLRDESK.token
      };

      socket.emit(type, edited);
    }

  socket.on('inv.info', function(result){
    type = 'inv.update';
    origCall = result.call;
    $('#callNumber').val(result.call);
    $('#callNumber').attr('placeholder', result.call);

    $('#quantity').val(result.quantity);
    $('#quantity').attr('placeholder', result.quantity);

    $('#language').val(result.languages);
    $('#media').val(result.media);

    $('#title').val(result.title);
    $('#title').attr('placeholder', result.title);

    $('#checkoutLength').val(result.checkout_period);
    $('#checkoutLength').attr('placeholder', result.checkout_period);

    $('#onReserve').attr('checked', result.is_reserve);

    $('#duplicatable').attr('checked', result.is_duplicatable);

    $('#HLROnline').attr('checked', result.on_hummedia);

    if(result.date_added) {
      var date = result.date_added.substring(0,10);
    }

    $('#dateAdded').html(date);

    $('#editedBy').html(result.edited_by);

    if ($('#editedBy').html())
    {
      if(result.date_edited)
      {
        var edited = result.date_edited.substring(0,10);
        $('#dateEdited').attr('type', 'date');
        $('#dateEdited').html(edited);
      }
    }
    else{
      $('#dateEdited').html(" N/A");
      $('#editedBy').html(" N/A");
     }

    $('#notes').val(result.notes);
    $('#notes').attr('placeholder', result.notes);
    oldItem =
    {
      quant: result.quantity,
      titl: result.title,
      reserv: result.is_reserve,
      dup: result.is_duplicatable,
      hum: result.on_hummedia,
      notes: result.notes
    };
  });

  window.HLRDESK.plugins.search({
    search: '#editCatalog-search',
    results: '#editCatalog-search-results',
    hideCheckedOut: false,
    clickCallback: function()
    {
      var item = this;
      var item = { "callNum":this.dataset.call, token: window.HLRDESK.token }
      socket.emit('inv.get', item);
      var editItem = document.getElementById('editItem');
      openModal = window.patternlibrary.displayModal(editItem);
      document.getElementById('onReserve').addEventListener('change', reserveAlert);
      document.getElementById('delete-item').addEventListener('click', deleteItem);
      document.getElementById('save-item').addEventListener('click', updateDatabase);
    }
  });

  socket.on('alertMessage', function(alertMsg){
    alert(alertMsg);
  });

}
<commit_msg>changed html to text to prevent xss likelihood<commit_after>window.HLRDESK.init.editCatalog = function() {
    var socket = window.io();
    var origCall;
    var oldItem;
    var type;

    document.getElementById('newItem').addEventListener('click', addItem);

    function reserveAlert(){
      if (document.getElementById('onReserve').checked == true)
      {
        alert("Because this is a reserve item, make sure to include the owner of the reserve item in the desctiption and the date to return the item to the owner in the notes section");
        $('#notes').attr('required', 'required');
      }
    }

    function addItem()
    {
      var newItem = document.getElementById('editItem');
      openModal = window.patternlibrary.displayModal(newItem);
      type = 'inv.create';
      $('#quantity').val(1);
      $('#quantity').attr('placeholder', 1);
      document.getElementById('headText').textContent='Add Item';
      $('#checkoutLength').val(1);
      $('#checkoutLength').attr('placeholder', 1);
      document.getElementById('onReserve').addEventListener('change', reserveAlert);
      document.getElementById('delete-item').addEventListener('click', deleteItem);
      document.getElementById('save-item').addEventListener('click', updateDatabase);
    }
    function deleteItem()
    {
      var delInfo = {origCall, token: window.HLRDESK.token}
      socket.emit('deleteItem', delInfo);
    }
    function updateDatabase(){
      var newCall = $('#callNumber').val();
      var title = $('#title').val();
      var media = $('#media').val();
      var languages = $('#language').val();
      var quantity = parseInt($('#quantity').val(),10);
      var checkout_period = parseInt($('#checkoutLength').val(),10);
      var is_reserve = document.getElementById('onReserve').checked;
      var on_hummedia = document.getElementById('HLROnline').checked;
      var is_duplicatable = document.getElementById('duplicatable').checked;
      var notes = $('#notes').val();
      var edited = {
        data: {
          call: origCall,
          newCall,
          title,
          media,
          languages,
          quantity,
          checkout_period,
          is_reserve,
          on_hummedia,
          is_duplicatable,
          notes
        },
        token: window.HLRDESK.token
      };

      socket.emit(type, edited);
    }

  socket.on('inv.info', function(result){
    type = 'inv.update';
    origCall = result.call;
    $('#callNumber').val(result.call);
    $('#callNumber').attr('placeholder', result.call);

    $('#quantity').val(result.quantity);
    $('#quantity').attr('placeholder', result.quantity);

    $('#language').val(result.languages);
    $('#media').val(result.media);

    $('#title').val(result.title);
    $('#title').attr('placeholder', result.title);

    $('#checkoutLength').val(result.checkout_period);
    $('#checkoutLength').attr('placeholder', result.checkout_period);

    $('#onReserve').attr('checked', result.is_reserve);

    $('#duplicatable').attr('checked', result.is_duplicatable);

    $('#HLROnline').attr('checked', result.on_hummedia);

    if(result.date_added) {
      var date = result.date_added.substring(0,10);
    }

    $('#dateAdded').text(date);

    $('#editedBy').text(result.edited_by);

    if ($('#editedBy').text())
    {
      if(result.date_edited)
      {
        var edited = result.date_edited.substring(0,10);
        $('#dateEdited').attr('type', 'date');
        $('#dateEdited').text(edited);
      }
    }
    else{
      $('#dateEdited').text(" N/A");
      $('#editedBy').text(" N/A");
     }

    $('#notes').val(result.notes);
    $('#notes').attr('placeholder', result.notes);
    oldItem =
    {
      quant: result.quantity,
      titl: result.title,
      reserv: result.is_reserve,
      dup: result.is_duplicatable,
      hum: result.on_hummedia,
      notes: result.notes
    };
  });

  window.HLRDESK.plugins.search({
    search: '#editCatalog-search',
    results: '#editCatalog-search-results',
    hideCheckedOut: false,
    clickCallback: function()
    {
      var item = this;
      var item = { "callNum":this.dataset.call, token: window.HLRDESK.token }
      socket.emit('inv.get', item);
      var editItem = document.getElementById('editItem');
      openModal = window.patternlibrary.displayModal(editItem);
      document.getElementById('onReserve').addEventListener('change', reserveAlert);
      document.getElementById('delete-item').addEventListener('click', deleteItem);
      document.getElementById('save-item').addEventListener('click', updateDatabase);
    }
  });

  socket.on('alertMessage', function(alertMsg){
    alert(alertMsg);
  });

}
<|endoftext|>


<commit_before>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');
const http = require('http');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;
const FS_CLIENT_SECRET = process.env.FS_CLIENT_SECRET;
const FS_CLIENT_ID = process.env.FS_CLIENT_ID;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

const foursquareVersion = '20160108';

const actionFindVenue = 'findVenue';
const intentFindVenue = 'FindVenue';

function processEvent(event) {
    var sender = event.sender.id.toString();

    if ((event.message && event.message.text) || (event.postback && event.postback.payload)) {
        var text = event.message ? event.message.text : event.postback.payload;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("Text:", text);

        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });

        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                var action = response.result.action;
                var intentName = response.result.metadata.intentName;
                var parameters = response.result.parameters;

                console.log(action);

                if (isDefined(responseData) && isDefined(responseData.facebook)) {
                    if (!Array.isArray(responseData.facebook)) {
                        try {
                            console.log('Response as formatted message');
                            sendFBMessage(sender, responseData.facebook);
                        } catch (err) {
                            sendFBMessage(sender, {text: err.message});
                        }
                    } else {
                        async.eachSeries(responseData.facebook, (facebookMessage, callback) => {
                            try {
                                if (facebookMessage.sender_action) {
                                    console.log('Response as sender action');
                                    sendFBSenderAction(sender, facebookMessage.sender_action, callback);
                                }
                                else {
                                    console.log('Response as formatted message');
                                    sendFBMessage(sender, facebookMessage, callback);
                                }
                            } catch (err) {
                                sendFBMessage(sender, {text: err.message}, callback);
                            }
                        });
                    }
                } else if (isDefined(responseText)) {
                    console.log('Response as text message');
                    // facebook API limit for text length is 320,
                    // so we must split message if needed
                    var splittedText = splitResponse(responseText);

                    async.eachSeries(splittedText, (textPart, callback) => {
                        sendFBMessage(sender, {text: textPart}, callback);
                    });
                } else if (isDefined(action) && isDefined(intentName)) {
                    if (action === actionFindVenue && intentName == intentFindVenue) {
                        if (isDefined(parameters)) {
                            console.log('Found parameters');
                            var foursquareResponse = splitResponse(findVenue(parameters));

                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                        }
                    }
                }

            }
        });

        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320) {
        return [str];
    }

    return chunkString(str, 300);
}

function chunkString(s, len) {
    var curr = len, prev = 0;

    var output = [];

    while (s[curr]) {
        if (s[curr++] == ' ') {
            output.push(s.substring(prev, curr));
            prev = curr;
            curr += len;
        }
        else {
            var currReverse = curr;
            do {
                if (s.substring(currReverse - 1, currReverse) == ' ') {
                    output.push(s.substring(prev, currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while (currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    return output;
}

function sendFBMessage(sender, messageData, callback) {
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: messageData
        }
    }, (error, response, body) => {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }

        if (callback) {
            callback();
        }
    });
}

function sendFBSenderAction(sender, action, callback) {
    setTimeout(() => {
        request({
            url: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {access_token: FB_PAGE_ACCESS_TOKEN},
            method: 'POST',
            json: {
                recipient: {id: sender},
                sender_action: action
            }
        }, (error, response, body) => {
            if (error) {
                console.log('Error sending action: ', error);
            } else if (response.body.error) {
                console.log('Error: ', response.body.error);
            }
            if (callback) {
                callback();
            }
        });
    }, 1000);
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        (error, response, body) => {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();

app.use(bodyParser.text({type: 'application/json'}));

app.get('/webhook/', (req, res) => {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(() => {
            doSubscribeRequest();
        }, 3000);
    } else {
        res.send('Error, wrong validation token');
    }
});

app.post('/webhook/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);

        if (data.entry) {
            let entries = data.entry;
            entries.forEach((entry) => {
                let messaging_events = entry.messaging;
                if (messaging_events) {
                    messaging_events.forEach((event) => {
                        if (event.message && !event.message.is_echo ||
                            event.postback && event.postback.payload) {
                            processEvent(event);
                        }
                    });
                }
            });
        }

        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

app.listen(REST_PORT, () => {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();

function formatGETOptions(parameters) {

    var options = {
        near: '&near='.concat(parameters.address),
        query: '&query='.concat(parameters.venue)
    };

    var httpOptions = {
    host: 'api.foursquare.com/v2',
    port: 80,
    path: '/venues/search?'.concat('client_id=', FS_CLIENT_ID,
        '&client_secret=', FS_CLIENT_SECRET,
        '&v=', foursquareVersion,
        '&m=foursquare',
        options.near,
        options.query)
    };

    console.log(httpOptions.path);

    return httpOptions;
}

function findVenue(parameters) {

    var response = "";

    var options = formatGETOptions(parameters);

    http.get(options, function(res){
        res.on('data', function(chunk){
            response = chunk;
            console.log(chunk);
        });
    }).on("error", function(e){
    console.log("GET error: " + e.message);
    });

    return response.name;
}<commit_msg>test get<commit_after>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');
const http = require('http');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'en';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;
const FS_CLIENT_SECRET = process.env.FS_CLIENT_SECRET;
const FS_CLIENT_ID = process.env.FS_CLIENT_ID;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

const foursquareVersion = '20160108';

const actionFindVenue = 'findVenue';
const intentFindVenue = 'FindVenue';

function processEvent(event) {
    var sender = event.sender.id.toString();

    if ((event.message && event.message.text) || (event.postback && event.postback.payload)) {
        var text = event.message ? event.message.text : event.postback.payload;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("Text:", text);

        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });

        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                var action = response.result.action;
                var intentName = response.result.metadata.intentName;
                var parameters = response.result.parameters;

                console.log(action);

                if (isDefined(responseData) && isDefined(responseData.facebook)) {
                    if (!Array.isArray(responseData.facebook)) {
                        try {
                            console.log('Response as formatted message');
                            sendFBMessage(sender, responseData.facebook);
                        } catch (err) {
                            sendFBMessage(sender, {text: err.message});
                        }
                    } else {
                        async.eachSeries(responseData.facebook, (facebookMessage, callback) => {
                            try {
                                if (facebookMessage.sender_action) {
                                    console.log('Response as sender action');
                                    sendFBSenderAction(sender, facebookMessage.sender_action, callback);
                                }
                                else {
                                    console.log('Response as formatted message');
                                    sendFBMessage(sender, facebookMessage, callback);
                                }
                            } catch (err) {
                                sendFBMessage(sender, {text: err.message}, callback);
                            }
                        });
                    }
                } else if (isDefined(responseText)) {
                    console.log('Response as text message');
                    // facebook API limit for text length is 320,
                    // so we must split message if needed
                    var splittedText = splitResponse(responseText);

                    async.eachSeries(splittedText, (textPart, callback) => {
                        sendFBMessage(sender, {text: textPart}, callback);
                    });
                } else if (isDefined(action) && isDefined(intentName)) {
                    if (action === actionFindVenue && intentName == intentFindVenue) {
                        if (isDefined(parameters)) {
                            console.log('Found parameters');
                            var foursquareResponse = splitResponse(findVenue(parameters));

                            async.eachSeries(splittedText, (textPart, callback) => {
                                sendFBMessage(sender, {text: textPart}, callback);
                            });
                        }
                    }
                }

            }
        });

        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320) {
        return [str];
    }

    return chunkString(str, 300);
}

function chunkString(s, len) {
    var curr = len, prev = 0;

    var output = [];

    while (s[curr]) {
        if (s[curr++] == ' ') {
            output.push(s.substring(prev, curr));
            prev = curr;
            curr += len;
        }
        else {
            var currReverse = curr;
            do {
                if (s.substring(currReverse - 1, currReverse) == ' ') {
                    output.push(s.substring(prev, currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while (currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    return output;
}

function sendFBMessage(sender, messageData, callback) {
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: messageData
        }
    }, (error, response, body) => {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }

        if (callback) {
            callback();
        }
    });
}

function sendFBSenderAction(sender, action, callback) {
    setTimeout(() => {
        request({
            url: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {access_token: FB_PAGE_ACCESS_TOKEN},
            method: 'POST',
            json: {
                recipient: {id: sender},
                sender_action: action
            }
        }, (error, response, body) => {
            if (error) {
                console.log('Error sending action: ', error);
            } else if (response.body.error) {
                console.log('Error: ', response.body.error);
            }
            if (callback) {
                callback();
            }
        });
    }, 1000);
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        (error, response, body) => {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();

app.use(bodyParser.text({type: 'application/json'}));

app.get('/webhook/', (req, res) => {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(() => {
            doSubscribeRequest();
        }, 3000);
    } else {
        res.send('Error, wrong validation token');
    }
});

app.post('/webhook/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);

        if (data.entry) {
            let entries = data.entry;
            entries.forEach((entry) => {
                let messaging_events = entry.messaging;
                if (messaging_events) {
                    messaging_events.forEach((event) => {
                        if (event.message && !event.message.is_echo ||
                            event.postback && event.postback.payload) {
                            processEvent(event);
                        }
                    });
                }
            });
        }

        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

app.listen(REST_PORT, () => {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();

function formatGETOptions(parameters) {

    var options = {
        near: '&near='.concat(parameters.address),
        query: '&query='.concat(parameters.venue)
    };

    var httpOptions = {
    host: 'api.foursquare.com/v2',
    port: 80,
    path: '/venues/search?'.concat('client_id=', FS_CLIENT_ID,
        '&client_secret=', FS_CLIENT_SECRET,
        '&v=', foursquareVersion,
        '&m=foursquare',
        options.near,
        options.query)
    };

    console.log(httpOptions.path);

    return httpOptions;
}

function findVenue(parameters) {

    var response = "";

    var options = formatGETOptions(parameters);

    http.get(options, function(res){
        res.on('data', function(chunk){
            response = chunk;
            console.log(chunk);
        });
    }).on("error", function(e){
    console.log("GET error: " + e.message);
    });

    console.log(response.name);
    return response.name;
}<|endoftext|>