<commit_before>//import 'babel-polyfill';

import 'core-js/fn/object/assign';
import 'core-js/fn/promise';
import 'core-js/fn/string/includes';

import {makeNetBankingPayment} from './apis/net-banking';
import {getPaymentDetails, getPaymentDetailsForMCP} from './apis/payment-details';
import  {makeBlazeCardPayment, getmerchantCardSchemes, makeMotoCardPayment} from './apis/cards';
import {validateExpiryDate, validateScheme, validateCreditCard} from './validation/custom-validations';
import {init, handlersMap, setConfig, getConfig} from './config';
import {makeMCPCardPayment, getCardCurrencyInfo} from './apis/mcp';
import * as tests from './tests/simple-tests';
import {schemeFromNumber} from './utils';

init(); //initializes custom validators

window.citrus = window.citrus || {};

Object.assign(window.citrus, {
    setConfig,
    getConfig,
    validators: {
        validateExpiryDate,
        validateScheme,
        validateCreditCard
    },
    utils: {
        schemeFromNumber
    },
    registerHandlers: (key, handler) => {
        handlersMap[key] = handler;
    },
    geteways: {
        getPaymentDetails
    },
    netbanking: {
        makeNetBankingPayment
    },
    cards: {
        getmerchantCardSchemes,
        makeBlazeCardPayment,
        makeMCPCardPayment,
        getCardCurrencyInfo,
        getPaymentDetailsForMCP,
        getPaymentDetails
    }
});
//some dummy comment dfdfs
//tests.test1();<commit_msg>Moto card done.<commit_after>//import 'babel-polyfill';

import 'core-js/fn/object/assign';
import 'core-js/fn/promise';
import 'core-js/fn/string/includes';

import {makeNetBankingPayment} from './apis/net-banking';
import {getPaymentDetails, getPaymentDetailsForMCP} from './apis/payment-details';
import  {makeBlazeCardPayment, getmerchantCardSchemes, makeMotoCardPayment} from './apis/cards';
import {validateExpiryDate, validateScheme, validateCreditCard} from './validation/custom-validations';
import {init, handlersMap, setConfig, getConfig} from './config';
import {makeMCPCardPayment, getCardCurrencyInfo} from './apis/mcp';
import * as tests from './tests/simple-tests';
import {schemeFromNumber} from './utils';

init(); //initializes custom validators

window.citrus = window.citrus || {};

Object.assign(window.citrus, {
    setConfig,
    getConfig,
    validators: {
        validateExpiryDate,
        validateScheme,
        validateCreditCard
    },
    utils: {
        schemeFromNumber
    },
    registerHandlers: (key, handler) => {
        handlersMap[key] = handler;
    },
    geteways: {
        getPaymentDetails
    },
    netbanking: {
        makeNetBankingPayment
    },
    cards: {
        getmerchantCardSchemes,
        makeMotoCardPayment,
        makeBlazeCardPayment,
        makeMCPCardPayment,
        getCardCurrencyInfo,
        getPaymentDetailsForMCP,
        getPaymentDetails
    }
});
//some dummy comment dfdfs
//tests.test1();<|endoftext|>


<commit_before>'use strict';

const topLogPrefix = 'larvitadmingui: index.js: ';
const DbMigration = require('larvitdbmigration');
const Session = require('larvitsession');
const LUtils = require('larvitutils');
const Lbwww = require('larvitbase-www');
const Events = require('events');
const Acl = require(__dirname + '/models/acl.js');
const Lfs = require('larvitfs');
const lfs = new Lfs();
const _ = require('lodash');

// Extend lodash
_.defaultsDeep = require('lodash.defaultsdeep');
_.urlUtil = require(__dirname + '/models/utils.js').urlUtil;
_.trim = require('lodash.trim');

function App(options) {
	const logPrefix = topLogPrefix + 'App() - ';
	const that = this;

	that.options = options || {};
	that.options.baseOptions = that.options.baseOptions || {};
	that.options.routerOptions = that.options.routerOptions || {};
	that.options.baseOptions.httpOptions = that.options.baseOptions.httpOptions || {};
	that.emitter = new Events();
	that.dbReady = false;

	if (!that.options.log) {
		const lUtils = new LUtils();

		that.options.log = new lUtils.Log();
	}
	that.log = that.options.log;

	if (!that.options.db) {
		const err = new Error('Required option "db" is missing');
		that.log.error(logPrefix + err.message);
		throw err;
	}
	that.db = that.options.db;

	if (!that.options.userLib) {
		const err = new Error('Required option "userLib" is missing');
		that.log.error(logPrefix + err.message);
		throw err;
	}
	that.userLib = that.options.userLib;

	if (!that.options.session) {
		that.options.session = new Session({
			db: that.db,
			log: that.log
		});
	}
	that.session = that.options.session;

	if (that.options.menuStructure) {
		that.menuStructure = that.options.menuStructure;
	} else {
		// Include menu structure config
		// Do it through stringify/parse to not screw up the original structure
		that.menuStructure = JSON.parse(JSON.stringify(require(lfs.getPathSync('config/menuStructure.json'))));
	}

	if (that.options.routerOptions.routes === undefined) { that.options.routerOptions.routes = []; }

	that.options.routerOptions.routes.push({
		regex: '^/default$',
		controllerPath: 'login.js',
		templatePath: 'login.tmpl'
	});

	that.options.routerOptions.routes.push({
		regex: '\\.css$',
		controllerPath: 'css.js'
	});

	that.acl = new Acl(that.options);
	that.basewww = new Lbwww(that.options);
	that.basewww.options.baseOptions.middleware = [
		require('cookies').express(),
		function (req, res, cb) { that.session.start(req, res, cb); },
		function mwSetNextCallData(req, res, cb) { that.mwSetNextCallData(req, res, cb); },
		function mwParse(req, res, cb) { that.basewww.mwParse(req, res, cb); },
		function mwRoute(req, res, cb) { that.basewww.mwRoute(req, res, cb); },
		function mwSendStatic(req, res, cb) { that.basewww.mwSendStatic(req, res, cb); },
		function setPropertiesOnRequest(req, res, cb) { that.setPropertiesOnRequest(req, res, cb); },
		require(lfs.getPathSync('models/controllerGlobal.js')),
		function checkAndRedirect(req, res, cb) { that.checkAndRedirect(req, res, cb); },
		function mwRunController(req, res, cb) { that.basewww.mwRunController(req, res, cb); },
		function mwRender(req, res, cb) { that.basewww.mwRender(req, res, cb); },
		function mwSendToClient(req, res, cb) { that.basewww.mwSendToClient(req, res, cb); },
		function mwCleanup(req, res, cb) { that.basewww.mwCleanup(req, res, cb); },
		function writeSessionToDb(req, res, cb) { that.session.writeToDb(req, res, cb); }
	];

	if (that.options.middleware) {
		that.basewww.options.baseOptions.middleware.unshift(that.options.middleware[0]);
	}

	that.runDbMigrations();
}

App.prototype.runDbMigrations = function runDbMigrations() {
	const logPrefix = topLogPrefix + 'App.runDbMigrations() - ';
	const options = {};
	const that = this;

	let dbMigration;

	options.dbType = 'mariadb';
	options.dbDriver = that.db;
	options.tableName = 'admingui_db_version';
	options.migrationScriptsPath = __dirname + '/dbmigration';
	options.log = that.log;

	dbMigration = new DbMigration(options);
	that.userLib.dataWriter.ready(function (err) {
		if (err) {
			that.log.error(logPrefix + err.message);
			throw err;
		}

		dbMigration.run(function (err) {
			if (err) {
				that.log.error(logPrefix + err.message);
				throw err;
			}

			that.emitter.emit('dbReady');
			that.dbReady = true;
		});
	});
};

App.prototype.mwSetNextCallData = function mwSetNextCallData(req, res, cb) {
	if (req.session && req.session.data && req.session.data.nextCallData) {
		// TODO(vktr): Probably should do this recursive instead
		for (const key of Object.keys(req.session.data.nextCallData)) {
			for (const subKey of Object.keys(req.session.data.nextCallData[key])) {
				if (!res[key]) {
					res[key] = {};
				}

				res[key][subKey] = req.session.data.nextCallData[key][subKey];
			}
		}

		delete req.session.data.nextCallData;
	}

	cb();
};

App.prototype.setPropertiesOnRequest = function setPropertiesOnRequest(req, res, cb) {
	const that = this;

	// Default admin rights to be false
	// In the bottom this gets set to true if a correct user is logged in
	res.adminRights = false;

	// Make ACL object available for other parts of the system
	req.acl = that.acl;

	req.db = that.db;
	req.userLib = that.userLib;
	req.log = that.log;

	// TODO: Figure out a better way to reset the menu structure between requests.
	// Some controllers modify the menuStructure which is why we need to reset it.
	// Object.assign does not do a deep copy, so we use JSON parse/stringify to
	// create a deep copy.
	req.menuStructure = JSON.parse(JSON.stringify(that.menuStructure));

	return cb();
};

App.prototype.checkAndRedirect = function checkAndRedirect(req, res, cb) {
	const that = this;

	if (req.finished) return cb();

	that.acl.checkAndRedirect(req, res, function (err, userGotAccess) {
		if (err) {
			that.log.error(logPrefix + err.message);

			return cb(err);
		}

		// User got access, proceed with executing the controller
		if (userGotAccess) {
			res.adminRights = true;
		} else {
			// If userGotAccess is false, we should not execute the controller.
			// Instead just run sendToClient directly, circumventing the afterware as well.
			res.end('Access denied');
			req.finished = true;
		}

		cb();
	});
};

App.prototype.ready = function ready(cb) {
	const that = this;

	if (that.dbReady) return cb();
	that.emitter.on('dbReady', cb);
};

App.prototype.start = function start(cb) {
	this.ready(() => {
		this.basewww.start(cb);
	});
};

App.prototype.stop = function stop(cb) {
	this.basewww.stop(cb);
};

exports = module.exports = App;
<commit_msg>Write session to db before sending response to avoid races<commit_after>'use strict';

const topLogPrefix = 'larvitadmingui: index.js: ';
const DbMigration = require('larvitdbmigration');
const Session = require('larvitsession');
const LUtils = require('larvitutils');
const Lbwww = require('larvitbase-www');
const Events = require('events');
const Acl = require(__dirname + '/models/acl.js');
const Lfs = require('larvitfs');
const lfs = new Lfs();
const _ = require('lodash');

// Extend lodash
_.defaultsDeep = require('lodash.defaultsdeep');
_.urlUtil = require(__dirname + '/models/utils.js').urlUtil;
_.trim = require('lodash.trim');

