<commit_before>#!/usr/bin/env node

/**
 * This script gathers dates and payload names from the subreddit launch manifest,
 * fuzzy checks them against existing upcoming payload id's and updates the date if a
 * change is made in the wiki. The proper time zone is calculated from the launch site
 * id of the launch. It also updates the flight number order based on the launch manifest order.
 *
 * Hopefully the format of the wiki does not change, but there's no real reason for it to change in the
 * forseeable future. If it does change, this script will have to be updated as necessary.
 */

const MongoClient = require('mongodb');
const moment = require('moment-timezone');
const cheerio = require('cheerio');
const request = require('request-promise-native');
const fuzz = require('fuzzball');

moment.suppressDeprecationWarnings = true;

let client;
let location;
let calculatedTimes;
let localTime;
let date;

const sites = [];
const payloads = [];
const promises = [];
const precision = [];
const flight_numbers = [];

// RegEx expressions for matching dates in the wiki manifest
// Allows for long months or short months ex. September vs Sep
// Allows for time with or without brackets ex [23:45] vs 23:45
const hour = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}\s(\[[0-9]{2}:[0-9]{2}\]|[0-9]{2}:[0-9]{2})$/;
const day = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}$/;
const month = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})$/;
const year = /^[0-9]{4}$/;

(async () => {
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });

    const db = client.db('spacex-api');
    const col = db.collection('launch');

    const launches = await col.find({ upcoming: true }).sort({ flight_number: 1 }).toArray();
    const base_flight_number = launches[0].flight_number;

    // Collect site names for time zone and payload name for fuzzy check
    launches.forEach(launch => {
      // Add temp fix for last Iridium NEXT launch because we need fuzzy
      // search to return 100% substring match, else we get SSO-A and SSO-B changing
      // because of a slight difference.
      // NOTE: Will be removed after launch
      if (launch.rocket.second_stage.payloads[0].payload_id === 'Iridium NEXT 8') {
        payloads.push('Iridium 8');
      } else {
        payloads.push(launch.rocket.second_stage.payloads[0].payload_id);
      }
      sites.push(launch.launch_site.site_id);
    });

    // Grab subreddit wiki manifest
    const result = await request('https://www.reddit.com/r/spacex/wiki/launches/manifest');
    const $ = cheerio.load(result);

    // Grab entire row, clean date, and convert to valid UTC moment date
    const manifest = $('body > div.content > div > div > table:nth-child(6) > tbody').text();
    const manifest_row = manifest.split('\n').filter(v => v !== '');

    // Filter to collect manaifest dates
    const manifest_dates = manifest_row.filter((value, index) => {
      return index % 8 === 0;
    });

    // Filter to collect payload names
    const manifest_payloads = manifest_row.filter((value, index) => {
      return (index + 3) % 8 === 0;
    });

    // Compare each payload against entire list of manifest payloads, and fuzzy match the
    // payload id against the manifest payload name. The partial match must be 100%, to avoid
    // conflicts like SSO-A and SSO-B, where a really close match would produce wrong results.
    payloads.forEach((payload, p_index) => {
      manifest_payloads.forEach((manifest_payload, m_index) => {
        if (fuzz.partial_ratio(payload, manifest_payload) === 100) {
          // Check and see if dates match a certain patten depending on the length of the
          // date given. This sets the amount of precision needed for the date.
          let mdate = manifest_dates[m_index];
          if (mdate.includes('Q')) {
            mdate = mdate.replace('Q', '');
            precision[m_index] = 'quarter';
          } else if (mdate.includes('H1')) {
            mdate = mdate.replace('H1', '1');
            precision[m_index] = 'half';
          } else if (mdate.includes('H2')) {
            mdate = mdate.replace('H2', '3');
            precision[m_index] = 'half';
          } else if (year.test(mdate)) {
            precision[m_index] = 'year';
          } else if (month.test(mdate)) {
            precision[m_index] = 'month';
          } else if (day.test(mdate)) {
            precision[m_index] = 'day';
          } else if (hour.test(mdate)) {
            precision[m_index] = 'hour';
          } else {
            console.log('Date did not match any of the existing regular expressions');
            process.exit(1);
          }

          // Store site_id for update query
          // Store manifest date for cleaning
          location = sites[p_index];
          date = manifest_dates[m_index];

          console.log(date);
          console.log(`${payload} : ${manifest_payload}`);

          // Strip brackets from time given, and tack on UTC time offset at the end for date parser
          const stripped_time = `${date.replace('[', '').replace(']', '')} +0000`;
          // Feed stripped time into all possible date formats in the wiki currently
          const time = moment(stripped_time, ['YYYY MMM D HH:mm Z', 'YYYY MMM D Z', 'YYYY MMM Z', 'YYYY Q Z', 'YYYY Z']);
          const zone = moment.tz(time, 'UTC');

          // Set timezone based on launch site id
          if (location === 'ccafs_slc_40' || location === 'ksc_lc_39a' || location === 'ccafs_lc_13') {
            localTime = time.tz('America/New_York').format();
          } else if (location === 'vafb_slc_4e' || location === 'vafb_slc_4w') {
            localTime = time.tz('America/Los_Angeles').format();
          } else {
            localTime = time.tz('America/Chicago').format();
          }

          // Add flight numbers to array to check for duplicates
          flight_numbers.push(base_flight_number + m_index);

          // Build launch time objects to update
          calculatedTimes = {
            flight_number: (base_flight_number + m_index),
            launch_date_unix: zone.unix(),
            launch_date_utc: zone.toISOString(),
            launch_date_local: localTime,
            is_tentative: true,
            tentative_max_precision: precision[m_index],
          };
          console.log(calculatedTimes);
          console.log('');

          // Another special case added for last Iridium launch
          // NOTE: Will be removed after launch
          if (payload === 'Iridium 8') {
            payload = 'Iridium NEXT 8';
          }

          // Add to array of promises to update all at once after the forEach iterations finish
          promises.push(col.updateOne({ 'rocket.second_stage.payloads.payload_id': payload }, { $set: calculatedTimes }));
        }
      });
    });

    // Check if duplicate flight numbers exist
    if ([...new Set(flight_numbers)].length < flight_numbers.length) {
      console.log('Duplicate flight numbers found');
      process.exit(1);
    }

    // Execute all our stored update promises
    const output = await Promise.all(promises);

    // Display if the document was found, and if it was modified or not
    output.forEach(doc => {
      console.log(`N: ${doc.result.n}`);
      console.log(`Modified: ${doc.result.nModified}`);
    });
  } catch (err) {
    console.log(err.stack);
  }

  if (client) {
    client.close();
  }
})();
<commit_msg>Replace n with payload names for easier update debugging in upcoming launch script<commit_after>#!/usr/bin/env node

/**
 * This script gathers dates and payload names from the subreddit launch manifest,
 * fuzzy checks them against existing upcoming payload id's and updates the date if a
 * change is made in the wiki. The proper time zone is calculated from the launch site
 * id of the launch. It also updates the flight number order based on the launch manifest order.
 *
 * Hopefully the format of the wiki does not change, but there's no real reason for it to change in the
 * forseeable future. If it does change, this script will have to be updated as necessary.
 */

const MongoClient = require('mongodb');
const moment = require('moment-timezone');
const cheerio = require('cheerio');
const request = require('request-promise-native');
const fuzz = require('fuzzball');

moment.suppressDeprecationWarnings = true;

let client;
let location;
let calculatedTimes;
let localTime;
let date;

const sites = [];
const payloads = [];
const promises = [];
const precision = [];
const flight_numbers = [];

// RegEx expressions for matching dates in the wiki manifest
// Allows for long months or short months ex. September vs Sep
// Allows for time with or without brackets ex [23:45] vs 23:45
const hour = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}\s(\[[0-9]{2}:[0-9]{2}\]|[0-9]{2}:[0-9]{2})$/;
const day = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})\s[0-9]{1,2}$/;
const month = /^[0-9]{4}\s([a-zA-Z]{3}|[a-zA-Z]{3,9})$/;
const year = /^[0-9]{4}$/;