function App(options) {
	const logPrefix = topLogPrefix + 'App() - ';
	const that = this;

	that.options = options || {};
	that.options.baseOptions = that.options.baseOptions || {};
	that.options.routerOptions = that.options.routerOptions || {};
	that.options.baseOptions.httpOptions = that.options.baseOptions.httpOptions || {};
	that.emitter = new Events();
	that.dbReady = false;

	if (!that.options.log) {
		const lUtils = new LUtils();

		that.options.log = new lUtils.Log();
	}
	that.log = that.options.log;

	if (!that.options.db) {
		const err = new Error('Required option "db" is missing');
		that.log.error(logPrefix + err.message);
		throw err;
	}
	that.db = that.options.db;

	if (!that.options.userLib) {
		const err = new Error('Required option "userLib" is missing');
		that.log.error(logPrefix + err.message);
		throw err;
	}
	that.userLib = that.options.userLib;

	if (!that.options.session) {
		that.options.session = new Session({
			db: that.db,
			log: that.log
		});
	}
	that.session = that.options.session;

	if (that.options.menuStructure) {
		that.menuStructure = that.options.menuStructure;
	} else {
		// Include menu structure config
		// Do it through stringify/parse to not screw up the original structure
		that.menuStructure = JSON.parse(JSON.stringify(require(lfs.getPathSync('config/menuStructure.json'))));
	}

	if (that.options.routerOptions.routes === undefined) { that.options.routerOptions.routes = []; }

	that.options.routerOptions.routes.push({
		regex: '^/default$',
		controllerPath: 'login.js',
		templatePath: 'login.tmpl'
	});

	that.options.routerOptions.routes.push({
		regex: '\\.css$',
		controllerPath: 'css.js'
	});

	that.acl = new Acl(that.options);
	that.basewww = new Lbwww(that.options);
	that.basewww.options.baseOptions.middleware = [
		require('cookies').express(),
		function (req, res, cb) { that.session.start(req, res, cb); },
		function mwSetNextCallData(req, res, cb) { that.mwSetNextCallData(req, res, cb); },
		function mwParse(req, res, cb) { that.basewww.mwParse(req, res, cb); },
		function mwRoute(req, res, cb) { that.basewww.mwRoute(req, res, cb); },
		function mwSendStatic(req, res, cb) { that.basewww.mwSendStatic(req, res, cb); },
		function setPropertiesOnRequest(req, res, cb) { that.setPropertiesOnRequest(req, res, cb); },
		require(lfs.getPathSync('models/controllerGlobal.js')),
		function checkAndRedirect(req, res, cb) { that.checkAndRedirect(req, res, cb); },
		function mwRunController(req, res, cb) { that.basewww.mwRunController(req, res, cb); },
		function writeSessionToDb(req, res, cb) { that.session.writeToDb(req, res, cb); },
		function mwRender(req, res, cb) { that.basewww.mwRender(req, res, cb); },
		function mwSendToClient(req, res, cb) { that.basewww.mwSendToClient(req, res, cb); },
		function mwCleanup(req, res, cb) { that.basewww.mwCleanup(req, res, cb); }
	];

	if (that.options.middleware) {
		that.basewww.options.baseOptions.middleware.unshift(that.options.middleware[0]);
	}

	that.runDbMigrations();
}

App.prototype.runDbMigrations = function runDbMigrations() {
	const logPrefix = topLogPrefix + 'App.runDbMigrations() - ';
	const options = {};
	const that = this;

	let dbMigration;

	options.dbType = 'mariadb';
	options.dbDriver = that.db;
	options.tableName = 'admingui_db_version';
	options.migrationScriptsPath = __dirname + '/dbmigration';
	options.log = that.log;

	dbMigration = new DbMigration(options);
	that.userLib.dataWriter.ready(function (err) {
		if (err) {
			that.log.error(logPrefix + err.message);
			throw err;
		}

		dbMigration.run(function (err) {
			if (err) {
				that.log.error(logPrefix + err.message);
				throw err;
			}

			that.emitter.emit('dbReady');
			that.dbReady = true;
		});
	});
};

App.prototype.mwSetNextCallData = function mwSetNextCallData(req, res, cb) {
	if (req.session && req.session.data && req.session.data.nextCallData) {
		// TODO(vktr): Probably should do this recursive instead
		for (const key of Object.keys(req.session.data.nextCallData)) {
			for (const subKey of Object.keys(req.session.data.nextCallData[key])) {
				if (!res[key]) {
					res[key] = {};
				}

				res[key][subKey] = req.session.data.nextCallData[key][subKey];
			}
		}

		delete req.session.data.nextCallData;
	}

	cb();
};

App.prototype.setPropertiesOnRequest = function setPropertiesOnRequest(req, res, cb) {
	const that = this;

	// Default admin rights to be false
	// In the bottom this gets set to true if a correct user is logged in
	res.adminRights = false;

	// Make ACL object available for other parts of the system
	req.acl = that.acl;

	req.db = that.db;
	req.userLib = that.userLib;
	req.log = that.log;

	// TODO: Figure out a better way to reset the menu structure between requests.
	// Some controllers modify the menuStructure which is why we need to reset it.
	// Object.assign does not do a deep copy, so we use JSON parse/stringify to
	// create a deep copy.
	req.menuStructure = JSON.parse(JSON.stringify(that.menuStructure));

	return cb();
};

App.prototype.checkAndRedirect = function checkAndRedirect(req, res, cb) {
	const that = this;

	if (req.finished) return cb();

	that.acl.checkAndRedirect(req, res, function (err, userGotAccess) {
		if (err) {
			that.log.error(logPrefix + err.message);

			return cb(err);
		}

		// User got access, proceed with executing the controller
		if (userGotAccess) {
			res.adminRights = true;
		} else {
			// If userGotAccess is false, we should not execute the controller.
			// Instead just run sendToClient directly, circumventing the afterware as well.
			res.end('Access denied');
			req.finished = true;
		}

		cb();
	});
};

App.prototype.ready = function ready(cb) {
	const that = this;

	if (that.dbReady) return cb();
	that.emitter.on('dbReady', cb);
};

App.prototype.start = function start(cb) {
	this.ready(() => {
		this.basewww.start(cb);
	});
};

App.prototype.stop = function stop(cb) {
	this.basewww.stop(cb);
};

exports = module.exports = App;
<|endoftext|>


<commit_before>'use strict'

module.exports = [
  '1.0.0'
, '1.0.1'
, '1.0.2'
, '1.0.3'
, '1.0.4'
, '1.1.0'
, '1.2.0'
, '1.3.0'
, '1.4.1'
, '1.4.2'
, '1.4.3'
, '1.5.0'
, '1.5.1'
, '1.6.0'
, '1.6.1'
, '1.6.2'
, '1.6.3'
, '1.6.4'
, '1.7.1'
, '1.8.1'
, '1.8.2'
, '1.8.3'
, '1.8.4'
, '2.0.0'
, '2.0.1'
, '2.0.2'
, '2.1.0'
, '2.2.0'
, '2.2.1'
, '2.3.0'
, '2.3.1'
, '2.3.2'
, '2.3.3'
, '2.3.4'
, '2.4.0'
, '2.5.0'
, '3.0.0'
, '3.1.0'
, '3.2.0'
]
<commit_msg>add v3.3.0<commit_after>'use strict'

module.exports = [
  '1.0.0'
, '1.0.1'
, '1.0.2'
, '1.0.3'
, '1.0.4'
, '1.1.0'
, '1.2.0'
, '1.3.0'
, '1.4.1'
, '1.4.2'
, '1.4.3'
, '1.5.0'
, '1.5.1'
, '1.6.0'
, '1.6.1'
, '1.6.2'
, '1.6.3'
, '1.6.4'
, '1.7.1'
, '1.8.1'
, '1.8.2'
, '1.8.3'
, '1.8.4'
, '2.0.0'
, '2.0.1'
, '2.0.2'
, '2.1.0'
, '2.2.0'
, '2.2.1'
, '2.3.0'
, '2.3.1'
, '2.3.2'
, '2.3.3'
, '2.3.4'
, '2.4.0'
, '2.5.0'
, '3.0.0'
, '3.1.0'
, '3.2.0'
, '3.3.0'
]
<|endoftext|>


<commit_before>#!/usr/bin/env node
require('shelljs/global');

// Creates a changelog for the current build and puts it in the root
// Commits the changelog if it updated
// Does not push commit

function parseGitUri(uri) {
  return uri.match(/https:..github.com\/([^./]+)\/([^./]+).*/) ||
    uri.match(/git@github.com:(.*)\/(.*)\.git/);
}

function verifyChangelog() {
  var diff = exec('git diff HEAD CHANGELOG.md').split('\n');
  var changelog = cat('CHANGELOG.md').split('\n');
  if (changelog[changelog.length - 1] === '') changelog.pop();
  var isOneLine = (changelog.length === 1);
  var deletions = diff.filter(/^-/.test).length;
  var containsError = false;
  diff.forEach(function (line) {
    if (line.indexOf('Make a POST first') >= 0) containsError = true;
  });
  if (isOneLine) {
    revertChanges();
    console.error('Changelog diff should be more than 1 line long');
    process.exit(3);
  }
  if (deletions > 10) {
    revertChanges();
    console.error('Too many deletions (-' + deletions + '), verify that the changes to CHANGELOG.md are correct');
    process.exit(4);
  }
  if (containsError) {
    revertChanges();
    console.error('Changelog contains an error message');
    process.exit(5);
  }
}

function revertChanges() {
  exec('git checkout -- .');
}

function run() {
  echo('...generating changelog (be patient)');
  config.silent = true;
  var urls = exec('git remote show -n origin')
      .grep('Push');
  if (!urls) {
    console.error('Unable to find any URLs you can push to');
    process.exit(1);
  }
  var repoInfo = parseGitUri(urls);
  if (!repoInfo) {
    console.error('Unable to parse your git URL');
    process.exit(2);
  }
  var url = 'github-changelog-api.herokuapp.com/' + repoInfo[1] + '/' + repoInfo[2];
  exec('curl -X POST -s "' + url + '"');
  var newLog;
  do {
    exec('sleep 1');
    newLog = exec('curl "' + url + '"');
  } while (newLog.match(/^Working, try again.*/));
  // Now that the contents are valid, we can write this out to disk
  newLog.to('CHANGELOG.md');

  var changelog_was_updated = false;
  exec('git ls-files --exclude-standard --modified --others').split('\n').forEach(function (file) {
    if (file === 'CHANGELOG.md') changelog_was_updated = true;
  });

  if (changelog_was_updated) {
    echo('...verifying changelog');
    verifyChangelog();
    echo('...committing updated changelog');
    var current_user = exec('git config user.name').trimRight();
    config.silent = false;
    exec('git add CHANGELOG.md');
    exec('git commit -m "docs(changelog): updated by ' + current_user + ' [ci skip]"');
    echo('Done.  You can now \'git push\' the updated changelog.');
  } else {
    echo('CHANGELOG.md already up-to-date.');
  }
}

run();
<commit_msg>Use assertions, try-catch for control flow<commit_after>#!/usr/bin/env node
var assert = require('assert');
require('shelljs/global');

// Creates a changelog for the current build and puts it in the root
// Commits the changelog if it updated
// Does not push commit

function parseGitUri(uri) {
  return uri.match(/https:..github.com\/([^./]+)\/([^./]+).*/) ||
    uri.match(/git@github.com:(.*)\/(.*)\.git/);
}

function verifyChangelog() {
  var diff = exec('git diff HEAD CHANGELOG.md').split('\n');
  var changelog = cat('CHANGELOG.md').split('\n');
  if (changelog[changelog.length - 1] === '') changelog.pop();
  var isOneLine = (changelog.length === 1);
  var deletions = diff.filter(/^-/.test).length;
  var containsError = false;
  diff.forEach(function (line) {
    if (line.indexOf('Make a POST first') >= 0) containsError = true;
  });
  assert(
    changelog.length > 1,
    'Changelog diff should be more than 1 line long'
  );
  assert(
    deletions < 10,
    'Too many deletions (-' + deletions + '), verify that the changes to CHANGELOG.md are correct'
  );
  assert(
    !containsError,
    'Changelog contains an error message'
  );
}

function revertChanges() {
  exec('git checkout -- .');
}

function run() {
  echo('...generating changelog (be patient)');
  config.silent = true;
  var urls = exec('git remote show -n origin')
      .grep('Push');
  if (!urls) {
    console.error('Unable to find any URLs you can push to');
    process.exit(1);
  }
  var repoInfo = parseGitUri(urls);
  if (!repoInfo) {
    console.error('Unable to parse your git URL');
    process.exit(2);
  }
  var url = 'github-changelog-api.herokuapp.com/' + repoInfo[1] + '/' + repoInfo[2];
  exec('curl -X POST -s "' + url + '"');
  var newLog;
  do {
    exec('sleep 1');
    newLog = exec('curl "' + url + '"');
  } while (newLog.match(/^Working, try again.*/));
  // Now that the contents are valid, we can write this out to disk
  newLog.to('CHANGELOG.md');

  var changelog_was_updated = false;
  exec('git ls-files --exclude-standard --modified --others').split('\n').forEach(function (file) {
    if (file === 'CHANGELOG.md') changelog_was_updated = true;
  });

  if (changelog_was_updated) {
    echo('...verifying changelog');
    try {
      verifyChangelog();
    } catch (err) {
      revertChanges();
      console.error(err.message);
      process.exit(1);
    }
    echo('...committing updated changelog');
    var current_user = exec('git config user.name').trimRight();
    config.silent = false;
    exec('git add CHANGELOG.md');
    exec('git commit -m "docs(changelog): updated by ' + current_user + ' [ci skip]"');
    echo('Done.  You can now \'git push\' the updated changelog.');
  } else {
    echo('CHANGELOG.md already up-to-date.');
  }
}

run();
<|endoftext|>


<commit_before>/**
 * update-copyright <https://github.com/jonschlinkert/update-copyright>
 *
 * Copyright (c) 2014, Jon Schlinkert.
 * Licensed under the MIT license.
 */

var author = require('./lib/author');
var defaults = require('./lib/defaults');
var template = require('./lib/template');
var utils = require('./lib/utils');

module.exports = function(str, options) {
  var context = {};

  if (typeof str === 'string') {
    var match = utils.parseCopyright(str);
    if (match.length) {
      context = match[0];
    }
  } else {
    options = str;
    str = '';
  }
  options = options || {};
  return updateCopyright(str, context, options);
}

function updateYear(context) {
  return context.dateRange
    ? utils.updateYear(context.dateRange, String(utils.year()))
    : utils.year();
}

function updateCopyright(str, context, options) {
  var pkg = utils.loadPkg.sync(process.cwd());
  var opts = utils.merge({template: template}, options);
  var engine = new utils.Engine(opts);

  // create the template context from defaults, package.json,
  // context from parsing the original statement, and options.
  var ctx = utils.merge({}, defaults, pkg, context, opts);
  ctx.authors = ctx.author = author(ctx, pkg, options);
  ctx.years = ctx.year = updateYear(ctx);

  var statement = ctx.statement;

  // if no original statement was found, create one with the template
  if (typeof statement === 'undefined') {
    return engine.render(opts.template, ctx);
  }

  // necessary since the copyright regex doesn't match
  // the trailing dot. If it does later this is future-proof
  if (statement[statement.length - 1] !== '.') {
    var ch = statement + '.';
    if (str.indexOf(ch) !== -1) {
      statement = ch;
    }
  }

  // create the new copyright statement
  var newStatement = engine.render(opts.template, ctx);

  // if the original string is no more than a copyright statement
  // just return the new one
  if (statement.trim() === str.trim()) {
    return newStatement;
  }

  return str.replace(statement, newStatement);
}

module.exports.parse = utils.parseCopyright;
<commit_msg>code comments<commit_after>/**
 * update-copyright <https://github.com/jonschlinkert/update-copyright>
 *
 * Copyright (c) 2014, Jon Schlinkert.
 * Licensed under the MIT license.
 */

var author = require('./lib/author');
var defaults = require('./lib/defaults');
var template = require('./lib/template');
var utils = require('./lib/utils');

module.exports = function(str, options) {
  var context = {};

  if (typeof str === 'string') {
    var match = utils.parseCopyright(str);
    if (match.length) {
      context = match[0];
    }
  } else {
    options = str;
    str = '';
  }
  options = options || {};
  return updateCopyright(str, context, options);
};

/**
 * Parse the copyright statement and update the year or year range.
 *
 * @param {Object} `context`
 * @return {String}
 */

function updateYear(context) {
  return context.dateRange
    ? utils.updateYear(context.dateRange, String(utils.year()))
    : utils.year();
}

/**
 * Update an existing copyright statement, or create a new one
 * if one isn't passed.
 *
 * @param {String} `str` String with copyright statement
 * @param {Object} `context` Context to use for rendering the copyright template
 * @param {Object} `options`
 * @return {String}
 */

function updateCopyright(str, context, options) {
  var pkg = utils.loadPkg.sync(process.cwd());
  var opts = utils.merge({template: template}, options);
  var engine = new utils.Engine(opts);

  // create the template context from defaults, package.json,
  // context from parsing the original statement, and options.
  var ctx = utils.merge({}, defaults, pkg, context, opts);
  ctx.authors = ctx.author = author(ctx, pkg, options);
  ctx.years = ctx.year = updateYear(ctx);

  var statement = ctx.statement;

  // if no original statement was found, create one with the template
  if (typeof statement === 'undefined') {
    return engine.render(opts.template, ctx);
  }

  // necessary since the copyright regex doesn't match
  // the trailing dot. If it does later this is future-proof
  if (statement[statement.length - 1] !== '.') {
    var ch = statement + '.';
    if (str.indexOf(ch) !== -1) {
      statement = ch;
    }
  }

  // create the new copyright statement
  var newStatement = engine.render(opts.template, ctx);

  // if the original string is no more than a copyright statement
  // just return the new one
  if (statement.trim() === str.trim()) {
    return newStatement;
  }

  return str.replace(statement, newStatement);
}

/**
 * Expose `parse`
 */

module.exports.parse = utils.parseCopyright;
<|endoftext|>


<commit_before>require('./bin-debug/interface.js');

module.exports = rtPlayer;
<commit_msg>actually export the module<commit_after>module.exports = require('./bin-debug/interface.js');
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var Onus = require('onus');
var React = require('react');

var componentCache = {};

module.exports = function(conf) {
  var render = conf.render;
  return Onus({
    render: function(DOM, $get, props, state, _yield, params, query, forms, t) {
      var contents = render(format, $get, props, state, _yield, params, query, forms, t);
      return DOM('style', null, '\n' + Array.isArray(contents) ? contents.join('') : contents);
    }
  });
}

function format(selectors, props) {
  return selectors.join('\n') + ' {\n' + formatProps(props) + '\n}\n';
}

function formatProps(props) {
  var parts = [];
  for (var k in props) {
    parts.push('  ' + k + ':' + props[k] + ';');
  }
  return parts.join('\n');
}
<commit_msg>remove key prop<commit_after>/**
 * Module dependencies
 */

var Onus = require('onus');
var React = require('react');

var componentCache = {};

module.exports = function(conf) {
  var render = conf.render;
  return Onus({
    render: function(DOM, $get, props, state, _yield, params, query, forms, t) {
      var contents = render(format, $get, props, state, _yield, params, query, forms, t);
      return DOM('style', null, '\n' + Array.isArray(contents) ? contents.join('') : contents);
    }
  });
}

function format(selectors, props) {
  return selectors.join('\n') + ' {\n' + formatProps(props) + '\n}\n';
}

function formatProps(props) {
  var parts = [];
  for (var k in props) {
    if (k === 'key') continue;
    parts.push('  ' + k + ':' + props[k] + ';');
  }
  return parts.join('\n');
}
<|endoftext|>


<commit_before>/**
 * Simple loader
 *
 * @param  {string} source
 * @return {string}
 */
module.exports = function (source) {
  return '/* inlined comment */\n' + source;
};
<commit_msg>small helper<commit_after>/**
 * Simple loader
 *
 * @param  {string} source
 * @return {string}
 */
module.exports = function (source) {
  // In case of async transformations
  // var callback = this.async();

  // Flag itself cacheable if possible
  // this.cacheable();
  // Mark dependencies if a loader uses external resources
  // this.addDependency(externalPath);
  return '/* inlined comment */\n' + source;
};
<|endoftext|>


<commit_before>var chalk = require('chalk');
var gutil = require('gulp-util');
var prettyBytes = require('pretty-bytes');
var moment = require('moment');
var through = require('through2');
var gzipSize = require('gzip-size');

var displaySize = function (contents, gzip) {
    var size, result;
    if (gzip) {
        size = gzipSize(contents);
    } else {
        size = contents.length;
    }

    result = prettyBytes(size);
    if (gzip) {
        result = result + ', gzipped';
    }
    return result;
};

module.exports = function (options) {
    options = options || {
        since: false,
        title: null,
        gzip: false
    };

    var title = options.title ? options.title + ' ' : '';
    var since = options.since;
    var gzip = options.gzip;

    return through.obj(function (file, enc, cb) {
        var now, duration, nowFormatted;

        if (file.isNull()) {
            this.push(file);
            return cb();
        }

        if (file.isStream()) {
            this.emit(
                'error',
                new gutil.PluginError('gulp-file-activity', 'Streaming not supported')
            );
        }

        if (since !== undefined && typeof since.getTime === 'function') {
            now = new Date();
            duration = now.getTime() - started.getTime();
            nowFormatted = moment(now).format('YYYY-MM-DD HH:mm:ss.SSS');
            gutil.log(
                '[' + chalk.grey(nowFormatted) + '] ' + title + chalk.blue(file.relative) +
                ' (' + displaySize(file.contents, gzip) + ') in ' +
                chalk.green('' + duration + ' ms')
            );
        } else {
            gutil.log(
                '[' + chalk.grey(nowFormatted) + '] ' + title + chalk.blue(file.relative) +
                ' (' + displaySize(file.contents, gzip) + ')'
            );
        }
        cb();
    });
};
<commit_msg>Some small fixes<commit_after>var chalk = require('chalk');
var gutil = require('gulp-util');
var prettyBytes = require('pretty-bytes');
var moment = require('moment');
var through = require('through2');
var gzipSize = require('gzip-size');

var displaySize = function (contents, gzip) {
    var size, result;
    if (gzip) {
        size = gzipSize.sync(contents);
    } else {
        size = contents.length;
    }

    result = prettyBytes(size);
    if (gzip) {
        result = result + ', gzipped';
    }
    return result;
};

module.exports = function (options) {
    options = options || {
        since: false,
        title: null,
        gzip: false
    };

    var title = options.title ? options.title + ' ' : '';
    var since = options.since;
    var gzip = options.gzip;

    return through.obj(function (file, enc, cb) {
        var now, duration, nowFormatted;

        if (file.isNull()) {
            this.push(file);
            return cb();
        }

        if (file.isStream()) {
            this.emit(
                'error',
                new gutil.PluginError('gulp-file-activity', 'Streaming not supported')
            );
        }

        now = new Date();
        nowFormatted = moment(now).format('YYYY-MM-DD HH:mm:ss.SSS');
        if (since !== undefined && typeof since.getTime === 'function') {
            duration = now.getTime() - since.getTime();
            gutil.log(
                '[' + chalk.grey(nowFormatted) + '] ' + title + chalk.blue(file.relative) +
                ' (' + displaySize(file.contents, gzip) + ') in ' +
                chalk.green('' + duration + ' ms')
            );
        } else {
            gutil.log(
                '[' + chalk.grey(nowFormatted) + '] ' + title + chalk.blue(file.relative) +
                ' (' + displaySize(file.contents, gzip) + ')'
            );
        }
        cb();
    });
};
<|endoftext|>


<commit_before>// this entire module is depressing. i should have spent my time learning
// how to patch v8 so that these options would just be available on the
// process object.

const os = require('os');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const execFile = require('child_process').execFile;
const configPath = require('./config-path.js')(process.platform);
const env = process.env;
const user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME || '';
const exclusions = ['--help'];

const configfile = '.v8flags.'+process.versions.v8+'.'+crypto.createHash('md5').update(user).digest('hex')+'.json';

const failureMessage = [
  'Unable to cache a config file for v8flags to your home directory',
  'or a temporary folder. To fix this problem, please correct your',
  'environment by setting HOME=/path/to/home or TEMP=/path/to/temp.',
  'NOTE: the user running this must be able to access provided path.',
  'If all else fails, please open an issue here:',
  'http://github.com/tkellen/js-v8flags'
].join('\n');

function fail (err) {
  err.message += '\n\n' + failureMessage;
  return err;
}

function openConfig (cb) {
  fs.mkdir(configPath, function () {
    tryOpenConfig(path.join(configPath, configfile), function (err, fd) {
      if (err) return tryOpenConfig(path.join(os.tmpdir(), configfile), cb);
      return cb(null, fd);
    });
  })
}