(async () => {
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });

    const db = client.db('spacex-api');
    const col = db.collection('launch');

    const launches = await col.find({ upcoming: true }).sort({ flight_number: 1 }).toArray();
    const base_flight_number = launches[0].flight_number;

    // Collect site names for time zone and payload name for fuzzy check
    launches.forEach(launch => {
      // Add temp fix for last Iridium NEXT launch because we need fuzzy
      // search to return 100% substring match, else we get SSO-A and SSO-B changing
      // because of a slight difference.
      // NOTE: Will be removed after launch
      if (launch.rocket.second_stage.payloads[0].payload_id === 'Iridium NEXT 8') {
        payloads.push('Iridium 8');
      } else {
        payloads.push(launch.rocket.second_stage.payloads[0].payload_id);
      }
      sites.push(launch.launch_site.site_id);
    });

    // Grab subreddit wiki manifest
    const result = await request('https://www.reddit.com/r/spacex/wiki/launches/manifest');
    const $ = cheerio.load(result);

    // Grab entire row, clean date, and convert to valid UTC moment date
    const manifest = $('body > div.content > div > div > table:nth-child(6) > tbody').text();
    const manifest_row = manifest.split('\n').filter(v => v !== '');

    // Filter to collect manaifest dates
    const manifest_dates = manifest_row.filter((value, index) => {
      return index % 8 === 0;
    });

    // Filter to collect payload names
    const manifest_payloads = manifest_row.filter((value, index) => {
      return (index + 3) % 8 === 0;
    });

    // Compare each payload against entire list of manifest payloads, and fuzzy match the
    // payload id against the manifest payload name. The partial match must be 100%, to avoid
    // conflicts like SSO-A and SSO-B, where a really close match would produce wrong results.
    payloads.forEach((payload, p_index) => {
      manifest_payloads.forEach((manifest_payload, m_index) => {
        if (fuzz.partial_ratio(payload, manifest_payload) === 100) {
          // Check and see if dates match a certain patten depending on the length of the
          // date given. This sets the amount of precision needed for the date.
          let mdate = manifest_dates[m_index];
          if (mdate.includes('Q')) {
            mdate = mdate.replace('Q', '');
            precision[m_index] = 'quarter';
          } else if (mdate.includes('H1')) {
            mdate = mdate.replace('H1', '1');
            precision[m_index] = 'half';
          } else if (mdate.includes('H2')) {
            mdate = mdate.replace('H2', '3');
            precision[m_index] = 'half';
          } else if (year.test(mdate)) {
            precision[m_index] = 'year';
          } else if (month.test(mdate)) {
            precision[m_index] = 'month';
          } else if (day.test(mdate)) {
            precision[m_index] = 'day';
          } else if (hour.test(mdate)) {
            precision[m_index] = 'hour';
          } else {
            console.log('Date did not match any of the existing regular expressions');
            process.exit(1);
          }

          // Store site_id for update query
          // Store manifest date for cleaning
          location = sites[p_index];
          date = manifest_dates[m_index];

          console.log(date);
          console.log(`${payload} : ${manifest_payload}`);

          // Strip brackets from time given, and tack on UTC time offset at the end for date parser
          const stripped_time = `${date.replace('[', '').replace(']', '')} +0000`;
          // Feed stripped time into all possible date formats in the wiki currently
          const time = moment(stripped_time, ['YYYY MMM D HH:mm Z', 'YYYY MMM D Z', 'YYYY MMM Z', 'YYYY Q Z', 'YYYY Z']);
          const zone = moment.tz(time, 'UTC');

          // Set timezone based on launch site id
          if (location === 'ccafs_slc_40' || location === 'ksc_lc_39a' || location === 'ccafs_lc_13') {
            localTime = time.tz('America/New_York').format();
          } else if (location === 'vafb_slc_4e' || location === 'vafb_slc_4w') {
            localTime = time.tz('America/Los_Angeles').format();
          } else {
            localTime = time.tz('America/Chicago').format();
          }

          // Add flight numbers to array to check for duplicates
          flight_numbers.push(base_flight_number + m_index);

          // Build launch time objects to update
          calculatedTimes = {
            flight_number: (base_flight_number + m_index),
            launch_date_unix: zone.unix(),
            launch_date_utc: zone.toISOString(),
            launch_date_local: localTime,
            is_tentative: true,
            tentative_max_precision: precision[m_index],
          };
          console.log(calculatedTimes);
          console.log('');

          // Another special case added for last Iridium launch
          // NOTE: Will be removed after launch
          if (payload === 'Iridium 8') {
            payload = 'Iridium NEXT 8';
          }

          // Add to array of promises to update all at once after the forEach iterations finish
          promises.push(col.updateOne({ 'rocket.second_stage.payloads.payload_id': payload }, { $set: calculatedTimes }));
        }
      });
    });

    // Check if duplicate flight numbers exist
    if ([...new Set(flight_numbers)].length < flight_numbers.length) {
      console.log('Duplicate flight numbers found');
      process.exit(1);
    }

    // Execute all our stored update promises
    const output = await Promise.all(promises);

    // Display if the document was found, and if it was modified or not
    output.forEach((doc, index) => {
      if (doc.result.nModified !== 0) {
        console.log(`${payloads[index]} UPDATED`);
      } else {
        console.log(`${payloads[index]}`);
      }
    });
  } catch (err) {
    console.log(err.stack);
  }

  if (client) {
    client.close();
  }
})();
<|endoftext|>


<commit_before>/**
 * Created by NicolasGERARD on 11/18/2015.
 */
// As per https://www.dokuwiki.org/devel:javascript
// If the javascript file is not lib/plugins/*/script.js
// It will not be placed in the js

// This file is used in the iframe if the window console function
// is used in order to redirect the output in the HTML page
// in a div container

// Don't forget to increment the version number in the CONSTANT WEB_CONSOLE_JS_VERSION of basis.php

console = {

    webConsole: document.querySelector("#webCodeConsole"),
    log: function (input) {
        var webConsoleLine = document.createElement("p");
        webConsoleLine.className = "webCodeConsoleLine";
        webConsoleLine.innerHTML = String(input);
        this.webConsole.appendChild(webConsoleLine);
    }

};

<commit_msg>webCodeConsole.js no output \n as
<commit_after>/**
 * Created by NicolasGERARD on 11/18/2015.
 */
// As per https://www.dokuwiki.org/devel:javascript
// If the javascript file is not lib/plugins/*/script.js
// It will not be placed in the js

// This file is used in the iframe if the window console function
// is used in order to redirect the output in the HTML page
// in a div container

// Don't forget to increment the version number in the CONSTANT WEB_CONSOLE_JS_VERSION of basis.php

console = {

    webConsole: document.querySelector("#webCodeConsole"),
    log: function (input) {
        s = String(input);
        s = s.replace('\n','
')
        var webConsoleLine = document.createElement("p");
        webConsoleLine.className = "webCodeConsoleLine";
        webConsoleLine.innerHTML = s;
        this.webConsole.appendChild(webConsoleLine);
    }

};

<|endoftext|>


<commit_before>OC.search.catagorizeResults=function(results){
	var types={};
	for(var i=0;i<results.length;i++){
		var type=results[i].type;
		if(!types[type]){
			types[type]=[];
		}
		types[type].push(results[i]);
	}
	return types;
};
OC.search.hide=function(){
	$('#searchresults').hide();
	if($('#searchbox').val().length>2){
		$('#searchbox').val('');
		if (FileList && typeof FileList.unfilter === 'function') { //TODO add hook system
			FileList.unfilter();
		}
	};
	if ($('#searchbox').val().length === 0) {
		if (FileList && typeof FileList.unfilter === 'function') { //TODO add hook system
			FileList.unfilter();
		}
	}
};
OC.search.showResults=function(results){
	if(results.length === 0){
		return;
	}
	if(!OC.search.showResults.loaded){
		var parent=$('<div/>');
		$('body').append(parent);
		parent.load(OC.filePath('search','templates','part.results.php'),function(){
			OC.search.showResults.loaded=true;
			$('#searchresults').click(function(event){
				OC.search.hide();
				event.stopPropagation();
			});
			$(document).click(function(event){
				OC.search.hide();
				if (FileList && typeof FileList.unfilter === 'function') { //TODO add hook system
					FileList.unfilter();
				}
			});
			OC.search.lastResults=results;
			OC.search.showResults(results);
		});
	}else{
		var types=OC.search.catagorizeResults(results);
		$('#searchresults').show();
		$('#searchresults tr.result').remove();
		var index=0;
		for(var typeid in types){
			var type=types[typeid];
			if(type.length>0){
				for(var i=0;i<type.length;i++){
					var row=$('#searchresults tr.template').clone();
					row.removeClass('template');
					row.addClass('result');

					row.data('type', typeid);
					row.data('name', type[i].name);
					row.data('text', type[i].text);
					row.data('index',index);

					if (i === 0){
						var typeName = OC.search.resultTypes[typeid];
						row.children('td.type').text(t('lib', typeName));
					}
					row.find('td.result div.name').text(type[i].name);
					row.find('td.result div.text').text(type[i].text);

					if (type[i].path) {
						var parent = OC.dirname(type[i].path);
						if (parent === '') {
							parent = '/';
						}
						var containerName = OC.basename(parent);
						if (containerName === '') {
							containerName = '/';
						}
						var containerLink = OC.linkTo('files', 'index.php')
							+'?dir='+encodeURIComponent(parent)
							+'&scrollto='+encodeURIComponent(type[i].name);
						row.find('td.result a')
							.attr('href', containerLink)
							.attr('title', t('core', 'Show in {folder}', {folder: containerName}));
					} else {
						row.find('td.result a').attr('href', type[i].link);
					}

					index++;
					/**
					 * Give plugins the ability to customize the search results. For example:
					 * OC.search.customResults.file = function (row, item){
				 	 *  if(item.name.search('.json') >= 0) ...
					 * };
					 */
					if(OC.search.customResults[typeid]){
						OC.search.customResults[typeid](row, type[i]);
					}
					$('#searchresults tbody').append(row);
				}
			}
		}
		$('#searchresults').on('click', 'result', function () {
			if ($(this).data('type') === 'Files') {
				//FIXME use ajax to navigate to folder & highlight file
			}
		});
	}
};
OC.search.showResults.loaded=false;

OC.search.renderCurrent=function(){
	if($('#searchresults tr.result')[OC.search.currentResult]){
		var result=$('#searchresults tr.result')[OC.search.currentResult];
		$('#searchresults tr.result').removeClass('current');
		$(result).addClass('current');
	}
};<commit_msg>add / to url to match route<commit_after>OC.search.catagorizeResults=function(results){
	var types={};
	for(var i=0;i<results.length;i++){
		var type=results[i].type;
		if(!types[type]){
			types[type]=[];
		}
		types[type].push(results[i]);
	}
	return types;
};
OC.search.hide=function(){
	$('#searchresults').hide();
	if($('#searchbox').val().length>2){
		$('#searchbox').val('');
		if (FileList && typeof FileList.unfilter === 'function') { //TODO add hook system
			FileList.unfilter();
		}
	};
	if ($('#searchbox').val().length === 0) {
		if (FileList && typeof FileList.unfilter === 'function') { //TODO add hook system
			FileList.unfilter();
		}
	}
};
OC.search.showResults=function(results){
	if(results.length === 0){
		return;
	}
	if(!OC.search.showResults.loaded){
		var parent=$('<div/>');
		$('body').append(parent);
		parent.load(OC.filePath('search','templates','part.results.php'),function(){
			OC.search.showResults.loaded=true;
			$('#searchresults').click(function(event){
				OC.search.hide();
				event.stopPropagation();
			});
			$(document).click(function(event){
				OC.search.hide();
				if (FileList && typeof FileList.unfilter === 'function') { //TODO add hook system
					FileList.unfilter();
				}
			});
			OC.search.lastResults=results;
			OC.search.showResults(results);
		});
	}else{
		var types=OC.search.catagorizeResults(results);
		$('#searchresults').show();
		$('#searchresults tr.result').remove();
		var index=0;
		for(var typeid in types){
			var type=types[typeid];
			if(type.length>0){
				for(var i=0;i<type.length;i++){
					var row=$('#searchresults tr.template').clone();
					row.removeClass('template');
					row.addClass('result');

					row.data('type', typeid);
					row.data('name', type[i].name);
					row.data('text', type[i].text);
					row.data('index',index);

					if (i === 0){
						var typeName = OC.search.resultTypes[typeid];
						row.children('td.type').text(t('lib', typeName));
					}
					row.find('td.result div.name').text(type[i].name);
					row.find('td.result div.text').text(type[i].text);

					if (type[i].path) {
						var parent = OC.dirname(type[i].path);
						if (parent === '') {
							parent = '/';
						}
						var containerName = OC.basename(parent);
						if (containerName === '') {
							containerName = '/';
						}
						var containerLink = OC.linkTo('files', 'index.php')
							+'/?dir='+encodeURIComponent(parent)
							+'&scrollto='+encodeURIComponent(type[i].name);
						row.find('td.result a')
							.attr('href', containerLink)
							.attr('title', t('core', 'Show in {folder}', {folder: containerName}));
					} else {
						row.find('td.result a').attr('href', type[i].link);
					}

					index++;
					/**
					 * Give plugins the ability to customize the search results. For example:
					 * OC.search.customResults.file = function (row, item){
				 	 *  if(item.name.search('.json') >= 0) ...
					 * };
					 */
					if(OC.search.customResults[typeid]){
						OC.search.customResults[typeid](row, type[i]);
					}
					$('#searchresults tbody').append(row);
				}
			}
		}
		$('#searchresults').on('click', 'result', function () {
			if ($(this).data('type') === 'Files') {
				//FIXME use ajax to navigate to folder & highlight file
			}
		});
	}
};
OC.search.showResults.loaded=false;

OC.search.renderCurrent=function(){
	if($('#searchresults tr.result')[OC.search.currentResult]){
		var result=$('#searchresults tr.result')[OC.search.currentResult];
		$('#searchresults tr.result').removeClass('current');
		$(result).addClass('current');
	}
};<|endoftext|>


<commit_before>/**
 * @license Copyright (c) 2011 Cello Software, LLC.
 * All rights reserved.
 * Available via the new BSD License.
 */
/*jshint
	asi: false, bitwise: false, boss: false, curly: true, eqeqeq: true, eqnull: false, es5: true,
	evil: false, expr: true, forin: true, globalstrict: false, immed: true, indent: 4, latedef: true,
	laxbreak: false, loopfunc: true, maxlen: 100, newcap: true, noarg: true, noempty: true,
	nonew: true, nomen: false, onevar: true, passfail: false, plusplus: false, shadow: false,
	strict: false, sub: false, trailing: true, undef: true, white: true
*/
/*global define: false, require: false*/

define([
	'../support/promise',
	'../support/compose',
	'./Singleton'
], function (promise, compose, Singleton) {
	'use strict';
	return compose(function LifecycleManager() {
	}, {
		process: function (model, next) {
			var dfd = promise.defer();

			function assign(Lifecycle) {
				var lifecycle = new Lifecycle(model);

				model.lifecycle = lifecycle;
				model.on('destroyed', function () {
					lifecycle.destroy();
				});
				promise.when(next(model), function (model) {
					dfd.resolve(model);
				});
			}

			if (model.lifestyle) {
				// asynchronously load the lifestyle
				model.load([model.lifestyle], assign);
			}
			// Singleton is default
			else {
				assign(Singleton);
			}

			return dfd.promise;
		}
	});
});
<commit_msg>reformat lifecycle/Manager<commit_after>/**
 * @license Copyright (c) 2011 Cello Software, LLC.
 * All rights reserved.
 * Available via the new BSD License.
 */
/*jshint
	asi: false, bitwise: false, boss: false, curly: true, eqeqeq: true, eqnull: false, es5: true,
	evil: false, expr: true, forin: true, globalstrict: false, immed: true, indent: 4, latedef: true,
	laxbreak: false, loopfunc: true, maxlen: 100, newcap: true, noarg: true, noempty: true,
	nonew: true, nomen: false, onevar: true, passfail: false, plusplus: false, shadow: false,
	strict: false, sub: false, trailing: true, undef: true, white: true
*/
/*global define: false, require: false*/

define([
	'../support/promise',
	'../support/compose',
	'./Singleton'
], function (promise, compose, Singleton) {
	'use strict';

	function LifecycleManager() {}

	return compose(LifecycleManager, {
		process: function (model, next) {
			function assign(Lifecycle) {
				var lifecycle = new Lifecycle(model);

				model.lifecycle = lifecycle;
				model.on('destroyed', function () {
					lifecycle.destroy();
				});
				promise.when(next(model), function (model) {
					dfd.resolve(model);
				});
			}

			var dfd = promise.defer();

			if (model.lifestyle) {
				// asynchronously load the lifestyle
				model.load([model.lifestyle], assign);
			}
			// Singleton is default
			else {
				assign(Singleton);
			}

			return dfd.promise;
		}
	});
});
<|endoftext|>


<commit_before>const path = require("path");
const webpack = require("webpack");

var PROD = process.env.NODE_ENV === "production";
var MINIFY = new webpack.optimize.UglifyJsPlugin({minimize: true});
var TS_LOADER = {test: /\.ts$/, loaders: ["ts-loader"]};

module.exports = [{
	name: "sunwell",
	target: "web",
	entry: {
		sunwell: path.join(__dirname, "src/Sunwell.ts"),
	},
	output: {
		path: path.resolve(__dirname, "dist"),
		filename: PROD ? "[name].min.js" : "[name].js",
		library: "Sunwell",
		libraryTarget: "commonjs2",
	},
	resolve: {
		extensions: [".webpack.js", ".web.js", ".ts", ".js"],
	},
	module: {
		loaders: [TS_LOADER],
	},
	plugins: PROD ? [MINIFY] : [],
}];
<commit_msg>Switch to libraryTarget var<commit_after>const path = require("path");
const webpack = require("webpack");

var PROD = process.env.NODE_ENV === "production";
var MINIFY = new webpack.optimize.UglifyJsPlugin({minimize: true});
var TS_LOADER = {test: /\.ts$/, loaders: ["ts-loader"]};

module.exports = [{
	name: "sunwell",
	target: "web",
	entry: {
		sunwell: path.join(__dirname, "src/Sunwell.ts"),
	},
	output: {
		path: path.resolve(__dirname, "dist"),
		filename: PROD ? "[name].min.js" : "[name].js",
		library: "Sunwell",
		libraryTarget: "var",
	},
	resolve: {
		extensions: [".webpack.js", ".web.js", ".ts", ".js"],
	},
	module: {
		loaders: [TS_LOADER],
	},
	plugins: PROD ? [MINIFY] : [],
}];
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var webpack = require('webpack')
var WebpackStrip = require('webpack-strip') // to remove console.log etc statement
var StringReplacePlugin = require('string-replace-webpack-plugin')

var host = 'localhost'
var port = 3000
var srcPath = 'src'

var production = process.env.NODE_ENV === 'production'
var dev = process.env.NODE_ENV === 'dev'
var testMode = (process.env.MODE === undefined || process.env.MODE !== 'production') ? true : false
console.log('running in production mode', production, 'in test mode', testMode)

var getSymlinkedModules = function () {
  var rootPath = path.join(__dirname, 'node_modules')
  var contents = fs.readdirSync(rootPath)
  var results = contents
    .map(function (entry) {
      var fPath = path.join(rootPath, entry)
      return fPath
    })
    .filter(function (fPath) {
      function check (entry) {
        var stats = fs.lstatSync(fPath)
        return stats.isSymbolicLink()
      }
      return check(fPath)
    })
    .map(function (fPath) {
      return fs.realpathSync(fPath)
    })
  return results
}

// add any extra folders we want to apply loaders to
var pathsToInclude = path.join(__dirname, srcPath) // getSymlinkedModules().concat( path.join(__dirname, srcPath) )

// FIXME !! temporary hack: add any paths where loaders should be apllied
// pathsToInclude.push( path.join(__dirname, "node_modules", "glView-helpers") )

// ugh, also needed because of workers (ie worker loader)
// pathsToInclude.push( path.join(__dirname, "node_modules", "usco-stl-parser")   )
// pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ctm-parser")   )
// pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ply-parser")   )

// console.log("will user loaders on",pathsToInclude)

var config = {
  host: host,
  port: port,
  devtool: 'eval',
  entry: {
    jam: './' + srcPath + '/index'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: '/dist/' // '/'+'dist'+'/'
  },
  plugins: [
    // new webpack.NoErrorsPlugin(),
    // new webpack.optimize.DedupePlugin()
    // new webpack.optimize.CommonsChunkPlugin("init.js")
    new StringReplacePlugin()
  ],
  module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' }, // ?optional[]=runtime&optional=es6.blockScoping
      // { test: /-worker*\.js$/, loader: "worker-loader",include : pathsToInclude},//if any module does "require(XXX-worker)" it converts to a web worker
      // 'react-hot',
      { test: /\.js$/, loaders: [ /* WebpackStrip.loader('console.log', 'console.error')*/, 'babel'],
      include: pathsToInclude, exclude: /(node_modules|bower_components)/ },
      { test: /\.css$/, loader: 'style-loader!css-loader' },
      // special string replacements , could be cleaner
      { test: /index.js$/, loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: `mode = 'production'`,
              replacement: function (match, p1, offset, string) {
                return 'mode = "' + process.env.NODE_ENV + '"'
              }
            }
        ]})
      },
      {
        test: /youMagineDriver.js$/,loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: 'api.',
              replacement: function (match, p1, offset, string) {
                if (testMode) {
                  return 'api-test.'
                } else {
                  return 'api.'
                }
              }
            }
        ]})
      }
    ],
    noParse: /\.min\.js/
  },
  resolve: {
    extensions: ['', '.js', '.jsx', 'json'],
    root: [
      path.join(__dirname, 'node_modules'),
    ],
    /*alias: {
        "q$":path.join(__dirname, "node_modules","usco-kernel2/src/kernel.js"),//needed only FOR DEV
    }*/
    alias: {
      'three$': path.join(__dirname, 'node_modules', 'three/three.min.js')
    }
  },
  resolveLoader: {
    root: path.join(__dirname, 'node_modules')
  }
}

// console.log("production",production,"dev",dev)