function tryOpenConfig (configpath, cb) {
  try {
    // if the config file is valid, it should be json and therefore
    // node should be able to require it directly. if this doesn't
    // throw, we're done!
    var content = require(configpath);
    process.nextTick(function () {
      cb(null, content);
    });
  } catch (e) {
    // if requiring the config file failed, maybe it doesn't exist, or
    // perhaps it has become corrupted. instead of calling back with the
    // content of the file, call back with a file descriptor that we can
    // write the cached data to
    fs.open(configpath, 'w+', function (err, fd) {
      if (err) {
        return cb(err);
      }
      return cb(null, fd);
    });
  }
}

// i can't wait for the day this whole module is obsolete because these
// options are available on the process object. this executes node with
// `--v8-options` and parses the result, returning an array of command
// line flags.
function getFlags (cb) {
  execFile(process.execPath, ['--v8-options'], function (execErr, result) {
    if (execErr) {
      return cb(execErr);
    }
    var flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
      return match.substring(2);
    }).filter(function (name) {
      return exclusions.indexOf(name) === -1;
    });
    return cb(null, flags);
  });
}

// write some json to a file descriptor. if this fails, call back
// with both the error and the data that was meant to be written.
function writeConfig (fd, flags, cb) {
  var buf = new Buffer(JSON.stringify(flags));
  return fs.write(fd, buf, 0, buf.length, 0 , function (writeErr) {
    fs.close(fd, function (closeErr) {
      var err = writeErr || closeErr;
      if (err) {
        return cb(fail(err), flags);
      }
      return cb(null, flags);
    });
  });
}

module.exports = function (cb) {
  // bail early if this is not node
  var isElectron = process.versions && process.versions.electron;
  if (isElectron) {
    return process.nextTick(function () {
      cb(null, []);
    });
  }

  // attempt to open/read cache file
  openConfig(function (openErr, result) {
    if (!openErr && typeof result !== 'number') {
      return cb(null, result);
    }
    // if the result is not an array, we need to go fetch
    // the flags by invoking node with `--v8-options`
    getFlags(function (flagsErr, flags) {
      // if there was an error fetching the flags, bail immediately
      if (flagsErr) {
        return cb(flagsErr);
      }
      // if there was a problem opening the config file for writing
      // throw an error but include the flags anyway so that users
      // can continue to execute (at the expense of having to fetch
      // flags on every run until they fix the underyling problem).
      if (openErr) {
        return cb(fail(openErr), flags);
      }
      // write the config file to disk so subsequent runs can read
      // flags out of a cache file.
      return writeConfig(result, flags, cb);
    });
  });
};

module.exports.configfile = configfile;
module.exports.configPath = configPath;
<commit_msg>Update: Avoid using deprecated Buffer API on newer node<commit_after>// this entire module is depressing. i should have spent my time learning
// how to patch v8 so that these options would just be available on the
// process object.

const os = require('os');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const execFile = require('child_process').execFile;
const configPath = require('./config-path.js')(process.platform);
const env = process.env;
const user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME || '';
const exclusions = ['--help'];

const configfile = '.v8flags.'+process.versions.v8+'.'+crypto.createHash('md5').update(user).digest('hex')+'.json';

const failureMessage = [
  'Unable to cache a config file for v8flags to your home directory',
  'or a temporary folder. To fix this problem, please correct your',
  'environment by setting HOME=/path/to/home or TEMP=/path/to/temp.',
  'NOTE: the user running this must be able to access provided path.',
  'If all else fails, please open an issue here:',
  'http://github.com/tkellen/js-v8flags'
].join('\n');

function fail (err) {
  err.message += '\n\n' + failureMessage;
  return err;
}

function openConfig (cb) {
  fs.mkdir(configPath, function () {
    tryOpenConfig(path.join(configPath, configfile), function (err, fd) {
      if (err) return tryOpenConfig(path.join(os.tmpdir(), configfile), cb);
      return cb(null, fd);
    });
  })
}

function tryOpenConfig (configpath, cb) {
  try {
    // if the config file is valid, it should be json and therefore
    // node should be able to require it directly. if this doesn't
    // throw, we're done!
    var content = require(configpath);
    process.nextTick(function () {
      cb(null, content);
    });
  } catch (e) {
    // if requiring the config file failed, maybe it doesn't exist, or
    // perhaps it has become corrupted. instead of calling back with the
    // content of the file, call back with a file descriptor that we can
    // write the cached data to
    fs.open(configpath, 'w+', function (err, fd) {
      if (err) {
        return cb(err);
      }
      return cb(null, fd);
    });
  }
}

// i can't wait for the day this whole module is obsolete because these
// options are available on the process object. this executes node with
// `--v8-options` and parses the result, returning an array of command
// line flags.
function getFlags (cb) {
  execFile(process.execPath, ['--v8-options'], function (execErr, result) {
    if (execErr) {
      return cb(execErr);
    }
    var flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
      return match.substring(2);
    }).filter(function (name) {
      return exclusions.indexOf(name) === -1;
    });
    return cb(null, flags);
  });
}

// write some json to a file descriptor. if this fails, call back
// with both the error and the data that was meant to be written.
function writeConfig (fd, flags, cb) {
  var json = JSON.stringify(flags);
  var buf;
  if (Buffer.from && Buffer.from !== Uint8Array.from) {
    // Node.js 4.5.0 or newer
    buf = Buffer.from(json);
  } else {
    // Old Node.js versions
    // The typeof safeguard below is mostly against accidental copy-pasting
    // and code rewrite, it never happens as json is always a string here.
    if (typeof json === 'number') throw new Error('Unexpected type number');
    buf = new Buffer(json);
  }
  return fs.write(fd, buf, 0, buf.length, 0 , function (writeErr) {
    fs.close(fd, function (closeErr) {
      var err = writeErr || closeErr;
      if (err) {
        return cb(fail(err), flags);
      }
      return cb(null, flags);
    });
  });
}

module.exports = function (cb) {
  // bail early if this is not node
  var isElectron = process.versions && process.versions.electron;
  if (isElectron) {
    return process.nextTick(function () {
      cb(null, []);
    });
  }

  // attempt to open/read cache file
  openConfig(function (openErr, result) {
    if (!openErr && typeof result !== 'number') {
      return cb(null, result);
    }
    // if the result is not an array, we need to go fetch
    // the flags by invoking node with `--v8-options`
    getFlags(function (flagsErr, flags) {
      // if there was an error fetching the flags, bail immediately
      if (flagsErr) {
        return cb(flagsErr);
      }
      // if there was a problem opening the config file for writing
      // throw an error but include the flags anyway so that users
      // can continue to execute (at the expense of having to fetch
      // flags on every run until they fix the underyling problem).
      if (openErr) {
        return cb(fail(openErr), flags);
      }
      // write the config file to disk so subsequent runs can read
      // flags out of a cache file.
      return writeConfig(result, flags, cb);
    });
  });
};

module.exports.configfile = configfile;
module.exports.configPath = configPath;
<|endoftext|>


<commit_before>var spawn = require('child_process').spawn;
var fs = require("fs");
var jsonfile = require('jsonfile');
var webpackOutputJsonFilename = "webpack-output.json";
var reportFileName = "webpack-bamboo-report.json";

console.log("Creating " + webpackOutputJsonFilename);
const tempWritable = fs.createWriteStream(webpackOutputJsonFilename);
console.log("Running webpack --json -p");
try {
    var child = spawn('node', ['./node_modules/webpack/bin/webpack.js', '--json', '-p']);
    child.stdout.on('data', function (data) {
        try {
            tempWritable.write(data);
        } catch (e) {
            console.error(e);
        }
    });
    child.on("error", function(error) {
        console.error(error);
    });
    child.on('close', function (code) {
        console.log("Reading " + webpackOutputJsonFilename);
        jsonfile.readFile(webpackOutputJsonFilename, function (err, obj) {
            if (err) {
                console.error(err);
                return;
            }
            var result = {
                stats: {
                    tests: 0 /*(result.success + result.failed)*/,
                    passes: 0 /*result.success*/,
                    failures: obj.errors.length /*result.failed*/,
                    duration: obj.time /*results.time*/
                },
                failures: obj.errors.map(function (error) {
                    var lines = error.split("\n");
                    return {
                        title: lines[0],
                        fullTitle: lines[1],
                        duration: obj.time,
                        error: lines.slice(2).join("\n")
                    }
                }),
                passes: [],
                skipped: []
            };
            for (var i = 0; i < result.failures.length; i++) {
                var failure = result.failures[i];
                console.error(failure.title + ": " + failure.fullTitle + "\n" + failure.error);
            }
            console.log("Writing " + reportFileName);
            jsonfile.writeFileSync(reportFileName, result, {spaces: 2});
            console.log("Exiting with code " + code);
            process.exit(code);
        });
    });
} catch (e) {
    log.erro(e);
}<commit_msg>Supports arguments. Better logging<commit_after>var spawn = require('child_process').spawn;
var fs = require("fs");
var jsonfile = require('jsonfile');
var webpackOutputJsonFilename = "webpack-output.json";
var reportFileName = "webpack-bamboo-report.json";

console.log("Creating " + webpackOutputJsonFilename);
const tempWritable = fs.createWriteStream(webpackOutputJsonFilename);
var arguments = ['./node_modules/webpack/bin/webpack.js', '--json'];
Array.prototype.push.apply(arguments, process.argv.slice(2));
console.log("Running node " + arguments.join(" "));

try {
    var child = spawn('node', arguments);
    console.log("Child process PID: " + child.pid);
    child.stdout.on('data', function (data) {
        try {
            tempWritable.write(data);
        } catch (e) {
            console.error(e);
        }
    });
    child.stderr.on('data', function(data) {
        console.log(data);
    });
    child.on("error", function(error) {
        console.error(error);
    });
    child.on("message", function(message) {
        console.info(message);
    });
    child.on("exit", function(code, signal) {
        console.info("Child process exited with code " + code + ", signal " + signal);
    });
    child.on('close', function (code) {
        console.log("Reading " + webpackOutputJsonFilename);
        jsonfile.readFile(webpackOutputJsonFilename, function (err, obj) {
            if (err) {
                console.error(err);
                return;
            }
            var result = {
                stats: {
                    tests: 0 /*(result.success + result.failed)*/,
                    passes: 0 /*result.success*/,
                    failures: obj.errors.length /*result.failed*/,
                    duration: obj.time /*results.time*/
                },
                failures: obj.errors.map(function (error) {
                    var lines = error.split("\n");
                    return {
                        title: lines[0],
                        fullTitle: lines[1],
                        duration: obj.time,
                        error: lines.slice(2).join("\n")
                    }
                }),
                passes: [],
                skipped: []
            };
            for (var i = 0; i < result.failures.length; i++) {
                var failure = result.failures[i];
                console.error(failure.title + ": " + failure.fullTitle + "\n" + failure.error);
            }
            console.log("Writing " + reportFileName);
            jsonfile.writeFileSync(reportFileName, result, {spaces: 2});
            console.log("Exiting with code " + code);
            process.exit(code);
        });
    });
} catch (e) {
    console.error(e);
}<|endoftext|>


<commit_before>module.exports = simpleGet

var concat = require('simple-concat')
var http = require('http')
var https = require('https')
var once = require('once')
var querystring = require('querystring')
var unzipResponse = require('unzip-response') // excluded from browser build
var url = require('url')