if (production) {
  config.bail = true
  config.debug = false
  config.profile = false
  config.output.pathInfo = false
  config.output.publicPath = './dist/' // withouth this, issues with webworker paths

  // config.devtool = "#source-map"
  // config.output.filename = "[name].min.js"//"[name].[hash].min.js"
  // config.output.chunkFilename = '[id].js'
  config.plugins = config.plugins.concat([
    new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production') } }),
    new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
    new webpack.optimize.DedupePlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({minimize: true }) // ,drop_console:true})
  /*
  new webpack.optimize.UglifyJsPlugin({
    mangle: {
      except: ['require', 'export', '$super', 'import']
    },
    compress: {
      warnings: false,
      sequences: true,
      dead_code: true,
      conditionals: true,
      booleans: true,
      unused: true,
      if_return: true,
      join_vars: true,
      drop_console: true
    }
  })
  , new CompressionPlugin({
    asset: "{file}.gz",
    algorithm: "gzip",
    regExp: /\.js$|\.html$/,
    threshold: 10240,
    minRatio: 0.8
  })*/
  ])

  /*config.module= {
    loaders: [
      { test: /\.json$/,   loader: "json-loader" },//?optional[]=runtime&optional=es6.blockScoping
      //{ test: /-worker*\.js$/, loader: "worker-loader",include : pathsToInclude},//if any module does "require(XXX-worker)" it converts to a web worker
      //'react-hot',
      { test: /\.js?$/, loaders: [WebpackStrip.loader('console.log', 'console.error') ,'babel', ],include : pathsToInclude,exclude: /(node_modules|bower_components)/},
      { test: /\.css$/, loader: "style-loader!css-loader" },
      //{ test: /\.js$/, loader: }

    ],
    noParse: /\.min\.js/
  }*/
  var stripLoader = {
    test: [],
    loader: WebpackStrip.loader('console.log')
  }

  config.module.loaders.push(stripLoader)
} else {
  /*config.entry = config.entry.concat([
    //'webpack-dev-server/client?',//http://'+host+":"+port,
    //'webpack/hot/only-dev-server',
  ])*/

  /*var ymReplacerLoader = {
    test: /youMagineDriver.js$/,loader: StringReplacePlugin.replace({
    replacements: [
        {
            pattern: 'api.',
            replacement: function (match, p1, offset, string) {
                return 'api-test.'
            }
        }
    ]})
  }
  config.module.loaders.push(ymReplacerLoader)*/

  config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin()
  ])
}

module.exports = config
<commit_msg>chore(build): tweaked webpack config for dev mode<commit_after>var fs = require('fs')
var path = require('path')
var webpack = require('webpack')
var WebpackStrip = require('webpack-strip') // to remove console.log etc statement
var StringReplacePlugin = require('string-replace-webpack-plugin')

var host = 'localhost'
var port = 3000
var srcPath = 'src'

var production = process.env.NODE_ENV === 'production'
var testMode = (process.env.MODE === undefined || process.env.MODE !== 'production') ? true : false
console.log('running in production mode', production, 'in test mode', testMode)

var getSymlinkedModules = function () {
  var rootPath = path.join(__dirname, 'node_modules')
  var contents = fs.readdirSync(rootPath)
  var results = contents
    .map(function (entry) {
      var fPath = path.join(rootPath, entry)
      return fPath
    })
    .filter(function (fPath) {
      function check (entry) {
        var stats = fs.lstatSync(fPath)
        return stats.isSymbolicLink()
      }
      return check(fPath)
    })
    .map(function (fPath) {
      return fs.realpathSync(fPath)
    })
  return results
}

// add any extra folders we want to apply loaders to
var pathsToInclude = path.join(__dirname, srcPath) // getSymlinkedModules().concat( path.join(__dirname, srcPath) )

// FIXME !! temporary hack: add any paths where loaders should be apllied
// pathsToInclude.push( path.join(__dirname, "node_modules", "glView-helpers") )

// ugh, also needed because of workers (ie worker loader)
// pathsToInclude.push( path.join(__dirname, "node_modules", "usco-stl-parser")   )
// pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ctm-parser")   )
// pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ply-parser")   )

// console.log("will user loaders on",pathsToInclude)

var config = {
  host: host,
  port: port,
  devtool: 'eval',
  entry: {
    jam: './' + srcPath + '/index'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: '/dist/' // '/'+'dist'+'/'
  },
  plugins: [
    // new webpack.NoErrorsPlugin(),
    // new webpack.optimize.DedupePlugin()
    // new webpack.optimize.CommonsChunkPlugin("init.js")
    new StringReplacePlugin()
  ],
  module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' }, // ?optional[]=runtime&optional=es6.blockScoping
      // { test: /-worker*\.js$/, loader: "worker-loader",include : pathsToInclude},//if any module does "require(XXX-worker)" it converts to a web worker
      // 'react-hot',
      { test: /\.js$/, loaders: [ /* WebpackStrip.loader('console.log', 'console.error')*/'babel' ],
      include: pathsToInclude, exclude: /(node_modules|bower_components)/ },
      { test: /\.css$/, loader: 'style-loader!css-loader' },
      // special string replacements , could be cleaner
      { test: /index.js$/, loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: `mode = 'production'`,
              replacement: function (match, p1, offset, string) {
                return 'mode = "' + process.env.NODE_ENV + '"'
              }
            }
        ]})
      },
      {
        test: /youMagineDriver.js$/,loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: 'api.',
              replacement: function (match, p1, offset, string) {
                if (testMode) {
                  return 'api-test.'
                } else {
                  return 'api.'
                }
              }
            }
        ]})
      }
    ],
    noParse: /\.min\.js/
  },
  resolve: {
    extensions: ['', '.js', '.jsx', 'json'],
    root: [
      path.join(__dirname, 'node_modules')
    ],
    /* alias: {
        "q$":path.join(__dirname, "node_modules","usco-kernel2/src/kernel.js"),//needed only FOR DEV
    }*/
    alias: {
      'three$': path.join(__dirname, 'node_modules', 'three/three.min.js')
    }
  },
  resolveLoader: {
    root: path.join(__dirname, 'node_modules')
  }
}

// console.log("production",production,"dev",dev)

if (production) {
  config.bail = true
  config.debug = false
  config.profile = false
  config.output.pathInfo = false
  config.output.publicPath = './dist/' // withouth this, issues with webworker paths

  // config.devtool = "#source-map"
  // config.output.filename = "[name].min.js"//"[name].[hash].min.js"
  // config.output.chunkFilename = '[id].js'
  config.plugins = config.plugins.concat([
    new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }),
    new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
    new webpack.optimize.DedupePlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({ minimize: true }) // ,drop_console:true})
  /*
  new webpack.optimize.UglifyJsPlugin({
    mangle: {
      except: ['require', 'export', '$super', 'import']
    },
    compress: {
      warnings: false,
      sequences: true,
      dead_code: true,
      conditionals: true,
      booleans: true,
      unused: true,
      if_return: true,
      join_vars: true,
      drop_console: true
    }
  })
  , new CompressionPlugin({
    asset: "{file}.gz",
    algorithm: "gzip",
    regExp: /\.js$|\.html$/,
    threshold: 10240,
    minRatio: 0.8
  })*/
  ])

  /*config.module= {
    loaders: [
      { test: /\.json$/,   loader: "json-loader" },//?optional[]=runtime&optional=es6.blockScoping
      //{ test: /-worker*\.js$/, loader: "worker-loader",include : pathsToInclude},//if any module does "require(XXX-worker)" it converts to a web worker
      //'react-hot',
      { test: /\.js?$/, loaders: [WebpackStrip.loader('console.log', 'console.error') ,'babel', ],include : pathsToInclude,exclude: /(node_modules|bower_components)/},
      { test: /\.css$/, loader: "style-loader!css-loader" },
      //{ test: /\.js$/, loader: }

    ],
    noParse: /\.min\.js/
  }*/
  var stripLoader = {
    test: [],
    loader: WebpackStrip.loader('console.log')
  }

  config.module.loaders.push(stripLoader)
} else {
  /*config.entry = config.entry.concat([
    //'webpack-dev-server/client?',//http://'+host+":"+port,
    //'webpack/hot/only-dev-server',
  ])*/

  /*var ymReplacerLoader = {
    test: /youMagineDriver.js$/,loader: StringReplacePlugin.replace({
    replacements: [
        {
            pattern: 'api.',
            replacement: function (match, p1, offset, string) {
                return 'api-test.'
            }
        }
    ]})
  }
  config.module.loaders.push(ymReplacerLoader)*/

  config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1})
  ])
}

module.exports = config
<|endoftext|>


<commit_before>const webpack = require('webpack');
const path = require('path');
const BabiliPlugin = require("babili-webpack-plugin"); // uglifier for typescript
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

const name = 'natural-gallery';

module.exports = function(env) {

    const prod = process.env.NODE_ENV === 'production';
    const dependencies = !(env && env.nodependencies === true);

    let entry = {'app': './app/app.ts'};
    let outName = name;
    if (dependencies) {
        entry = {'full': './app/full.ts'};
        outName = name + '.full';
    }

    const extractCSS = new ExtractTextPlugin("themes/natural.css");
    const extractSASS = new ExtractTextPlugin(outName + ".css");

    let plugins = [
        extractCSS,
        extractSASS,
        new OptimizeCssAssetsPlugin({
            assetNameRegExp: /natural-gallery\.css$/g,
            cssProcessor: require('cssnano'),
            cssProcessorOptions: {
                discardComments: {removeAll: prod},
                sourceMap: !prod
            },
            canPrint: true
        })
    ];

    let externals = {};
    if (!dependencies) {
        plugins.push(new DtsBundlePlugin());
        plugins.push(new webpack.WatchIgnorePlugin([
            /\.d\.ts$/
        ]));
        externals = {
            'photoswipe': 'PhotoSwipe',
            'photoswipe/dist/photoswipe-ui-default': 'PhotoSwipeUI_Default'
        }
    }

    if (prod) {
        plugins.push(new BabiliPlugin());
    }

    return {
        entry: entry,
        output: {
            path: __dirname + '/dist',
            filename: outName + '.js',
            library: "NaturalGallery",
            libraryTarget: 'umd',
            umdNamedDefine: true
        },
        devServer: {
            contentBase: './demo'
        },
        devtool: prod ? false : "source-map", // 'inline-source-map'
        resolve: {
            extensions: [".ts", ".js"],
        },
        plugins: plugins,
        externals: externals,
        module: {
            rules: [
                {
                    test: /\.ts?$/,
                    loader: "awesome-typescript-loader"
                }, {
                    enforce: "pre",
                    test: /\.js$/,
                    loader: "source-map-loader"
                }, {
                    test: /\.css$/,
                    loader: extractCSS.extract(['css-loader']),
                }, {
                    test: /\.scss$/,
                    loader: extractSASS.extract({
                        fallback: 'style-loader',
                        use: [
                            {
                                loader: 'css-loader',
                                options: {
                                    sourceMap: !prod,
                                    minimize: prod
                                }
                            }, {
                                loader: 'postcss-loader',
                                options: {sourceMap: 'inline'}
                            }, {
                                loader: 'sass-loader',
                                options: {
                                    sourceMap: !prod,
                                    sourceMapContents: !prod,
                                    outputStyle: 'expanded'
                                }
                            }
                        ]
                    })
                }, {
                    test: /\.(gif|png|jpe?g|svg)$/i,
                    loaders: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: 'images/[name].[ext]'
                            }
                        },
                        {
                            loader: 'image-webpack-loader',
                            query: {
                                mozjpeg: {
                                    progressive: true,
                                },
                                pngquant: {
                                    quality: '65-90',
                                    speed: 4,
                                    optimizationLevel: 7,
                                    interlaced: false,
                                },
                                gifsicle: {
                                    optimizationLevel: 7,
                                    interlaced: false
                                },
                            }
                        }
                    ]
                }
            ]
        },
    }
};