function simpleGet (opts, cb) {
  opts = typeof opts === 'string' ? {url: opts} : Object.assign({}, opts)
  cb = once(cb)

  if (opts.url) parseOptsUrl(opts)
  if (opts.headers == null) opts.headers = {}
  if (opts.maxRedirects == null) opts.maxRedirects = 10

  var body
  if (opts.form) body = typeof opts.form === 'string' ? opts.form : querystring.stringify(opts.form)
  if (opts.body) body = opts.json ? JSON.stringify(opts.body) : opts.body

  if (opts.json) opts.headers.accept = 'application/json'
  if (opts.json && body) opts.headers['content-type'] = 'application/json'
  if (opts.form) opts.headers['content-type'] = 'application/x-www-form-urlencoded'
  if (body) opts.headers['content-length'] = Buffer.byteLength(body)
  delete opts.body; delete opts.form

  if (body && !opts.method) opts.method = 'POST'
  if (opts.method) opts.method = opts.method.toUpperCase()

  // Request gzip/deflate
  var customAcceptEncoding = Object.keys(opts.headers).some(function (h) {
    return h.toLowerCase() === 'accept-encoding'
  })
  if (!customAcceptEncoding) opts.headers['accept-encoding'] = 'gzip, deflate'

  // Support http/https urls
  var protocol = opts.protocol === 'https:' ? https : http
  var req = protocol.request(opts, function (res) {
    // Follow 3xx redirects
    if (res.statusCode >= 300 && res.statusCode < 400 && 'location' in res.headers) {
      opts.url = res.headers.location
      parseOptsUrl(opts)
      res.resume() // Discard response

      if (opts.maxRedirects > 0) {
        opts.maxRedirects -= 1
        simpleGet(opts, cb)
      } else {
        cb(new Error('too many redirects'))
      }
      return
    }

    var tryUnzip = typeof unzipResponse === 'function' && opts.method !== 'HEAD'
    cb(null, tryUnzip ? unzipResponse(res) : res)
  })
  req.on('timeout', function () {
    req.abort()
    cb(new Error('Request timed out'))
  })
  req.on('error', cb)
  req.end(body)
  return req
}

simpleGet.concat = function (opts, cb) {
  return simpleGet(opts, function (err, res) {
    if (err) return cb(err)
    concat(res, function (err, data) {
      if (err) return cb(err)
      if (opts.json) {
        try {
          data = JSON.parse(data.toString())
        } catch (err) {
          return cb(err, res, data)
        }
      }
      cb(null, res, data)
    })
  })
}

;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(function (method) {
  simpleGet[method] = function (opts, cb) {
    if (typeof opts === 'string') opts = {url: opts}
    opts.method = method.toUpperCase()
    return simpleGet(opts, cb)
  }
})

function parseOptsUrl (opts) {
  var loc = url.parse(opts.url)
  if (loc.hostname) opts.hostname = loc.hostname
  if (loc.port) opts.port = loc.port
  if (loc.protocol) opts.protocol = loc.protocol
  if (loc.auth) opts.auth = loc.auth
  opts.path = loc.path
  delete opts.url
}
<commit_msg>Remove extra parseOptsUrl() call<commit_after>module.exports = simpleGet

var concat = require('simple-concat')
var http = require('http')
var https = require('https')
var once = require('once')
var querystring = require('querystring')
var unzipResponse = require('unzip-response') // excluded from browser build
var url = require('url')

function simpleGet (opts, cb) {
  opts = typeof opts === 'string' ? {url: opts} : Object.assign({}, opts)
  cb = once(cb)

  if (opts.url) parseOptsUrl(opts)
  if (opts.headers == null) opts.headers = {}
  if (opts.maxRedirects == null) opts.maxRedirects = 10

  var body
  if (opts.form) body = typeof opts.form === 'string' ? opts.form : querystring.stringify(opts.form)
  if (opts.body) body = opts.json ? JSON.stringify(opts.body) : opts.body

  if (opts.json) opts.headers.accept = 'application/json'
  if (opts.json && body) opts.headers['content-type'] = 'application/json'
  if (opts.form) opts.headers['content-type'] = 'application/x-www-form-urlencoded'
  if (body) opts.headers['content-length'] = Buffer.byteLength(body)
  delete opts.body; delete opts.form

  if (body && !opts.method) opts.method = 'POST'
  if (opts.method) opts.method = opts.method.toUpperCase()

  // Request gzip/deflate
  var customAcceptEncoding = Object.keys(opts.headers).some(function (h) {
    return h.toLowerCase() === 'accept-encoding'
  })
  if (!customAcceptEncoding) opts.headers['accept-encoding'] = 'gzip, deflate'

  // Support http/https urls
  var protocol = opts.protocol === 'https:' ? https : http
  var req = protocol.request(opts, function (res) {
    // Follow 3xx redirects
    if (res.statusCode >= 300 && res.statusCode < 400 && 'location' in res.headers) {
      opts.url = res.headers.location
      res.resume() // Discard response

      if (opts.maxRedirects > 0) {
        opts.maxRedirects -= 1
        simpleGet(opts, cb)
      } else {
        cb(new Error('too many redirects'))
      }
      return
    }

    var tryUnzip = typeof unzipResponse === 'function' && opts.method !== 'HEAD'
    cb(null, tryUnzip ? unzipResponse(res) : res)
  })
  req.on('timeout', function () {
    req.abort()
    cb(new Error('Request timed out'))
  })
  req.on('error', cb)
  req.end(body)
  return req
}

simpleGet.concat = function (opts, cb) {
  return simpleGet(opts, function (err, res) {
    if (err) return cb(err)
    concat(res, function (err, data) {
      if (err) return cb(err)
      if (opts.json) {
        try {
          data = JSON.parse(data.toString())
        } catch (err) {
          return cb(err, res, data)
        }
      }
      cb(null, res, data)
    })
  })
}

;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(function (method) {
  simpleGet[method] = function (opts, cb) {
    if (typeof opts === 'string') opts = {url: opts}
    opts.method = method.toUpperCase()
    return simpleGet(opts, cb)
  }
})

function parseOptsUrl (opts) {
  var loc = url.parse(opts.url)
  if (loc.hostname) opts.hostname = loc.hostname
  if (loc.port) opts.port = loc.port
  if (loc.protocol) opts.protocol = loc.protocol
  if (loc.auth) opts.auth = loc.auth
  opts.path = loc.path
  delete opts.url
}
<|endoftext|>


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

var counterSchema = new mongoose.Schema({
    model: {
        type: String,
        require: true
    },
    field: {
        type: String,
        require: true
    },
    c: {
        type: Number,
        default: 0
    }
});
counterSchema.index({ field: 1, model: 1 }, { unique: true, required: true, index: -1 });
var Counter = mongoose.connection.model('Counter', counterSchema);

module.exports = exports = function (schema, options) {
    var settings = {
            model: null,
            field: '_id',
            startAt: 0,
            incrementBy: 1
        },
        fields = {},
        ready = false;

    switch (typeof(options)) {
        case 'String':
            settings.model = options;
            break;
        case 'Object':
            extend(settings, options);
            break;
    }

    fields[settings.field] = {
        type: Number,
        unique: true,
        require: true
    };
    schema.add(fields);

    Counter.findOne(
        { model: settings.model, field: settings.field },
        function (err, res) {
            if (!res) {
                var counter = new Counter({ model: settings.model, field: settings.field, c: settings.startAt });
                counter.save(function () {
                    ready = true;
                });
            }
            else
                ready = true;
        }
    );

    schema.pre('save', function (next) {
        var doc = this;
        (function save() {
            if (ready) {
                Counter.collection.findAndModify(
                    { model: settings.model, field: settings.field },
                    null,
                    { $inc: { c: settings.incrementBy } },
                    { new: true, upsert: true },
                    function (err, res) {
                        if (err) return next(err);
                        if (typeof(doc[settings.field]) !== 'number')
                            doc[settings.field] = res.c - 1;
                        next();
                    }
                );
            }
            else
                setTimeout(save, 5);
        })();
    });
};<commit_msg>Made counter collection name more unique.<commit_after>var mongoose = require('mongoose');

var counterSchema = new mongoose.Schema({
    model: {
        type: String,
        require: true
    },
    field: {
        type: String,
        require: true
    },
    c: {
        type: Number,
        default: 0
    }
});
counterSchema.index({ field: 1, model: 1 }, { unique: true, required: true, index: -1 });
var Counter = mongoose.connection.model('MAIC-Counter', counterSchema);

module.exports = exports = function (schema, options) {
    var settings = {
            model: null,
            field: '_id',
            startAt: 0,
            incrementBy: 1
        },
        fields = {},
        ready = false;

    switch (typeof(options)) {
        case 'String':
            settings.model = options;
            break;
        case 'Object':
            extend(settings, options);
            break;
    }

    fields[settings.field] = {
        type: Number,
        unique: true,
        require: true
    };
    schema.add(fields);

    Counter.findOne(
        { model: settings.model, field: settings.field },
        function (err, res) {
            if (!res) {
                var counter = new Counter({ model: settings.model, field: settings.field, c: settings.startAt });
                counter.save(function () {
                    ready = true;
                });
            }
            else
                ready = true;
        }
    );

    schema.pre('save', function (next) {
        var doc = this;
        (function save() {
            if (ready) {
                Counter.collection.findAndModify(
                    { model: settings.model, field: settings.field },
                    null,
                    { $inc: { c: settings.incrementBy } },
                    { new: true, upsert: true },
                    function (err, res) {
                        if (err) return next(err);
                        if (typeof(doc[settings.field]) !== 'number')
                            doc[settings.field] = res.c - 1;
                        next();
                    }
                );
            }
            else
                setTimeout(save, 5);
        })();
    });
};<|endoftext|>


<commit_before>'use strict'

const Lambda = require('aws-sdk/clients/lambda')
const EventEmitter = require('events')
const through2 = require('through2')
const zip = require('yazl')

/**
 * Create distributed jobs using AWS Lambda functions
 *
 * @type {Class}
 */

module.exports = class Hivemind extends EventEmitter {
  constructor(params) {
    super()

    this.func = params.func
    this.lambda = new Lambda({
      AccessKeyId: params.accessKeyId,
      SecretAccessKey: params.secretAccessKey,
      region: params.awsRegion
    })

    // Chunk the data into individual arrays for processing
    this.chunks = []
    params.data.forEach((item, index) => {

      // If chunk doesn't exist yet, create it.
      if (!this.chunks[index % params.chunkSize]) {
        this.chunks[index % params.chunkSize] = []
      }

      this.chunks[index % params.chunkSize].push(item)
    })
  }

  /**
   * Publishes the ZIP file as a Lambda function
   *
   * @param  {String} zipFile Fully-qualified path to ZIP file containing script
   */

  publish(params, awsParams) {
    if (!params.files || params.files.length === 0) {
      throw new Error('You must specify files to publish a function')
    }

    // Build ZIP file stream from passed functions
    const file = new zip.ZipFile()

    // Add files to zip file
    params.files.forEach(filePath => file.addFile(filePath, filePath))

    // Signal that there are no more files
    file.end()

    // Array to contain buffers
    let buff = Buffer.alloc(0)

    // We have to pipe the stream through 'through' so we can extract
    // the buffers that are contained in the stream
    file.outputStream
      .pipe(through2((chunk, _, callback) => {

        // Push buffers to buffer
        buff = Buffer.concat([buff, chunk])
        return callback()
      }))
      .on('finish', () => {

        // Merge parameters and AWS parameters
        // This is so add'l that only AWS cares about can be passed
        const mergedParams = Object.assign({
          Code: {
            ZipFile: buff
          },
          FunctionName: this.func.name,
          Handler: this.func.handler || 'index.handler',
          Role: this.func.role,
          Runtime: this.func.runtime || 'nodejs6.10'
        }, awsParams)

        // Check if function already exists!
        // This determines whether we will create or update the function
        this.lambda.getFunction({
          FunctionName: mergedParams.FunctionName
        }, (err) => {
          const deployCallback = (error) => {
            if (err) {
              return this.emit('error', error)
            }

            return this.emit('create')
          }

          if (err) {
            if (err.statusCode === 404) {
              this.lambda.createFunction(mergedParams, deployCallback)
            } else {
              this.emit('error', err)
            }
          }

          this.lambda.updateFunctionCode({
            FunctionName: mergedParams.FunctionName,
            ZipFile: mergedParams.Code.ZipFile
          }, deployCallback)
        })
      })
  }

  /**
   * Launches functions and passes chunked data that was passed into the construtor
   */

  run() {
    const promises = this.chunks.map((chunk) => {
      return new Promise((resolve, reject) => {
        this.lambda.invoke({
          FunctionName: this.func.name,
          Payload: JSON.stringify({
            chunk
          })
        }, (err, data) => {
          if (err) {
            return reject(err) && this.emit('error', err)
          }

          resolve()
          return this.emit('finish', data.Payload)
        })
      })
    })

    Promise.all(promises)
      .then(() => {
        this.emit('end')
      })
  }
}
<commit_msg>feat(Hivemind): Add ZIP + S3 files for publish()<commit_after>'use strict'