function DtsBundlePlugin(name, main) {
}

DtsBundlePlugin.prototype.apply = function(compiler) {
    compiler.plugin('done', function() {
        var dts = require('dts-bundle');

        dts.bundle({
            name: name,
            main: 'app/app.d.ts',
            out: '../dist/index.d.ts',
            removeSource: true,
            outputAsModuleFolder: true // to use npm in-package typings
        });
    });
};
<commit_msg>Prevent to remove sources when generating .d.ts files<commit_after>const webpack = require('webpack');
const path = require('path');
const BabiliPlugin = require("babili-webpack-plugin"); // uglifier for typescript
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

const name = 'natural-gallery';

module.exports = function(env) {

    const prod = process.env.NODE_ENV === 'production';
    const dependencies = !(env && env.nodependencies === true);

    let entry = {'app': './app/app.ts'};
    let outName = name;
    if (dependencies) {
        entry = {'full': './app/full.ts'};
        outName = name + '.full';
    }

    const extractCSS = new ExtractTextPlugin("themes/natural.css");
    const extractSASS = new ExtractTextPlugin(outName + ".css");

    let plugins = [
        extractCSS,
        extractSASS,
        new OptimizeCssAssetsPlugin({
            assetNameRegExp: /natural-gallery\.css$/g,
            cssProcessor: require('cssnano'),
            cssProcessorOptions: {
                discardComments: {removeAll: prod},
                sourceMap: !prod
            },
            canPrint: true
        })
    ];

    let externals = {};
    if (!dependencies) {
        plugins.push(new DtsBundlePlugin());
        plugins.push(new webpack.WatchIgnorePlugin([
            /\.d\.ts$/
        ]));
        externals = {
            'photoswipe': 'PhotoSwipe',
            'photoswipe/dist/photoswipe-ui-default': 'PhotoSwipeUI_Default'
        }
    }

    if (prod) {
        plugins.push(new BabiliPlugin());
    }

    return {
        entry: entry,
        output: {
            path: __dirname + '/dist',
            filename: outName + '.js',
            library: "NaturalGallery",
            libraryTarget: 'umd',
            umdNamedDefine: true
        },
        devServer: {
            contentBase: './demo'
        },
        devtool: prod ? false : "source-map", // 'inline-source-map'
        resolve: {
            extensions: [".ts", ".js"],
        },
        plugins: plugins,
        externals: externals,
        module: {
            rules: [
                {
                    test: /\.ts?$/,
                    loader: "awesome-typescript-loader"
                }, {
                    enforce: "pre",
                    test: /\.js$/,
                    loader: "source-map-loader"
                }, {
                    test: /\.css$/,
                    loader: extractCSS.extract(['css-loader']),
                }, {
                    test: /\.scss$/,
                    loader: extractSASS.extract({
                        fallback: 'style-loader',
                        use: [
                            {
                                loader: 'css-loader',
                                options: {
                                    sourceMap: !prod,
                                    minimize: prod
                                }
                            }, {
                                loader: 'postcss-loader',
                                options: {sourceMap: 'inline'}
                            }, {
                                loader: 'sass-loader',
                                options: {
                                    sourceMap: !prod,
                                    sourceMapContents: !prod,
                                    outputStyle: 'expanded'
                                }
                            }
                        ]
                    })
                }, {
                    test: /\.(gif|png|jpe?g|svg)$/i,
                    loaders: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: 'images/[name].[ext]'
                            }
                        },
                        {
                            loader: 'image-webpack-loader',
                            query: {
                                mozjpeg: {
                                    progressive: true,
                                },
                                pngquant: {
                                    quality: '65-90',
                                    speed: 4,
                                    optimizationLevel: 7,
                                    interlaced: false,
                                },
                                gifsicle: {
                                    optimizationLevel: 7,
                                    interlaced: false
                                },
                            }
                        }
                    ]
                }
            ]
        },
    }
};

function DtsBundlePlugin(name, main) {
}

DtsBundlePlugin.prototype.apply = function(compiler) {
    compiler.plugin('done', function() {
        var dts = require('dts-bundle');

        dts.bundle({
            name: name,
            main: 'app/app.d.ts',
            out: '../dist/index.d.ts',
            removeSource: false,
            outputAsModuleFolder: true // to use npm in-package typings
        });
    });
};
<|endoftext|>


<commit_before>var lblStatus;
var longitude, latitude;

function MarcoWindow() {

	var self = Ti.UI.createWindow({
		title: 'Marco',
		backgroundColor: '#fff'
	});

/*
var mountainView = Titanium.Map.createAnnotation({
	latitude:37.390749,
	longitude:-122.081651,
	title:"Appcelerator Headquarters",
	subtitle:'Mountain View, CA',
	pincolor:Titanium.Map.ANNOTATION_PURPLE,
	animate:true,
	image: 'KS_nav_ui.png',
	leftButton: '../images/appcelerator_small.png',
	myid:1 // Custom property to uniquely identify this annotation.
});
*/
lblStatus = Ti.UI.createLabel();

var mapview = Titanium.Map.createView({
	mapType : Titanium.Map.STANDARD_TYPE,
	animate : true,
	regionFit : true,
	userLocation : true/*,
	annotations: [ mountainView ]*/
});

	self.addEventListener('open', function() {
		findMe();

		mapview.setRegion({
			latitude: latitude,
			longitude: longitude,
			latitudeDelta:0.01,
			longitudeDelta:0.01
		});
	});

	self.add(mapview);

	return self;
}

/// CBR will me externalised
function findMe(statusLabel) {
	lblStatus.text = 'Geolocating...';

	if (Ti.Geolocation) {
		Ti.Geolocation.purpose = 'To find current location.';
		Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_BEST;
		Ti.Geolocation.distanceFilter = 0;

		Ti.Geolocation.getCurrentPosition(function (e) {
			if (!e.success || e.error) {
				lblStatus.text = 'GPS lost';
			}
			else {
				lblStatus.text = 'Location determined...';

				latitude = e.coords.latitude;
				longitude = e.coords.longitude;
			}
		});
	}
	else {
		Cloud.Clients.geolocate(function (e) {
			if (e.success) {
				lblStatus.text = 'Location determined...';

				latitude = e.location.latitude;
				longitude = e.location.longitude;
			}
			else {
				lblStatus.text = 'GPS lost';
			}
		});
	}
}

module.exports = MarcoWindow;<commit_msg>Polo (map) works on iOS<commit_after>var lblStatus;
var longitude, latitude;

function MarcoWindow() {

	var self = Ti.UI.createWindow({
		title: 'Marco',
		backgroundColor: '#fff'
	});

	var mountainView = Titanium.Map.createAnnotation({
		latitude: 37.390749,
		longitude: -122.081651,
		title: "Appcelerator Headquarters",
		subtitle: 'Mountain View, CA',
		pincolor: Titanium.Map.ANNOTATION_PURPLE,
		animate: true,
		image: 'KS_nav_ui.png',
		leftButton: 'KS_nav_views.png',
	});

	lblStatus = Ti.UI.createLabel();

	var mapview = Titanium.Map.createView({
		mapType: Titanium.Map.STANDARD_TYPE,
		animate: true,
		regionFit: true,
		userLocation: true
		//annotations: [mountainView]
	});

	self.addEventListener('open', function() {
		findMe();

		Cloud.Places.search({
			// No params to get everyone
		}, function(e) {
			if (e.success) {
				var annotations = [];
				for (var i = 0; i < e.places.length; i++) {
					var place = e.places[i];

					annotations.push(Titanium.Map.createAnnotation({
						latitude: place.latitude,
						longitude: place.longitude,
						title: place.name,
						pincolor: Titanium.Map.ANNOTATION_PURPLE,
						animate: true,
					}));
					Ti.API.debug('id: ' + place.id + '  name: ' + place.name + '  longitude: ' + place.longitude + '  latitude: ' + place.latitude);
				}

				mapview.setAnnotations(annotations);
			} else {
				alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
			}
		});

		mapview.setRegion({
			latitude: latitude,
			longitude: longitude,
			latitudeDelta: 0.01,
			longitudeDelta: 0.01
		});
	});

	self.add(mapview);

	return self;
}

/// CBR will be externalised
function findMe(statusLabel) {
	lblStatus.text = 'Geolocating...';

	if (Ti.Geolocation) {
		Ti.Geolocation.purpose = 'To find current location.';
		Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_BEST;
		Ti.Geolocation.distanceFilter = 0;

		Ti.Geolocation.getCurrentPosition(function(e) {
			if (!e.success || e.error) {
				lblStatus.text = 'GPS lost';
			} else {
				lblStatus.text = 'Location determined...';

				latitude = e.coords.latitude;
				longitude = e.coords.longitude;
			}
		});
	} else {
		Cloud.Clients.geolocate(function(e) {
			if (e.success) {
				lblStatus.text = 'Location determined...';

				latitude = e.location.latitude;
				longitude = e.location.longitude;
			} else {
				lblStatus.text = 'GPS lost';
			}
		});
	}
}

module.exports = MarcoWindow;<|endoftext|>


<commit_before>const webpack = require('webpack');
const helpers = require('./helpers');

const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HMR = helpers.hasProcessFlag('hot');

var metadata = {
  title: 'OPEN',
  baseUrl: '/',
  host: 'localhost',
  port: 3000,
  ENV: ENV,
  HMR: HMR
};
/*
 * Config
 * with default values at webpack.default.conf
 */