const Lambda = require('aws-sdk/clients/lambda')
const EventEmitter = require('events')
const through2 = require('through2')
const path = require('path')
const zip = require('yazl')
const fs = require('fs')

/**
 * Create distributed jobs using AWS Lambda functions
 *
 * @type {Class}
 */

module.exports = class Hivemind extends EventEmitter {
  constructor(params) {
    super()

    this.func = params.func
    this.lambda = new Lambda({
      AccessKeyId: params.accessKeyId,
      SecretAccessKey: params.secretAccessKey,
      region: params.awsRegion
    })

    // Chunk the data into individual arrays for processing
    this.chunks = []
    params.data.forEach((item, index) => {

      // If chunk doesn't exist yet, create it.
      if (!this.chunks[index % params.chunkSize]) {
        this.chunks[index % params.chunkSize] = []
      }

      this.chunks[index % params.chunkSize].push(item)
    })
  }

  /**
   * Publishes the ZIP file as a Lambda function
   *
   * @param  {String} zipFile Fully-qualified path to ZIP file containing script
   */

  publish(params, awsParams) {

    const publishFunc = (code) => {
      // Merge parameters and AWS parameters
      // This is so add'l that only AWS cares about can be passed
      const mergedParams = Object.assign({
        Code: {
          ZipFile: code
        },
        FunctionName: this.func.name,
        Handler: this.func.handler || 'index.handler',
        Role: this.func.role,
        Runtime: this.func.runtime || 'nodejs6.10'
      }, awsParams || {})

      // Check if function already exists!
      // This determines whether we will create or update the function
      this.lambda.getFunction({
        FunctionName: mergedParams.FunctionName
      }, (err, res) => {
        const deployCallback = (error) => {
          if (err) {
            return this.emit('error', error)
          }

          return this.emit('create')
        }

        if (err) {
          if (err.statusCode === 404) {
            this.lambda.createFunction(mergedParams, deployCallback)
          } else {
            this.emit('error', err)
          }
        }

        this.lambda.updateFunctionCode({
          FunctionName: res.Configuration.FunctionArn,
          ZipFile: mergedParams.Code.ZipFile
        }, deployCallback)
      })
    }

    if (params.zipFile) {
      publishFunc(fs.readFileSync(path.resolve(params.zipFile)))
    } else if (params.files) {
      // Build ZIP file stream from passed functions
      const file = new zip.ZipFile()

      // Add files to zip file
      params.files.forEach(filePath => file.addFile(filePath, filePath))

      // Signal that there are no more files
      file.end()

      // Array to contain buffers
      let buff = Buffer.alloc(0)

      // We have to pipe the stream through 'through' so we can extract
      // the buffers that are contained in the stream
      file.outputStream
        .pipe(through2((chunk, _, callback) => {

          // Push buffers to buffer
          buff = Buffer.concat([buff, chunk])
          return callback()
        }))
        .on('finish', () => {
          publishFunc(buff)
        })
    } else if (awsParams.Code.S3Key) {
      publishFunc()
    } else {
      throw new Error('You have to specify a code location to publish a function')
    }
  }

  /**
   * Launches functions and passes chunked data that was passed into the construtor
   */

  run() {
    const promises = this.chunks.map((chunk) => {
      return new Promise((resolve, reject) => {
        this.lambda.invoke({
          FunctionName: this.func.name,
          Payload: JSON.stringify({
            chunk
          })
        }, (err, data) => {
          if (err) {
            return reject(err) && this.emit('error', err)
          }

          resolve()
          return this.emit('finish', data.Payload)
        })
      })
    })

    Promise.all(promises)
      .then(() => {
        this.emit('end')
      })
  }
}
<|endoftext|>


<commit_before>/**
 * @jsx React.DOM
 */

var React = require('react')

module.exports = React.createClass({

  displayName: 'react-crouton',

  propTypes: {
    id: React.PropTypes.number.isRequired,
    onDismiss: React.PropTypes.func,
    hidden: React.PropTypes.bool,
    timeout: React.PropTypes.number,
    autoMiss: React.PropTypes.bool,
    message: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.array
      ]).isRequired,
    type: React.PropTypes.string.isRequired,
    buttons: function(props, propName, componentName) {
      var propValue = props[propName];
      if (propValue != null && typeof propValue !== 'string' && typeof propValue !== 'object' && !(typeof propValue === 'object' && propValue.name != null))
        return new Error('Expected a string or an URI for ' + propName + ' in ' + componentName );
    }
  },

  getInitialState: function() {
    return {
      // 2000 ms
      timeout: 2000,
      autoMiss: false,
      hidden: false,
      ttd: null
    };
  },

  dismiss: function() {
    this.setState({
      hidden: true
    });
    if (this.state.onDismiss) {
      this.state.onDismiss();
    }
    return this;
  },

  clearTimeout: function() {
    if(this.state.ttd)
      clearTimeout(this.state.ttd)
    return this;
  },

  handleClick: function(event) {
    this.dismiss().clearTimeout();
    var item = this.state.buttons.filter(function(button){
        return button.name.toLowerCase() === event.target.id
      })[0];
    if(item && item.listener){
      item.listener(event);
    }
  },

  componentWillMount: function() {
    this.changeState(this.props);
  },

  changeState: function(nextProps) {
    var buttons = nextProps.buttons;
    var self = this;
    if (typeof buttons === 'string')
      buttons = [buttons];
    if (buttons) {
      buttons = buttons.map(function(button) {
        if (typeof button === 'string')
          return {
            name: button
          };
        return button;
      });
    }

    var message = nextProps.message
    if(typeof message === 'string')
      message = [message];
    var autoMiss = nextProps.autoMiss || (buttons ? false : true);
    this.setState({
      onDismiss: nextProps.onDismiss || this.state.onDismiss,
      hidden: nextProps.hidden,
      buttons: buttons,
      timeout: nextProps.timeout || this.state.timeout,
      autoMiss: autoMiss,
      message: message,
      type: nextProps.type
    });
    if(autoMiss && !nextProps.hidden){
      var ttd = setTimeout(function() {
        self.dismiss()
      }, this.state.timeout);

      this.setState({
        ttd: ttd
      });
    }
  },

  componentWillReceiveProps: function(nextProps) {
    this.changeState(nextProps);
  },

  shouldComponentUpdate: function(nextProps, nextState) {
    if( nextProps.id === this.props.id ) {
      return nextState.hidden;
    }
    return true
  },

  render: function() {
    var self = this;
    return (

          {this.state.message.map(function(msg, i){
            return {msg}
          })}
          {
            this.state.buttons ?

            {this.state.buttons.map(function(button){
              return (<button
                id={button.name.toLowerCase()}
                key={button.name.toLowerCase()}
                className={button.name.toLowerCase()}
                onClick={self.handleClick}>{button.name}</button> )
            })}
: null

          }

    )
  }
})
<commit_msg>Clean code.<commit_after>/**
 * @jsx React.DOM
 */

var React = require('react')

module.exports = React.createClass({

  displayName: 'react-crouton',

  propTypes: {
    id: React.PropTypes.number.isRequired,
    onDismiss: React.PropTypes.func,
    hidden: React.PropTypes.bool,
    timeout: React.PropTypes.number,
    autoMiss: React.PropTypes.bool,
    message: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.array
      ]).isRequired,
    type: React.PropTypes.string.isRequired,
    buttons: function(props, propName, componentName) {
      var propValue = props[propName];
      if (propValue != null && typeof propValue !== 'string' && typeof propValue !== 'object' && !(typeof propValue === 'object' && propValue.name != null))
        return new Error('Expected a string or an URI for ' + propName + ' in ' + componentName );
    }
  },

  getInitialState: function() {
    return {
      // 2000 ms
      timeout: 2000,
      autoMiss: false,
      hidden: false,
      ttd: null
    };
  },

  dismiss: function() {
    this.setState({
      hidden: true
    });
    if (this.state.onDismiss) {
      this.state.onDismiss();
    }
    return this;
  },

  clearTimeout: function() {
    if(this.state.ttd)
      clearTimeout(this.state.ttd)
    return this;
  },

  handleClick: function(event) {
    this.dismiss().clearTimeout();
    var item = this.state.buttons.filter(function(button){
        return button.name.toLowerCase() === event.target.id
      })[0];
    if(item && item.listener){
      item.listener(event);
    }
  },

  componentWillMount: function() {
    this.changeState(this.props);
  },

  changeState: function(nextProps) {
    var buttons = nextProps.buttons;
    if (typeof buttons === 'string')
      buttons = [buttons];
    if (buttons) {
      buttons = buttons.map(function(button) {
        if (typeof button === 'string')
          return {
            name: button
          };
        return button;
      });
    }

    var message = nextProps.message
    if(typeof message === 'string')
      message = [message];
    var autoMiss = nextProps.autoMiss || (buttons ? false : true);
    this.setState({
      onDismiss: nextProps.onDismiss || this.state.onDismiss,
      hidden: nextProps.hidden,
      buttons: buttons,
      timeout: nextProps.timeout || this.state.timeout,
      autoMiss: autoMiss,
      message: message,
      type: nextProps.type
    });
    if(autoMiss && !nextProps.hidden){
      var ttd = setTimeout(this.dismiss.bind(this), this.state.timeout);

      this.setState({
        ttd: ttd
      });
    }
  },

  componentWillReceiveProps: function(nextProps) {
    this.changeState(nextProps);
  },

  shouldComponentUpdate: function(nextProps, nextState) {
    if( nextProps.id === this.props.id ) {
      return nextState.hidden;
    }
    return true
  },

  render: function() {
    return (

          {this.state.message.map(function(msg, i){
            return {msg}
          })}
          {
            this.state.buttons ?

            {this.state.buttons.map(function(button){
              return (<button
                id={button.name.toLowerCase()}
                key={button.name.toLowerCase()}
                className={button.name.toLowerCase()}
                onClick={this.handleClick}>{button.name}</button> )
            }, this)}
: null

          }

    )
  }
})
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const redis = require('redis');

const Loader = require('./modules/loader');
const builder = require('./modules/builder');
const tweeter = require('./modules/tweeter');

const client = redis.createClient();

builder.setClient(client);
tweeter.setClient(client);

const h = require('./modules/helpers');

const config =
    fs.existsSync('./local.config.js') ?
    require('./local.config.js') :
    require('./config.js');

const B = new builder.Builder(config.output);
const L = new Loader(config.download);
const T = new tweeter.Tweeter(config.twitterAPI);

const nomenclator = require('./nomenclator.json');

const build = function() {
    let place = h.choice(nomenclator);

    let url = `https://maps.googleapis.com/maps/api/streetview?size=640x440&location=${encodeURI(place.place)}, ${encodeURI(place.council)},Spain&fov=${h.randint(90,120)}&heading=${h.randint(0,360)}&pitch=0&key=${config.mapsAPI}`;

    L.load(url)
        .then(file => B.build(file, {
            font: config.font,
            stamp: config.stamps[place.province],
            council: place.council,
            place: place.place
        }))
        .then(file => T.tweet(file, {
            council: place.council
        }))
        .then(id => console.log(`https://twitter.com/postaisgalegas/status/${id}`))
        .catch(error => {
            console.log(error);
            return h.sleep(2).then(() => build());
        });
};