module.exports = {
  // static data for index.html
  metadata: metadata,
  devtool: 'cheap-module-eval-source-map',
  // cache: true,
  debug: true,
  // devtool: 'eval' // for faster builds use 'eval'

  // our angular app
  entry: {
    'polyfills': helpers.root('src/polyfills.ts'),
    'vendor': helpers.root('src/vendor.ts'),
    'app': helpers.root('src/app.ts'),
    'main-scripts': [
      helpers.root('node_modules/jquery/dist/jquery.min.js'),
      helpers.root('src/assets/js/jqueryelectron.js'),
      helpers.root('node_modules/bootstrap/dist/js/bootstrap.min.js')]
  },

  resolve: {
    extensions: ['', '.ts', '.js']
  },

  // Config for our build files
  output: {
    path: helpers.root('dist'),
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

  module: {
    preLoaders: [
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },
      // TODO(gdi2290): `exclude: [ helpers.root('node_modules/rxjs') ]` fixed with rxjs 5 beta.3 release
      { test: /\.js$/, loader: 'source-map-loader', exclude: [helpers.root('node_modules/rxjs')] }
    ],
    loaders: [
      // Support for .ts files.
      { test: /\.ts$/, loader: 'awesome-typescript-loader', exclude: [/\.(spec|e2e)\.ts$/] },

      // Support for *.json files.
      { test: /\.json$/, loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/, loader: 'style-loader!css-loader' },

      // support for .html as raw text
      { test: /\.html$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')] },

      // the url-loader uses DataUrls. // the file-loader emits files.
      { test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml' }
    ]
  },

  plugins: [
    new ForkCheckerPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({ name: ['vendor', 'polyfills'], minChunks: Infinity }),
    // static assets
    new CopyWebpackPlugin([
      { from: 'src/assets', to: 'assets' },

      { from: 'src/app/components', to: 'app/components' },
      { from: 'src/app.html', to: 'app.html' },
      { from: 'src/main.js', to: 'main.js' },
      { from: 'src/package.json', to: 'package.json' },
      { from: 'src/app/shared/enums', to: 'app/shared/enums' },
      { from: 'src/app/shared/models', to: 'app/shared/models' },
      { from: 'src/app/shared/pipes', to: 'app/shared/pipes' },
      { from: 'src/app/shared/plugins', to: 'app/shared/plugins' },
      { from: 'src/app/shared/services', to: 'app/shared/services' },

      { from: 'backend', to: 'backend' },

      { from: 'node_modules/body-parser', to: 'node_modules/body-parser' },
      { from: 'node_modules/express', to: 'node_modules/express' },
      { from: 'node_modules/lowdb', to: 'node_modules/lowdb' },
      { from: 'node_modules/multer', to: 'node_modules/multer' },
      { from: 'node_modules/ms', to: 'node_modules/ms' },
      { from: 'node_modules/electron-squirrel-startup', to: 'node_modules/electron-squirrel-startup' }
    ]),
    // generating html
    new HtmlWebpackPlugin({ template: helpers.root('src/index.html'), chunksSortMode: 'none' }),
    // Environment helpers (when adding more properties make sure you include them in custom-typings.d.ts)
    new webpack.DefinePlugin({
      'ENV': JSON.stringify(metadata.ENV),
      'HMR': HMR
    })
  ],

  // Other module loader config

  // our Webpack Development Server config
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src',
  },
  devServer: {
    port: metadata.port,
    host: metadata.host,
    historyApiFallback: true,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    }
  },
  node: {
    global: 'window',
    process: true,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};
<commit_msg>copying the new guid module in build folder<commit_after>const webpack = require('webpack');
const helpers = require('./helpers');

const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HMR = helpers.hasProcessFlag('hot');

var metadata = {
  title: 'OPEN',
  baseUrl: '/',
  host: 'localhost',
  port: 3000,
  ENV: ENV,
  HMR: HMR
};
/*
 * Config
 * with default values at webpack.default.conf
 */
module.exports = {
  // static data for index.html
  metadata: metadata,
  devtool: 'cheap-module-eval-source-map',
  // cache: true,
  debug: true,
  // devtool: 'eval' // for faster builds use 'eval'

  // our angular app
  entry: {
    'polyfills': helpers.root('src/polyfills.ts'),
    'vendor': helpers.root('src/vendor.ts'),
    'app': helpers.root('src/app.ts'),
    'main-scripts': [
      helpers.root('node_modules/jquery/dist/jquery.min.js'),
      helpers.root('src/assets/js/jqueryelectron.js'),
      helpers.root('node_modules/bootstrap/dist/js/bootstrap.min.js')]
  },

  resolve: {
    extensions: ['', '.ts', '.js']
  },

  // Config for our build files
  output: {
    path: helpers.root('dist'),
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

  module: {
    preLoaders: [
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },
      // TODO(gdi2290): `exclude: [ helpers.root('node_modules/rxjs') ]` fixed with rxjs 5 beta.3 release
      { test: /\.js$/, loader: 'source-map-loader', exclude: [helpers.root('node_modules/rxjs')] }
    ],
    loaders: [
      // Support for .ts files.
      { test: /\.ts$/, loader: 'awesome-typescript-loader', exclude: [/\.(spec|e2e)\.ts$/] },

      // Support for *.json files.
      { test: /\.json$/, loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/, loader: 'style-loader!css-loader' },

      // support for .html as raw text
      { test: /\.html$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')] },

      // the url-loader uses DataUrls. // the file-loader emits files.
      { test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml' }
    ]
  },

  plugins: [
    new ForkCheckerPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({ name: ['vendor', 'polyfills'], minChunks: Infinity }),
    // static assets
    new CopyWebpackPlugin([
      { from: 'src/assets', to: 'assets' },

      { from: 'src/app/components', to: 'app/components' },
      { from: 'src/app.html', to: 'app.html' },
      { from: 'src/main.js', to: 'main.js' },
      { from: 'src/package.json', to: 'package.json' },
      { from: 'src/app/shared/enums', to: 'app/shared/enums' },
      { from: 'src/app/shared/models', to: 'app/shared/models' },
      { from: 'src/app/shared/pipes', to: 'app/shared/pipes' },
      { from: 'src/app/shared/plugins', to: 'app/shared/plugins' },
      { from: 'src/app/shared/services', to: 'app/shared/services' },

      { from: 'backend', to: 'backend' },

      { from: 'node_modules/body-parser', to: 'node_modules/body-parser' },
      { from: 'node_modules/express', to: 'node_modules/express' },
      { from: 'node_modules/lowdb', to: 'node_modules/lowdb' },
      { from: 'node_modules/multer', to: 'node_modules/multer' },
      { from: 'node_modules/ms', to: 'node_modules/ms' },
      { from: 'node_modules/electron-squirrel-startup', to: 'node_modules/electron-squirrel-startup' },
      { from: 'node_modules/guid', to: 'node_modules/guid' }
    ]),
    // generating html
    new HtmlWebpackPlugin({ template: helpers.root('src/index.html'), chunksSortMode: 'none' }),
    // Environment helpers (when adding more properties make sure you include them in custom-typings.d.ts)
    new webpack.DefinePlugin({
      'ENV': JSON.stringify(metadata.ENV),
      'HMR': HMR
    })
  ],

  // Other module loader config

  // our Webpack Development Server config
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src',
  },
  devServer: {
    port: metadata.port,
    host: metadata.host,
    historyApiFallback: true,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    }
  },
  node: {
    global: 'window',
    process: true,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};
<|endoftext|>


<commit_before>process.traceDeprecation = true;
const path = require("path");
const package_json = require("./package.json");
const patternslib_package_json = require("@patternslib/patternslib/package.json");
const patternslib_config = require("@patternslib/dev/webpack/webpack.config");
const mf_config = require("@patternslib/dev/webpack/webpack.mf");

module.exports = (env, argv) => {
    let config = {
        entry: {
            "bundle.min": path.resolve(__dirname, "src/index.js"),
            "bootstrap.min": path.resolve(__dirname, "src/index-bootstrap.js"),
            "jquery.min": path.resolve(__dirname, "src/index-jquery.js"),
        },
    };

    config = patternslib_config(env, argv, config, ["@plone/mockup"]);

    config.output.path = path.resolve(__dirname, "dist/");

    config.plugins.push(
        mf_config({
            name: "patternslib",
            filename: "remote.min.js",
            remote_entry: config.entry["bundle.min"],
            dependencies: {
                ...patternslib_package_json.dependencies,
                ...package_json.dependencies,
            },
        })
    );
    config.plugins.push(
        mf_config({
            name: "bootstrap",
            filename: "bootstrap-remote.min.js",
            remote_entry: config.entry["bootstrap.min"],
            dependencies: {
                bootstrap: package_json.dependencies["bootstrap"],
            },
        })
    );
    config.plugins.push(
        mf_config({
            name: "jquery",
            filename: "jquery-remote.min.js",
            remote_entry: config.entry["jquery.min"],
            dependencies: {
                jquery: package_json.dependencies["jquery"],
            },
        })
    );

    if (process.env.NODE_ENV === "development") {
        // Note: ``publicPath`` is set to "auto" in Patternslib,
        //        so for the devServer the public path set to "/".
        config.devServer.port = "8000";
        config.devServer.static.directory = path.resolve(
            __dirname,
            "./docs/_site/"
        );
    }

    if (env && env.DEPLOYMENT === "plone") {
        config.output.path = path.resolve(
            __dirname,
            "../plone.staticresources/src/plone/staticresources/static/bundle-plone/"
        );
    }

    //console.log(JSON.stringify(config, null, 4));

    return config;
};
<commit_msg>Cleanup.<commit_after>process.traceDeprecation = true;
const path = require("path");
const package_json = require("./package.json");
const patternslib_package_json = require("@patternslib/patternslib/package.json");
const patternslib_config = require("@patternslib/dev/webpack/webpack.config");
const mf_config = require("@patternslib/dev/webpack/webpack.mf");

module.exports = (env, argv) => {
    let config = {
        entry: {
            "bundle.min": path.resolve(__dirname, "src/index.js"),
            "bootstrap.min": path.resolve(__dirname, "src/index-bootstrap.js"),
            "jquery.min": path.resolve(__dirname, "src/index-jquery.js"),
        },
    };

    config = patternslib_config(env, argv, config, ["@plone/mockup"]);

    config.output.path = path.resolve(__dirname, "dist/");

    config.plugins.push(
        mf_config({
            name: "patternslib",
            filename: "remote.min.js",
            remote_entry: config.entry["bundle.min"],
            dependencies: {
                ...patternslib_package_json.dependencies,
                ...package_json.dependencies,
            },
        })
    );
    config.plugins.push(
        mf_config({
            name: "bootstrap",
            filename: "bootstrap-remote.min.js",
            remote_entry: config.entry["bootstrap.min"],
            dependencies: {
                bootstrap: package_json.dependencies["bootstrap"],
            },
        })
    );
    config.plugins.push(
        mf_config({
            name: "jquery",
            filename: "jquery-remote.min.js",
            remote_entry: config.entry["jquery.min"],
            dependencies: {
                jquery: package_json.dependencies["jquery"],
            },
        })
    );

    if (process.env.NODE_ENV === "development") {
        // Note: ``publicPath`` is set to "auto" in Patternslib,
        //        so for the devServer the public path set to "/".
        config.devServer.port = "8000";
        config.devServer.static.directory = path.resolve(__dirname, "./docs/_site/");
    }

    if (env && env.DEPLOYMENT === "plone") {
        config.output.path = path.resolve(
            __dirname,
            "../plone.staticresources/src/plone/staticresources/static/bundle-plone/"
        );
    }

    //console.log(JSON.stringify(config, null, 4));

    return config;
};
<|endoftext|>


<commit_before>var Encore = require('@symfony/webpack-encore');

Encore
// directory where all compiled assets will be stored
    .setOutputPath('html/build/')

    // what's the public path to this directory (relative to your project's document root dir)
    .setPublicPath('/build')

    // empty the outputPath dir before each build
    .cleanupOutputBeforeBuild()

    // will output as build/admin.js and similar
    .addEntry('admin', './html/js/src/admin.js')
    .addEntry('public', './html/js/src/public.js')

    // allow sass/scss files to be processed
    .enableSassLoader(function(sassOptions) {}, {
        // see: http://symfony.com/doc/current/frontend/encore/bootstrap.html#importing-bootstrap-sass
        resolve_url_loader: false
    })
    .enablePostCssLoader()
    // allow .vue files to be processed
    .enableVueLoader()

    .enableSourceMaps(true)

    // create hashed filenames (e.g. public.abc123.css)
    .enableVersioning()
;

// export the final configuration
let config = Encore.getWebpackConfig();

config.resolve.alias['vue$'] = 'vue/dist/vue.common.js';

if (Encore.isProduction()) {
    config.devtool = 'source-map';
}

module.exports = config;
<commit_msg>showing some webpack stats<commit_after>var Encore = require('@symfony/webpack-encore');

Encore
// directory where all compiled assets will be stored
    .setOutputPath('html/build/')

    // what's the public path to this directory (relative to your project's document root dir)
    .setPublicPath('/build')

    // empty the outputPath dir before each build
    .cleanupOutputBeforeBuild()

    // will output as build/admin.js and similar
    .addEntry('admin', './html/js/src/admin.js')
    .addEntry('public', './html/js/src/public.js')

    // allow sass/scss files to be processed
    .enableSassLoader(function(sassOptions) {}, {
        // see: http://symfony.com/doc/current/frontend/encore/bootstrap.html#importing-bootstrap-sass
        resolve_url_loader: false
    })
    .enablePostCssLoader()
    // allow .vue files to be processed
    .enableVueLoader()

    .enableSourceMaps(true)

    // create hashed filenames (e.g. public.abc123.css)
    .enableVersioning()
;

// export the final configuration
let config = Encore.getWebpackConfig();

config.resolve.alias['vue$'] = 'vue/dist/vue.common.js';

// See: https://github.com/symfony/webpack-encore/blob/master/lib/config-generator.js#L223
// See: https://webpack.js.org/configuration/stats/
config.stats.assets = true;
config.stats.source = true;

if (Encore.isProduction()) {
    config.devtool = 'source-map';
}

module.exports = config;
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');

// helpers for writing path names
// e.g. join("web/static") => "/full/disk/path/to/hello/web/static"
function join(dest) { return path.resolve(__dirname, dest); }

function web(dest) { return join('web/static/' + dest); }

var config = module.exports = {

    devtool: 'source-map',

    // our application's entry points - for this example we'll use a single each for
    // css and js
    entry: {
        application: [
            web('css/application.sass'),
            web('js/application.js'),
        ],
    },

    // where webpack should output our files
    output: {
        path: join('priv/static'),
        filename: 'js/application.js',
    },

    resolve: {
        extensions: ['', '.js', '.sass'],
        modulesDirectories: ['node_modules'],
    },

    // more information on how our modules are structured, and
    //
    // in this case, we'll define our loaders for JavaScript and CSS.
    // we use regexes to tell Webpack what files require special treatment, and
    // what patterns to exclude.
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    cacheDirectory: true,
                    plugins: ['transform-decorators-legacy'],
                    presets: ['react', 'es2015', 'stage-2', 'stage-0'],
                },
            },
            {
                test: /\.sass$/,
                loader: ExtractTextPlugin.extract('style', 'css!sass?indentedSyntax&includePaths[]=' + __dirname +  '/node_modules'),
            },
        ],
    },

    // what plugins we'll be using - in this case, just our ExtractTextPlugin.
    // we'll also tell the plugin where the final CSS file should be generated
    // (relative to config.output.path)
    plugins: [
        new ExtractTextPlugin('css/application.css'),
    ],
};