setInterval(() => build(), 60 * 60 * 1000);
build();

process.on('SIGINT', function() {
    console.log('Exiting');
    client.end();
    process.exit();
});
<commit_msg>Try to get better geocoding<commit_after>'use strict';

const fs = require('fs');
const redis = require('redis');

const Loader = require('./modules/loader');
const builder = require('./modules/builder');
const tweeter = require('./modules/tweeter');

const client = redis.createClient();

builder.setClient(client);
tweeter.setClient(client);

const h = require('./modules/helpers');

const config =
    fs.existsSync('./local.config.js') ?
    require('./local.config.js') :
    require('./config.js');

const B = new builder.Builder(config.output);
const L = new Loader(config.download);
const T = new tweeter.Tweeter(config.twitterAPI);

const nomenclator = require('./nomenclator.json');

const build = function() {
    let place = h.choice(nomenclator);

    let url = `https://maps.googleapis.com/maps/api/streetview?size=640x440&location=${encodeURI(place.place)},${encodeURI(place.council)},${encodeURI(place.province)},Spain&fov=${h.randint(90,120)}&heading=${h.randint(0,360)}&pitch=0&key=${config.mapsAPI}`;

    L.load(url)
        .then(file => B.build(file, {
            font: config.font,
            stamp: config.stamps[place.province],
            council: place.council,
            place: place.place
        }))
        .then(file => T.tweet(file, {
            council: place.council
        }))
        .then(id => console.log(`https://twitter.com/postaisgalegas/status/${id}`))
        .catch(error => {
            console.log(error);
            return h.sleep(2).then(() => build());
        });
};

setInterval(() => build(), 60 * 60 * 1000);
build();

process.on('SIGINT', function() {
    console.log('Exiting');
    client.end();
    process.exit();
});
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var path = require('path');
var Funnel = require('broccoli-funnel');
var BroccoliMergeTrees = require('broccoli-merge-trees');

module.exports = {
  name: 'ember-cli-bootstrap-bookingsync-sass',

  included: function(app, parentAddon) {
    var target = (parentAddon || app);
    this._super.included(target);

    this.assetsPath = path.join(this.root, 'assets');
    this.vendorPath = path.join('vendor', 'ember-cli-bootstrap-bookingsync-sass');
    this.vendorJavascriptsPath = path.join(this.vendorPath, 'javascripts', 'bookingsync');

    if (process.env.EMBER_CLI_FASTBOOT) {
      this.ui.writeLine('bootstrap-bookingsync-sass: no JS enabled [FastBoot]');
    } else {
      target.import(path.join(this.vendorJavascriptsPath, 'form.js'));
      target.import(path.join(this.vendorJavascriptsPath, 'stackable.js'));
      target.import(path.join(this.vendorJavascriptsPath, 'switch.js'));
      target.import(path.join(app.bowerDirectory, '/sweetalert2/dist/sweetalert2.js'));
      target.import(path.join(app.bowerDirectory, '/sweetalert2/dist/sweetalert2.css'));
      this._ensureThisImport();
      this.import(path.join(this.treePaths.vendor, 'shims', 'sweetalert.js'));
    }
  },

  contentFor: function(type) {
    if (type === 'head') {
      return '<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700,300">';
    }
  },

  treeForStyles: function(tree) {
    var stylesheetsPath = path.join(this.assetsPath, 'stylesheets');
    var assetsTree = new Funnel(this.treeGenerator(stylesheetsPath), {
      srcDir: '/',
      destDir: '/app/styles'
    });

    return assetsTree;
  },

  treeForVendor: function(tree) {
    var javascriptsPath = path.join(this.assetsPath, 'javascripts');
    var javascriptsTree = new Funnel(this.treeGenerator(javascriptsPath), {
      srcDir: '/',
      destDir: '/ember-cli-bootstrap-bookingsync-sass/javascripts'
    });

    var vendorTrees = new BroccoliMergeTrees([javascriptsTree]);

    return vendorTrees;
  },

  // TODO: Remove once stable.
  isDevelopingAddon: function() {
    return true;
  },

  _ensureThisImport: function() {
    if (!this.import) {
      this._findHost = function findHostShim() {
        var current = this;
        var app;
        do {
          app = current.app || app;
        } while (current.parent.parent && (current = current.parent));
        return app;
      };
      this.import = function importShim(asset, options) {
        var app = this._findHost();
        app.import(asset, options);
      };
    }
  }
};
<commit_msg>Removed this import polyfill; fix shim import 2nd try<commit_after>/* jshint node: true */
'use strict';

var path = require('path');
var Funnel = require('broccoli-funnel');
var BroccoliMergeTrees = require('broccoli-merge-trees');

module.exports = {
  name: 'ember-cli-bootstrap-bookingsync-sass',

  included: function(app, parentAddon) {
    var target = (parentAddon || app);
    this._super.included(target);

    this.assetsPath = path.join(this.root, 'assets');
    this.vendorPath = path.join('vendor', 'ember-cli-bootstrap-bookingsync-sass');
    this.vendorJavascriptsPath = path.join(this.vendorPath, 'javascripts', 'bookingsync');

    if (process.env.EMBER_CLI_FASTBOOT) {
      this.ui.writeLine('bootstrap-bookingsync-sass: no JS enabled [FastBoot]');
    } else {
      target.import(path.join(this.vendorJavascriptsPath, 'form.js'));
      target.import(path.join(this.vendorJavascriptsPath, 'stackable.js'));
      target.import(path.join(this.vendorJavascriptsPath, 'switch.js'));
      target.import(path.join(app.bowerDirectory, '/sweetalert2/dist/sweetalert2.js'));
      target.import(path.join(app.bowerDirectory, '/sweetalert2/dist/sweetalert2.css'));
      app.import('vendor/shims/sweetalert.js');
    }
  },

  contentFor: function(type) {
    if (type === 'head') {
      return '<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700,300">';
    }
  },

  treeForStyles: function(tree) {
    var stylesheetsPath = path.join(this.assetsPath, 'stylesheets');
    var assetsTree = new Funnel(this.treeGenerator(stylesheetsPath), {
      srcDir: '/',
      destDir: '/app/styles'
    });

    return assetsTree;
  },

  treeForVendor: function(tree) {
    var javascriptsPath = path.join(this.assetsPath, 'javascripts');
    var javascriptsTree = new Funnel(this.treeGenerator(javascriptsPath), {
      srcDir: '/',
      destDir: '/ember-cli-bootstrap-bookingsync-sass/javascripts'
    });

    var vendorTrees = new BroccoliMergeTrees([javascriptsTree]);

    return vendorTrees;
  },

  // TODO: Remove once stable.
  isDevelopingAddon: function() {
    return true;
  }
};
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var crypto = require('crypto')
var mkdirp = require('mkdirp')
var glob = require('glob')

var isWindows = process.platform === 'win32'
var pathSep   = path.sep

exports.hashTree = hashTree
function hashTree (fullPath) {
  // This function is used by the watcher. It makes the following guarantees:
  //
  // (1) It never throws an exception.
  //
  // (2) It does not miss changes. In other words, if after this function returns,
  // any part of the directory hierarchy changes, a subsequent call must
  // return a different hash.
  //
  // (1) and (2) hold even in the face of a constantly-changing file system.
  return hashStrings(keysForTree(fullPath))
}

function keysForTree (fullPath, options) {
  options = options || {}

  var _stack         = options._stack
  var _followSymlink = options._followSymlink
  var relativePath   = options.relativePath || '.'
  var stats
  var statKeys

  try {
    if (_followSymlink) {
      stats = fs.statSync(fullPath)
    } else {
      stats = fs.lstatSync(fullPath)
    }
  } catch (err) {
    console.warn('Warning: failed to stat ' + fullPath)
    // fullPath has probably ceased to exist. Leave `stats` undefined and
    // proceed hashing.
  }
  var childKeys = []
  if (stats) {
    statKeys = ['stats', stats.mode]
  } else {
    statKeys = ['stat failed']
  }
  if (stats && stats.isDirectory()) {
    var fileIdentity = stats.dev + '\x00' + stats.ino
    if (_stack != null && _stack.indexOf(fileIdentity) !== -1) {
      console.warn('Symlink directory loop detected at ' + fullPath + ' (note: loop detection may have false positives on Windows)')
    } else {
      if (_stack != null) _stack = _stack.concat([fileIdentity])
      var entries
      try {
        entries = fs.readdirSync(fullPath).sort()
      } catch (err) {
        console.warn('Warning: Failed to read directory ' + fullPath)
        console.warn(err.stack)
        childKeys = ['readdir failed']
        // That's all there is to say about this directory.
      }
      if (entries != null) {
        for (var i = 0; i < entries.length; i++) {

          var keys = keysForTree(path.join(fullPath, entries[i]), {
            _stack: _stack,
            relativePath: path.join(relativePath, entries[i])
          })
          childKeys = childKeys.concat(keys)
        }
      }
    }
  } else if (stats && stats.isSymbolicLink()) {
    if (_stack == null) {
      // From here on in the traversal, we need to guard against symlink
      // directory loops. _stack is kept null in the absence of symlinks to we
      // don't have to deal with Windows for now, as long as it doesn't use
      // symlinks.
      _stack = []
    }
    childKeys = keysForTree(fullPath, {_stack: _stack, relativePath: relativePath, _followSymlink: true}) // follow symlink
    statKeys.push(stats.mtime.getTime())
    statKeys.push(stats.size)
  } else if (stats && stats.isFile()) {
    statKeys.push(stats.mtime.getTime())
    statKeys.push(stats.size)
  }

  // Perhaps we should not use basename to infer the file name
  return ['path', relativePath]
    .concat(statKeys)
    .concat(childKeys)
}

exports.hashStats = hashStats
function hashStats (stats, path) {
  // Both stats and path can be null
  var keys = []
  if (stats != null) {
    keys.push(stats.mode, stats.size, stats.mtime.getTime())
  }
  if (path != null) {
    keys.push(path)
  }
  return hashStrings(keys)
}

exports.hashStrings = hashStrings
function hashStrings (strings) {
  var joinedStrings = strings.join('\x00')
  return crypto.createHash('md5').update(joinedStrings).digest('hex')
}

// If src is a file, dest is a file name. If src is a directory, dest is the
// directory that the contents of src will be copied into.
//
// This function refuses to overwrite files, but accepts if directories exist
// already.
//
// This does not resolve symlinks. It is not clear whether it should.
//
// Note that unlike cp(1), we do not special-case if dest is an existing
// directory, because relying on things to exist when we're in the middle of
// assembling a new tree is too brittle.
//
// This function should be avoided in favor of
// https://github.com/broccolijs/node-copy-dereference
//
// copy-dereference differs from copyRecursivelySync in that it dereferences
// symlinks. copy-dereference also won't call mkdirp to create the target
// directory (or the parent directory of the target file), which makes it
// stricter: (1) It's not OK for the target directory to exist already, and
// (2) missing parent directories will not automatically be created.
exports.copyRecursivelySync = copyRecursivelySync
function copyRecursivelySync (src, dest, _mkdirp) {
  if (_mkdirp == null) _mkdirp = true
  // Note: We could try readdir'ing and catching ENOTDIR exceptions, but that
  // is 3x slower than stat'ing in the common case that we have a file.
  var srcStats = fs.lstatSync(src)
  if (srcStats.isDirectory()) {
    mkdirp.sync(dest)
    var entries = fs.readdirSync(src).sort()
    for (var i = 0; i < entries.length; i++) {
      // Set _mkdirp to false when recursing to avoid extra mkdirp calls.
      copyRecursivelySync(src + '/' + entries[i], dest + '/' + entries[i], false)
    }
  } else {
    if (_mkdirp) {
      mkdirp.sync(path.dirname(dest))
    }
    copyPreserveSync(src, dest, srcStats)
  }
}

// srcStats is optional; use it as an optimization to avoid double stats
// This function refuses to overwrite files.
exports.copyPreserveSync = copyPreserveSync
function copyPreserveSync (src, dest, srcStats) {
  if (srcStats == null) srcStats = fs.lstatSync(src)
  if (srcStats.isFile()) {
    var content = fs.readFileSync(src)
    fs.writeFileSync(dest, content, { flag: 'wx' })
    fs.utimesSync(dest, srcStats.atime, srcStats.mtime)
  } else if (srcStats.isSymbolicLink()) {
    fs.symlinkSync(fs.readlinkSync(src), dest)
    // We cannot update the atime/mtime of a symlink yet:
    // https://github.com/joyent/node/issues/2142
  } else {
    throw new Error('Unexpected file type for ' + src)
  }
}

exports.linkRecursivelySync = linkRecursivelySync
function linkRecursivelySync () {
  throw new Error('linkRecursivelySync has been removed; use copyRecursivelySync instead (note: it does not overwrite)')
}

exports.linkAndOverwrite = linkAndOverwrite
function linkAndOverwrite () {
  throw new Error('linkAndOverwrite has been removed; use copyPreserveSync instead (note: it does not overwrite)')
}

exports.assertAbsolutePaths = assertAbsolutePaths
function assertAbsolutePaths (paths) {
  for (var i = 0; i < paths.length; i++) {
    if (paths[i][0] !== '/') {
      throw new Error('Path must be absolute: "' + paths[i] + '"')
    }
  }
}

// Multi-glob with reasonable defaults, so APIs all behave the same
exports.multiGlob = multiGlob
function multiGlob (globs, globOptions) {
  if (!Array.isArray(globs)) {
    throw new TypeError("multiGlob's first argument must be an array");
  }
  var options = {
    nomount: true,
    strict: true
  }
  for (var key in globOptions) {
    if (globOptions.hasOwnProperty(key)) {
      options[key] = globOptions[key]
    }
  }

  var pathSet = {}
  var paths = []
  for (var i = 0; i < globs.length; i++) {
    if (options.nomount && globs[i][0] === '/') {
      throw new Error('Absolute paths not allowed (`nomount` is enabled): ' + globs[i])
    }
    var matches = glob.sync(globs[i], options)
    if (matches.length === 0) {
      throw new Error('Path or pattern "' + globs[i] + '" did not match any files')
    }
    for (var j = 0; j < matches.length; j++) {
      if (!pathSet[matches[j]]) {
        pathSet[matches[j]] = true
        paths.push(matches[j])
      }
    }
  }
  return paths
}

exports.symlinkOrCopyPreserveSync = symlinkOrCopyPreserveSync
function symlinkOrCopyPreserveSync (sourcePath, destPath) {
  if (isWindows) {
    copyRecursivelySync(sourcePath, destPath)
  } else {
    if (fs.lstatSync(sourcePath).isSymbolicLink()) {
      // When we encounter symlinks, follow them. This prevents indirection
      // from growing out of control. Note: At the moment `realpath` on Node
      // is 70x slower than native: https://github.com/joyent/node/issues/7902
      sourcePath = fs.realpathSync(sourcePath)
    } else if (sourcePath[0] !== pathSep) {
      sourcePath = process.cwd() + pathSep + sourcePath
    }

    fs.symlinkSync(sourcePath, destPath)
  }
}
<commit_msg>Add deprecation notice for symlinkOrCopyPreserveSync<commit_after>var fs = require('fs')
var path = require('path')
var crypto = require('crypto')
var mkdirp = require('mkdirp')
var glob = require('glob')

var isWindows = process.platform === 'win32'
var pathSep   = path.sep

exports.hashTree = hashTree
function hashTree (fullPath) {
  // This function is used by the watcher. It makes the following guarantees:
  //
  // (1) It never throws an exception.
  //
  // (2) It does not miss changes. In other words, if after this function returns,
  // any part of the directory hierarchy changes, a subsequent call must
  // return a different hash.
  //
  // (1) and (2) hold even in the face of a constantly-changing file system.
  return hashStrings(keysForTree(fullPath))
}

function keysForTree (fullPath, options) {
  options = options || {}

  var _stack         = options._stack
  var _followSymlink = options._followSymlink
  var relativePath   = options.relativePath || '.'
  var stats
  var statKeys

  try {
    if (_followSymlink) {
      stats = fs.statSync(fullPath)
    } else {
      stats = fs.lstatSync(fullPath)
    }
  } catch (err) {
    console.warn('Warning: failed to stat ' + fullPath)
    // fullPath has probably ceased to exist. Leave `stats` undefined and
    // proceed hashing.
  }
  var childKeys = []
  if (stats) {
    statKeys = ['stats', stats.mode]
  } else {
    statKeys = ['stat failed']
  }
  if (stats && stats.isDirectory()) {
    var fileIdentity = stats.dev + '\x00' + stats.ino
    if (_stack != null && _stack.indexOf(fileIdentity) !== -1) {
      console.warn('Symlink directory loop detected at ' + fullPath + ' (note: loop detection may have false positives on Windows)')
    } else {
      if (_stack != null) _stack = _stack.concat([fileIdentity])
      var entries
      try {
        entries = fs.readdirSync(fullPath).sort()
      } catch (err) {
        console.warn('Warning: Failed to read directory ' + fullPath)
        console.warn(err.stack)
        childKeys = ['readdir failed']
        // That's all there is to say about this directory.
      }
      if (entries != null) {
        for (var i = 0; i < entries.length; i++) {

          var keys = keysForTree(path.join(fullPath, entries[i]), {
            _stack: _stack,
            relativePath: path.join(relativePath, entries[i])
          })
          childKeys = childKeys.concat(keys)
        }
      }
    }
  } else if (stats && stats.isSymbolicLink()) {
    if (_stack == null) {
      // From here on in the traversal, we need to guard against symlink
      // directory loops. _stack is kept null in the absence of symlinks to we
      // don't have to deal with Windows for now, as long as it doesn't use
      // symlinks.
      _stack = []
    }
    childKeys = keysForTree(fullPath, {_stack: _stack, relativePath: relativePath, _followSymlink: true}) // follow symlink
    statKeys.push(stats.mtime.getTime())
    statKeys.push(stats.size)
  } else if (stats && stats.isFile()) {
    statKeys.push(stats.mtime.getTime())
    statKeys.push(stats.size)
  }

  // Perhaps we should not use basename to infer the file name
  return ['path', relativePath]
    .concat(statKeys)
    .concat(childKeys)
}

exports.hashStats = hashStats
function hashStats (stats, path) {
  // Both stats and path can be null
  var keys = []
  if (stats != null) {
    keys.push(stats.mode, stats.size, stats.mtime.getTime())
  }
  if (path != null) {
    keys.push(path)
  }
  return hashStrings(keys)
}

exports.hashStrings = hashStrings
function hashStrings (strings) {
  var joinedStrings = strings.join('\x00')
  return crypto.createHash('md5').update(joinedStrings).digest('hex')
}

// If src is a file, dest is a file name. If src is a directory, dest is the
// directory that the contents of src will be copied into.
//
// This function refuses to overwrite files, but accepts if directories exist
// already.
//
// This does not resolve symlinks. It is not clear whether it should.
//
// Note that unlike cp(1), we do not special-case if dest is an existing
// directory, because relying on things to exist when we're in the middle of
// assembling a new tree is too brittle.
//
// This function should be avoided in favor of
// https://github.com/broccolijs/node-copy-dereference
//
// copy-dereference differs from copyRecursivelySync in that it dereferences
// symlinks. copy-dereference also won't call mkdirp to create the target
// directory (or the parent directory of the target file), which makes it
// stricter: (1) It's not OK for the target directory to exist already, and
// (2) missing parent directories will not automatically be created.
exports.copyRecursivelySync = copyRecursivelySync
function copyRecursivelySync (src, dest, _mkdirp) {
  if (_mkdirp == null) _mkdirp = true
  // Note: We could try readdir'ing and catching ENOTDIR exceptions, but that
  // is 3x slower than stat'ing in the common case that we have a file.
  var srcStats = fs.lstatSync(src)
  if (srcStats.isDirectory()) {
    mkdirp.sync(dest)
    var entries = fs.readdirSync(src).sort()
    for (var i = 0; i < entries.length; i++) {
      // Set _mkdirp to false when recursing to avoid extra mkdirp calls.
      copyRecursivelySync(src + '/' + entries[i], dest + '/' + entries[i], false)
    }
  } else {
    if (_mkdirp) {
      mkdirp.sync(path.dirname(dest))
    }
    copyPreserveSync(src, dest, srcStats)
  }
}

// srcStats is optional; use it as an optimization to avoid double stats
// This function refuses to overwrite files.
exports.copyPreserveSync = copyPreserveSync
function copyPreserveSync (src, dest, srcStats) {
  if (srcStats == null) srcStats = fs.lstatSync(src)
  if (srcStats.isFile()) {
    var content = fs.readFileSync(src)
    fs.writeFileSync(dest, content, { flag: 'wx' })
    fs.utimesSync(dest, srcStats.atime, srcStats.mtime)
  } else if (srcStats.isSymbolicLink()) {
    fs.symlinkSync(fs.readlinkSync(src), dest)
    // We cannot update the atime/mtime of a symlink yet:
    // https://github.com/joyent/node/issues/2142
  } else {
    throw new Error('Unexpected file type for ' + src)
  }
}

exports.linkRecursivelySync = linkRecursivelySync
function linkRecursivelySync () {
  throw new Error('linkRecursivelySync has been removed; use copyRecursivelySync instead (note: it does not overwrite)')
}

exports.linkAndOverwrite = linkAndOverwrite
function linkAndOverwrite () {
  throw new Error('linkAndOverwrite has been removed; use copyPreserveSync instead (note: it does not overwrite)')
}

exports.assertAbsolutePaths = assertAbsolutePaths
function assertAbsolutePaths (paths) {
  for (var i = 0; i < paths.length; i++) {
    if (paths[i][0] !== '/') {
      throw new Error('Path must be absolute: "' + paths[i] + '"')
    }
  }
}

// Multi-glob with reasonable defaults, so APIs all behave the same
exports.multiGlob = multiGlob
function multiGlob (globs, globOptions) {
  if (!Array.isArray(globs)) {
    throw new TypeError("multiGlob's first argument must be an array");
  }
  var options = {
    nomount: true,
    strict: true
  }
  for (var key in globOptions) {
    if (globOptions.hasOwnProperty(key)) {
      options[key] = globOptions[key]
    }
  }

  var pathSet = {}
  var paths = []
  for (var i = 0; i < globs.length; i++) {
    if (options.nomount && globs[i][0] === '/') {
      throw new Error('Absolute paths not allowed (`nomount` is enabled): ' + globs[i])
    }
    var matches = glob.sync(globs[i], options)
    if (matches.length === 0) {
      throw new Error('Path or pattern "' + globs[i] + '" did not match any files')
    }
    for (var j = 0; j < matches.length; j++) {
      if (!pathSet[matches[j]]) {
        pathSet[matches[j]] = true
        paths.push(matches[j])
      }
    }
  }
  return paths
}

// This function is deprecated in favor of
// https://github.com/broccolijs/node-symlink-or-copy
exports.symlinkOrCopyPreserveSync = symlinkOrCopyPreserveSync
function symlinkOrCopyPreserveSync (sourcePath, destPath) {
  if (isWindows) {
    copyRecursivelySync(sourcePath, destPath)
  } else {
    if (fs.lstatSync(sourcePath).isSymbolicLink()) {
      // When we encounter symlinks, follow them. This prevents indirection
      // from growing out of control. Note: At the moment `realpath` on Node
      // is 70x slower than native: https://github.com/joyent/node/issues/7902
      sourcePath = fs.realpathSync(sourcePath)
    } else if (sourcePath[0] !== pathSep) {
      sourcePath = process.cwd() + pathSep + sourcePath
    }

    fs.symlinkSync(sourcePath, destPath)
  }
}
<|endoftext|>