// if running webpack in production mode, minify files with uglifyjs
if (process.env.NODE_ENV === 'production') {
    config.plugins.push(
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.UglifyJsPlugin({ minimize: true })
    );
}
<commit_msg>optimize<commit_after>'use strict';

var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');

// helpers for writing path names
// e.g. join("web/static") => "/full/disk/path/to/hello/web/static"
function join(dest) { return path.resolve(__dirname, dest); }

function web(dest) { return join('web/static/' + dest); }

var config = module.exports = {

    devtool: 'source-map',

    // our application's entry points - for this example we'll use a single each for
    // css and js
    entry: {
        application: [
            web('css/application.sass'),
            web('js/application.js'),
        ],
    },

    // where webpack should output our files
    output: {
        path: join('priv/static'),
        filename: 'js/application.js',
    },

    resolve: {
        extensions: ['', '.js', '.sass'],
        modulesDirectories: ['node_modules'],
    },

    // more information on how our modules are structured, and
    //
    // in this case, we'll define our loaders for JavaScript and CSS.
    // we use regexes to tell Webpack what files require special treatment, and
    // what patterns to exclude.
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    cacheDirectory: true,
                    plugins: ['transform-decorators-legacy'],
                    presets: ['react', 'es2015', 'stage-2', 'stage-0'],
                },
            },
            {
                test: /\.sass$/,
                loader: ExtractTextPlugin.extract('style', 'css!sass?indentedSyntax&includePaths[]=' + __dirname +  '/node_modules'),
            },
        ],
    },

    // what plugins we'll be using - in this case, just our ExtractTextPlugin.
    // we'll also tell the plugin where the final CSS file should be generated
    // (relative to config.output.path)
    plugins: [
        new ExtractTextPlugin('css/application.css'),
    ],
};

// if running webpack in production mode, minify files with uglifyjs
if (process.env.NODE_ENV === 'production') {
    config.plugins.push(
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.UglifyJsPlugin({ minimize: true }),
        new webpack.DefinePlugin({
          'process.env': {
            'NODE_ENV': JSON.stringify('production')
          }
        })
    );
}
<|endoftext|>


<commit_before>module.exports = {
  entry: './client/src/index.jsx',
  output: {
    path: './client/dist',
    filename: 'index.bundle.js',
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      query: {
        presets: ['react', 'es2015']
      }
    }]
  },
  devtool: 'source-map'
};<commit_msg>Add hot module loading plugin for webpack<commit_after>var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: [
    'webpack-hot-middleware/client',
    './client/src/index.jsx'
  ],
  output: {
    path: path.join(__dirname, '/client/dist'),
    filename: 'index.bundle.js',
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      query: {
        presets: ['react', 'es2015']
      }
    }]
  },
  devtool: 'source-map'
};<|endoftext|>


<commit_before>const webpack = require('webpack');
const ExtractTextPlugin = require ('extract-text-webpack-plugin');
const rimraf = require('rimraf');
const path = require('path');

const plugins = [
    {
        apply: compiler => {
            rimraf.sync(compiler.options.output.path);
        },
    },

    new webpack.NoEmitOnErrorsPlugin(),

    new webpack.DefinePlugin({
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
    }),
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        Selectize: 'selectize',
        leaflet: 'leaflet'
    }),
    new ExtractTextPlugin("bundle.css")
];

if(process.env.NODE_ENV === 'production') {
    plugins.push(new webpack.optimize.UglifyJsPlugin({
        compressor: { warnings: false },
    }));
}

module.exports = {
    entry: './public/app/app.module.js',
    output: {
        path: path.join(__dirname, '/public/build'),
        filename: 'bundle.js',
    },
    plugins,
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /(\.test.js$|node_modules)/,
                loader: 'babel-loader',
                query: {
                    presets: ["env"]
                },
            },
            {
                test: /\.html$/,
                loader: 'html-loader',
                exclude: /(node_modules|bower_components)/,
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader"
                })
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract(
                    'css-loader!sass-loader'
                ),
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            },
        ]
    },
};
<commit_msg>Add comments<commit_after>const webpack = require('webpack');
const ExtractTextPlugin = require ('extract-text-webpack-plugin');
const rimraf = require('rimraf');
const path = require('path');

const plugins = [
    {
        apply: compiler => {
            rimraf.sync(compiler.options.output.path);
        },
    },

    new webpack.NoEmitOnErrorsPlugin(),

    new webpack.DefinePlugin({
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
    }),
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        Selectize: 'selectize',
        leaflet: 'leaflet'
    }),
    new ExtractTextPlugin("bundle.css")
];

// if(process.env.NODE_ENV === 'production') {
//     plugins.push(new webpack.optimize.UglifyJsPlugin({
//         compressor: { warnings: false },
//     }));
// }

module.exports = {
    entry: './public/app/app.module.js',
    output: {
        path: path.join(__dirname, '/public/build'),
        filename: 'bundle.js',
    },
    plugins,
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /(\.test.js$|node_modules)/,
                loader: 'babel-loader',
                query: {
                    presets: ["env"]
                },
            },
            {
                test: /\.html$/,
                loader: 'html-loader',
                exclude: /(node_modules|bower_components)/,
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader"
                })
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract(
                    'css-loader!sass-loader'
                ),
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            },
        ]
    },
};
<|endoftext|>


<commit_before>/*
* acceptVerbsAttribute
* author: ruleechen
* contact: rulee@live.cn
* create date: 2014.7.12
*/

'use strict';

var utils = require('zoo-utils');

var acceptVerbsAttribute = module.exports = function(methods) {
	this.methodNames = methods; // GET,POST,PUT,DELETE,HEAD,PATCH,OPTIONS,etc...
	if (!utils.isString(this.methodNames)) {
		throw new Error('The methodNames of actionNameAttribute is invalid');
	}
};

acceptVerbsAttribute.prototype = {

    methodNames: null,

    constructor: acceptVerbsAttribute,

    isValidActionRequest: function(httpContext) {
        var methodName = httpContext.zoo.request.method;
        return this.methodNames.toUpperCase().indexOf(methodName) > -1;
    }
};
<commit_msg>update<commit_after>/*
* acceptVerbsAttribute
* author: ruleechen
* contact: rulee@live.cn
* create date: 2014.7.12
*/

'use strict';

var utils = require('zoo-utils');

var acceptVerbsAttribute = module.exports = function(methods) {
	this.methodNames = methods; // GET,POST,PUT,DELETE,HEAD,PATCH,OPTIONS,etc...
	if (!utils.isString(this.methodNames) || this.methodNames === '') {
		throw new Error('The methodNames of actionNameAttribute is invalid');
	}
};

acceptVerbsAttribute.prototype = {

    methodNames: null,

    constructor: acceptVerbsAttribute,

    isValidActionRequest: function(httpContext) {
        var methodName = httpContext.zoo.request.method;
        return this.methodNames.toUpperCase().indexOf(methodName) > -1;
    }
};
<|endoftext|>


<commit_before><commit_msg>create webpack config file<commit_after>var webpack = require('webpack');

module.exports = {
}
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: './renderer/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/',
  },
  target: 'electron',
	node: {
		__dirname: false,
		__filename: false
	},
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      }, {
        test: /\.(css|scss|sass)$/,
        loaders: ['style', 'css', 'sass'],
      }, {
        test: /\.(eot|woff)$/,
        loader: 'file-loader',
      },
    ],
  },
  devServer: {
    port: 8081
  }
}
<commit_msg>speficy in webpack wether to target electron-main vs electron-renderer<commit_after>const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: './renderer/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/',
  },
  // Compile for Electron for main process.
  target: 'electron-main',
  // configure whether to polyfill or mock certain Node.js globals
	node: {
		__dirname: false,
		__filename: false
	},
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      }, {
        test: /\.(css|scss|sass)$/,
        loaders: ['style', 'css', 'sass'],
      }, {
        test: /\.(eot|woff)$/,
        loader: 'file-loader',
      },
    ],
  },
  devServer: {
    port: 8081
  }
}
<|endoftext|>


<commit_before>/* global __dirname */

const child_process = require('child_process'); // eslint-disable-line camelcase
const process = require('process');
const webpack = require('webpack');

const minimize
    = process.argv.indexOf('-p') !== -1
        || process.argv.indexOf('--optimize-minimize') !== -1;
const plugins = [
    new webpack.LoaderOptionsPlugin({
        debug: !minimize,
        minimize
    })
];

if (minimize) {
    // While webpack will automatically insert UglifyJsPlugin when minimize is
    // true, the defaults of UglifyJsPlugin in webpack 1 and webpack 2 are
    // different. Explicitly state what we want even if we want defaults in
    // order to prepare for webpack 2.
    plugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: {
            // It is nice to see warnings from UglifyJsPlugin that something is
            // unused and, consequently, is removed. The default is false in
            // webpack 2.
            warnings: true
        },
        extractComments: true,

        // Use the source map to map error message locations to modules. The
        // default is false in webpack 2.
        sourceMap: true
    }));
}

module.exports = {
    devtool: 'source-map',
    entry: {
        'lib-jitsi-meet': './index.js'
    },
    module: {
        rules: [ {
            // Version this build of the lib-jitsi-meet library.

            loader: 'string-replace-loader',
            options: {
                flags: 'g',
                replace:
                    child_process.execSync( // eslint-disable-line camelcase
                            `${__dirname}/get-version.sh`)

                        // The type of the return value of
                        // child_process.execSync is either Buffer or String.
                        .toString()

                            // Shells may automatically append CR and/or LF
                            // characters to the output.
                            .trim(),
                search: '{#COMMIT_HASH#}'
            },
            test: `${__dirname}/JitsiMeetJS.js`
        }, {
            // Transpile ES2015 (aka ES6) to ES5.

            exclude: [
                `${__dirname}/modules/RTC/adapter.screenshare.js`,
                `${__dirname}/node_modules/`
            ],
            loader: 'babel-loader',
            options: {
                presets: [
                    [
                        'es2015',

                        // Tell babel to avoid compiling imports into CommonJS
                        // so that webpack may do tree shaking.
                        { modules: false }
                    ],
                    'stage-1'
                ]
            },
            test: /\.js$/
        } ]
    },
    node: {
        // Allow the use of the real filename of the module being executed. By
        // default Webpack does not leak path-related information and provides a
        // value that is a mock (/index.js).
        __filename: true
    },
    output: {
        filename: `[name]${minimize ? '.min' : ''}.js`,
        library: 'JitsiMeetJS',
        libraryTarget: 'umd',
        sourceMapFilename: `[name].${minimize ? 'min' : 'js'}.map`
    },
    plugins
};
<commit_msg>fix path on windows<commit_after>/* global __dirname */

const child_process = require('child_process'); // eslint-disable-line camelcase
const path = require('path');
const process = require('process');
const webpack = require('webpack');

const minimize
    = process.argv.indexOf('-p') !== -1
        || process.argv.indexOf('--optimize-minimize') !== -1;
const plugins = [
    new webpack.LoaderOptionsPlugin({
        debug: !minimize,
        minimize
    })
];

if (minimize) {
    // While webpack will automatically insert UglifyJsPlugin when minimize is
    // true, the defaults of UglifyJsPlugin in webpack 1 and webpack 2 are
    // different. Explicitly state what we want even if we want defaults in
    // order to prepare for webpack 2.
    plugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: {
            // It is nice to see warnings from UglifyJsPlugin that something is
            // unused and, consequently, is removed. The default is false in
            // webpack 2.
            warnings: true
        },
        extractComments: true,

        // Use the source map to map error message locations to modules. The
        // default is false in webpack 2.
        sourceMap: true
    }));
}

module.exports = {
    devtool: 'source-map',
    entry: {
        'lib-jitsi-meet': './index.js'
    },
    module: {
        rules: [ {
            // Version this build of the lib-jitsi-meet library.

            loader: 'string-replace-loader',
            options: {
                flags: 'g',
                replace:
                    child_process.execSync( // eslint-disable-line camelcase
                            `${__dirname}/get-version.sh`)

                        // The type of the return value of
                        // child_process.execSync is either Buffer or String.
                        .toString()

                            // Shells may automatically append CR and/or LF
                            // characters to the output.
                            .trim(),
                search: '{#COMMIT_HASH#}'
            },
            test: `${__dirname}/JitsiMeetJS.js`
        }, {
            // Transpile ES2015 (aka ES6) to ES5.

            exclude: [
                path.resolve(__dirname, 'modules/RTC/adapter.screenshare.js'),
                path.resolve(__dirname, 'node_modules')
            ],
            loader: 'babel-loader',
            options: {
                presets: [
                    [
                        'es2015',

                        // Tell babel to avoid compiling imports into CommonJS
                        // so that webpack may do tree shaking.
                        { modules: false }
                    ],
                    'stage-1'
                ]
            },
            test: /\.js$/
        } ]
    },
    node: {
        // Allow the use of the real filename of the module being executed. By
        // default Webpack does not leak path-related information and provides a
        // value that is a mock (/index.js).
        __filename: true
    },
    output: {
        filename: `[name]${minimize ? '.min' : ''}.js`,
        library: 'JitsiMeetJS',
        libraryTarget: 'umd',
        sourceMapFilename: `[name].${minimize ? 'min' : 'js'}.map`
    },
    plugins
};
<|endoftext|>


<commit_before>var webpack = require("webpack");
var PROD = JSON.parse(process.env.PROD_DEV || "0");
var path = require('path');
var plugins = [
   new webpack.optimize.DedupePlugin(),
   new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })
];

if(PROD) {
    plugins.push(
      new webpack.optimize.UglifyJsPlugin({
        minimize: true,
        compressor: {
          screw_ie8: true,
          warnings: false
        }
      })
    );
}

module.exports = {
    context: path.join(__dirname, "/src"),
    entry: path.join(__dirname, "/src/Inferno"),
    cache: true,
    debug: PROD ? false: true,
    devtool: 'source-map',
    output: {
        path: path.join(__dirname, "/dist"),
        filename: PROD ? "inferno.min.js" : "inferno.js",
        libraryTarget: "var",
        library: "Inferno",
        publicPath: 'http://localhost:8080/'
    },
    devServer: {
        contentBase: path.join(__dirname, "/examples"),
        noInfo: true,
        hot: true,
        inline: true
    },
    module: {
      loaders: [
        {
          test: /.*\/src\/.*\.js$/,
          exclude: /.spec.js/,
          loaders: ['babel-loader'],
		  query: {
			  optional: ['runtime']
		  }
        }
      ]
    },
    plugins: plugins
};
<commit_msg>reverted config change, it breaks<commit_after>var webpack = require("webpack");
var PROD = JSON.parse(process.env.PROD_DEV || "0");
var path = require('path');
var plugins = [
   new webpack.optimize.DedupePlugin(),
   new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })
];

if(PROD) {
    plugins.push(
      new webpack.optimize.UglifyJsPlugin({
        minimize: true,
        compressor: {
          screw_ie8: true,
          warnings: false
        }
      })
    );
}

module.exports = {
    context: path.join(__dirname, "/src"),
    entry: path.join(__dirname, "/src/Inferno"),
    cache: true,
    debug: PROD ? false: true,
    devtool: 'source-map',
    output: {
        path: path.join(__dirname, "/dist"),
        filename: PROD ? "inferno.min.js" : "inferno.js",
        libraryTarget: "var",
        library: "Inferno",
        publicPath: 'http://localhost:8080/'
    },
    devServer: {
        contentBase: path.join(__dirname, "/examples"),
        noInfo: true,
        hot: true,
        inline: true
    },
    module: {
      loaders: [
        {
          test: /.*\/src\/.*\.js$/,
          exclude: /.spec.js/,
          loader: 'babel',
		  query: {
			  optional: ['runtime']
		  }
        }
      ]
    },
    plugins: plugins
};
<|endoftext|>