<commit_before>/*
node-webkit 0.11.6 process.versions:
chromium: "38.0.2125.104"
http_parser: "2.2"
modules: "14"
node: "0.11.13-pre"
node-webkit: "0.11.6"
nw-commit-id: "ec3b4f4-d8ecacd-e5d35ef-f2f89e2-d9a9d39-cdd879e"
openssl: "1.0.1f"
uv: "0.11.22"
v8: "3.28.71.2"
zlib: "1.2.5"

nw 0.12.0-alpha2 process.versions:
chromium: "41.0.2236.2"
http_parser: "2.3"
modules: "14"
node: "1.0.0"
node-webkit: "0.12.0-alpha2"
nw-commit-id: "e0d5ce6-d017875-34492e5-2e978ac-1116f2c-fd87c8d"
openssl: "1.0.1j"
uv: "1.2.0"
v8: "3.31.31"
zlib: "1.2.5"
*/

console.log('Starting K3, in testK3/index.js');

// Load native UI library
var gui = require('nw.gui');

// Add copy & paste support on mac
if (process.platform === "darwin") {
  var mb = new gui.Menu({type: 'menubar'});
  mb.createMacBuiltin('Kipling', {
    hideEdit: false,
  });
  gui.Window.get().menu = mb;
}

// Get an instance of the startup window
var win = gui.Window.get();

// perform other requires
var path = require('path');
var q = require('q');

global.ljswitchboard = {};

function initIOManager() {
	var io_manager = require('../../ljswitchboard-io_manager');
	var io_interface = io_manager.io_interface();

	console.log(Object.keys(io_manager));
	console.log('initializing interface');
	io_interface.initialize()
	.then(function(res) {
		console.log('Initialized', res);
	}, function(err) {
		console.log('failed', err);
	});
}
// Require the package loader
// Load the local repository for development purposes
// console.log('Loading Dev version of the package_loader');
// var package_loader = require('../../ljswitchboard-package_loader');
// Load the library from the node_module dirctory:
var package_loader = require('ljswitchboard-package_loader');
var gns = package_loader.getNameSpace();

console.log('Run the command: window_manager.windowManager.managedWindows.kipling.win.show() to force the K3 window to appear.');

// Require persistent_data_manager
var persistent_data_manager = require('./persistent_data_manager');
var persistentDataManager;

// Require and initialize the window_manager
var window_manager = require('ljswitchboard-window_manager');
// Pass the window_manager a reference to the gui object
window_manager.configure({
	'gui': require('nw.gui')
});

// Add the -builder window to the window_manager to have it be managed.
var initialAppVisibility = false;
if(gui.App.manifest.window.show) {
	initialAppVisibility = true;
}
window_manager.addWindow({
	'name': 'main',
	'win': win,
	'initialVisibility': initialAppVisibility,
	'title': 'mainWindow'
});

// Attach to the "Quitting Application" event
window_manager.on(window_manager.eventList.QUITTING_APPLICATION, function() {
	console.log('Quitting Application');
	gui.App.quit();
});

var plEvents = package_loader.eventList;

var show3DevTools = function() {
	window_manager.windowManager.managedWindows.kipling.win.showDevTools();
}

// Define the splash screen updater
var createSplashScreenUpdater = function() {
	this.splashScreenObj = null;
	this.titleTextObj = null;

	this.saveDocumentReference = function(innerDocument) {
		self.splashScreenObj = innerDocument;
		var bodyEl = self.splashScreenObj.body;
		var splashScreenObj = bodyEl.children[0];
		var bottomLeftObj = splashScreenObj.children[0];
		self.titleTextObj = bottomLeftObj.children[0];
	};

	this.update = function(message) {
		console.log('Updating message to:', message);
		try {
			self.titleTextObj.textContent = message.toString();
		} catch(err) {
			// Error setting the item's message.
			console.error('Error setting splash screen message', err);
		}
	};
	var self = this;
};
var splashScreenUpdater = new createSplashScreenUpdater();

// Attach various event listeners to the package_loader
// package_loader.on('opened_window', windowManager.addWindow);
package_loader.on('loaded_package', function(packageName) {
	// console.log('Loaded New Package', packageName);
});
package_loader.on('set_package', function(packageName) {
	// console.log('Saved New Package', packageName);
});

package_loader.on('starting_extraction', function(packageInfo) {
	console.log('Extracting package', packageInfo.name, splashScreenUpdater);
	splashScreenUpdater.update('Extracting ' + packageInfo.name);
});
package_loader.on('finished_extraction', function(packageInfo) {
	console.log('Finished Extracting package', packageInfo.name, splashScreenUpdater);
	splashScreenUpdater.update('Finished Extracting ' + packageInfo.name);
});

package_loader.on('failed_to_initialize_package_manager', function(message) {
	console.log('Failed to initialize pagkage_manager', message);
	splashScreenUpdater.update(message.toString());
});
package_loader.on('failed_to_load_managed_package', function(message) {
	console.warn('Message:', message);
});

var startDir = require('./get_cwd').startDir;
var startInfo = require('./get_cwd').startInfo;

var rootPackages = [{
		'name': 'req',
		'loadMethod': 'set',
		'ref': require('ljswitchboard-require')
	}, {
		'name': 'ljm_driver_checker',
		'loadMethod': 'set',
		'ref': require('ljswitchboard-ljm_driver_checker')
	}, {
		'name': 'win',
		'loadMethod': 'set',
		'ref': win
	}, {
		'name': 'gui',
		'loadMethod': 'set',
		'ref': require('nw.gui')
	}, {
		'name': 'window_manager',
		'loadMethod': 'set',
		'ref': window_manager
	}, {
		'name': 'splash_screen',
		'loadMethod': 'set',
		'ref': splashScreenUpdater
	}, {
		'name': 'info',
		'loadMethod': 'set',
		'ref': require('./get_cwd')
	}
];

var secondaryPackages = [
	{
		// 'name': 'ljswitchboard-static_files',
		'name': 'static_files',
		'folderName': 'ljswitchboard-static_files',
		'loadMethod': 'managed',
		'forceRefresh': false,
		'directLoad': true,
		'locations': [
			// Add path to files for development purposes, out of a repo.
			path.join(startDir, '..', 'ljswitchboard-static_files'),

			// If those files aren't found, check the node_modules directory of
			// the current application for upgrades.
			path.join(startDir, 'node_modules', 'ljswitchboard-static_files'),

			// For non-development use, check the LabJack folder/K3/downloads
			// file for upgrades.
			// TODO: Add this directory

			// If all fails, check the starting directory of the process for the
			// zipped files originally distributed with the application.
			path.join(startDir, 'ljswitchboard-static_files.zip')
		]
	},
	{
		// 'name': 'ljswitchboard-core',
		'name': 'core',
		'folderName': 'ljswitchboard-core',
		'loadMethod': 'managed',
		'forceRefresh': false,
		'startApp': false,
		'showDevTools': true,
		'directLoad': true,
		'locations': [
			// Add path to files for development purposes, out of a repo.
			path.join(startDir, '..', 'ljswitchboard-core'),

			// If those files aren't found, check the node_modules directory of
			// the current application for upgrades.
			path.join(startDir, 'node_modules', 'ljswitchboard-core'),

			// For non-development use, check the LabJack folder/K3/downloads
			// file for upgrades.
			// TODO: Add this directory

			// If all fails, check the starting directory of the process for the
			// zipped files originally distributed with the application.
			path.join(startDir, 'ljswitchboard-core.zip')
		]
	}
];

var errorMessage = {
	'core': "Make sure that you download and installed the LabJack's main installer",
	'persistentData': "Failed to initialize or re-initialize K3's persistent data"
};

var errorHandler = function(err) {
	var defered = q.defer();
	console.log('Error encountered', err);
	defered.reject(err);
	return defered.promise;
};

var initializeProgram = function() {
	var defered = q.defer();

	// Configure the splashScreenUpdater
	splashScreenUpdater.saveDocumentReference(document);

	// Show the window's dev tools
	// win.showDevTools();

	// Perform synchronous loading of modules:
	rootPackages.forEach(function(packageInfo) {
		package_loader.loadPackage(packageInfo);
	});

	// Perform async operations
	global.ljswitchboard.ljm_driver_checker.verifyCoreInstall()
	.then(function(res) {
		console.log('Core Req Check', res);
		// Make sure that the LabJack directory has been created
		if(res.overallResult) {
			var lj_folder_path = res['LabJack folder'].path;

			// Save to the global scope
			global.ljswitchboard.labjackFolderPath = lj_folder_path;
			if(gui.App.manifest.test) {
				persistentDataManager = new persistent_data_manager.create(
					lj_folder_path,
					gui.App.manifest.testPersistentDataFolderName,
					gui.App.manifest.persistentDataVersion
				);
			} else {
				persistentDataManager = new persistent_data_manager.create(
					lj_folder_path,
					gui.App.manifest.persistentDataFolderName,
					gui.App.manifest.persistentDataVersion
				);
			}

			// Save the path to the global scope
			global.ljswitchboard.appDataPath = persistentDataManager.getPath();
			var forceRefresh = gui.App.manifest.forceRefreshOfPersistentData;
			persistentDataManager.init(forceRefresh)
			.then(function(res) {
				console.log('Re-Initialized Data:', res);
				defered.resolve();
			}, function(err) {
				console.log('Failed to initialize data', err);
				defered.reject({'code': 'persistentData', 'data': err});
			});
		} else {
			defered.reject({'code': 'core', 'data': res});
			console.log('Failed core-check', err);
			splashScreenUpdater.update('Failed installation verification');
		}
	}, function(err) {
		console.log('Failed while executing verifyCoreInstall', err);
		splashScreenUpdater.update('Failed to verify installation');
	});
	return defered.promise;
};

var loadSecondaryPackages = function() {
	var defered = q.defer();
	console.log('Loading Secondary Packages');

	// Get the appDataPath
	var appDataPath = global.ljswitchboard.appDataPath;

	// Configure the package_loader with this path
	package_loader.setExtractionPath(appDataPath);

	secondaryPackages.forEach(function(packageInfo) {
		package_loader.loadPackage(packageInfo);
	});
	package_loader.runPackageManager()
	.then(function(packages) {
		console.log('Managed Packages', packages);
		var managedPackageKeyss = Object.keys(packages);
		managedPackageKeyss.forEach(function(managedPackageKey) {
			// Add the managed packages root locations to the req library.
			var baseDir = packages[managedPackageKey].packageInfo.location;
			var extraPaths = [
				'',
				'node_modules',
				'lib',
				path.join('lib', 'node_modules')
			];
			extraPaths.forEach(function(extraPath) {
				var modulesDirToAdd = path.normalize(path.join(baseDir, extraPath));
				global.ljswitchboard.req.addDirectory(modulesDirToAdd);
			});
		});

		// Instruct the window_manager to open any managed nwApps
		window_manager.openManagedApps(packages);

		// Execute test function to proove that io_manager can be used.
		// global.require('../../test.js').runProgram();

	}, function(err) {
		console.log('Failed to run package manager (sp)', err);
		splashScreenUpdater.update('Failed to run package manager (sp)');
	});

	return defered.promise;
};

win.on('loaded', function() {
	console.log('LJSwitchboard Window Loaded!');
	initializeProgram()
	.then(loadSecondaryPackages, errorHandler);
});

// Load the ljswitchboard-core
// var ljswitchboard_core = require('../ljswitchboard-core');
// console.log(ljswitchboard_core);

if(false) {
// Perform a switch based on if this is a test or not.
if(gui.App.manifest.test) {
	// If set to 'test', perform testing code

	// Load the testing window
	// win.window.location = './test/test_ljswitchboard.html';
	console.log('This is a test, starting test window');
	var test_ljswitchboard = gui.Window.open('test_index.html', {
		position: 'center',
		width: 900,
		height: 900
	});

	test_ljswitchboard.on('closed', function() {
		win = null;
	});

	// Detect when a user closes the test_window
	test_ljswitchboard.on('close', function() {
		// Hide the test_ljswitchboard window for improved user feedback.
		this.hide();

		if(win !== null) {
			// Also close the startup window
			win.close(true);
		}

		// After closing the main window, close the test_ljswitchboard window
		this.close(true);
	});
	win.on('close', function() {
		console.log('Close captured');
		// Hide the startup window for improved user feedback.
		this.hide();

		// If the test_ljswitchboard window is still open then close it.
		if(test_ljswitchboard !== null) {
			test_ljswitchboard.close(true);
		}

		// After closing the startup window, close the test_ljswitchboard.
		this.close(true);
	});

} else {
	// If this isn't a test then start ljswitchboard
	var start_ljswitchboard = require('./lib/start_ljswitchboard');
}

}<commit_msg>Fixing log message<commit_after>/*
node-webkit 0.11.6 process.versions:
chromium: "38.0.2125.104"
http_parser: "2.2"
modules: "14"
node: "0.11.13-pre"
node-webkit: "0.11.6"
nw-commit-id: "ec3b4f4-d8ecacd-e5d35ef-f2f89e2-d9a9d39-cdd879e"
openssl: "1.0.1f"
uv: "0.11.22"
v8: "3.28.71.2"
zlib: "1.2.5"

nw 0.12.0-alpha2 process.versions:
chromium: "41.0.2236.2"
http_parser: "2.3"
modules: "14"
node: "1.0.0"
node-webkit: "0.12.0-alpha2"
nw-commit-id: "e0d5ce6-d017875-34492e5-2e978ac-1116f2c-fd87c8d"
openssl: "1.0.1j"
uv: "1.2.0"
v8: "3.31.31"
zlib: "1.2.5"
*/

console.log('Starting K3, in ljswitchboard-splash_screen/lib/index.js');

// Load native UI library
var gui = require('nw.gui');

// Add copy & paste support on mac
if (process.platform === "darwin") {
  var mb = new gui.Menu({type: 'menubar'});
  mb.createMacBuiltin('Kipling', {
    hideEdit: false,
  });
  gui.Window.get().menu = mb;
}

// Get an instance of the startup window
var win = gui.Window.get();

// perform other requires
var path = require('path');
var q = require('q');

global.ljswitchboard = {};

function initIOManager() {
	var io_manager = require('../../ljswitchboard-io_manager');
	var io_interface = io_manager.io_interface();

	console.log(Object.keys(io_manager));
	console.log('initializing interface');
	io_interface.initialize()
	.then(function(res) {
		console.log('Initialized', res);
	}, function(err) {
		console.log('failed', err);
	});
}
// Require the package loader
// Load the local repository for development purposes
// console.log('Loading Dev version of the package_loader');
// var package_loader = require('../../ljswitchboard-package_loader');
// Load the library from the node_module dirctory:
var package_loader = require('ljswitchboard-package_loader');
var gns = package_loader.getNameSpace();

console.log('Run the command: window_manager.windowManager.managedWindows.kipling.win.show() to force the K3 window to appear.');

// Require persistent_data_manager
var persistent_data_manager = require('./persistent_data_manager');
var persistentDataManager;

// Require and initialize the window_manager
var window_manager = require('ljswitchboard-window_manager');
// Pass the window_manager a reference to the gui object
window_manager.configure({
	'gui': require('nw.gui')
});

// Add the -builder window to the window_manager to have it be managed.
var initialAppVisibility = false;
if(gui.App.manifest.window.show) {
	initialAppVisibility = true;
}
window_manager.addWindow({
	'name': 'main',
	'win': win,
	'initialVisibility': initialAppVisibility,
	'title': 'mainWindow'
});

// Attach to the "Quitting Application" event
window_manager.on(window_manager.eventList.QUITTING_APPLICATION, function() {
	console.log('Quitting Application');
	gui.App.quit();
});

var plEvents = package_loader.eventList;

var show3DevTools = function() {
	window_manager.windowManager.managedWindows.kipling.win.showDevTools();
}

// Define the splash screen updater
var createSplashScreenUpdater = function() {
	this.splashScreenObj = null;
	this.titleTextObj = null;

	this.saveDocumentReference = function(innerDocument) {
		self.splashScreenObj = innerDocument;
		var bodyEl = self.splashScreenObj.body;
		var splashScreenObj = bodyEl.children[0];
		var bottomLeftObj = splashScreenObj.children[0];
		self.titleTextObj = bottomLeftObj.children[0];
	};

	this.update = function(message) {
		console.log('Updating message to:', message);
		try {
			self.titleTextObj.textContent = message.toString();
		} catch(err) {
			// Error setting the item's message.
			console.error('Error setting splash screen message', err);
		}
	};
	var self = this;
};
var splashScreenUpdater = new createSplashScreenUpdater();

// Attach various event listeners to the package_loader
// package_loader.on('opened_window', windowManager.addWindow);
package_loader.on('loaded_package', function(packageName) {
	// console.log('Loaded New Package', packageName);
});
package_loader.on('set_package', function(packageName) {
	// console.log('Saved New Package', packageName);
});

package_loader.on('starting_extraction', function(packageInfo) {
	console.log('Extracting package', packageInfo.name, splashScreenUpdater);
	splashScreenUpdater.update('Extracting ' + packageInfo.name);
});
package_loader.on('finished_extraction', function(packageInfo) {
	console.log('Finished Extracting package', packageInfo.name, splashScreenUpdater);
	splashScreenUpdater.update('Finished Extracting ' + packageInfo.name);
});

package_loader.on('failed_to_initialize_package_manager', function(message) {
	console.log('Failed to initialize pagkage_manager', message);
	splashScreenUpdater.update(message.toString());
});
package_loader.on('failed_to_load_managed_package', function(message) {
	console.warn('Message:', message);
});

var startDir = require('./get_cwd').startDir;
var startInfo = require('./get_cwd').startInfo;

var rootPackages = [{
		'name': 'req',
		'loadMethod': 'set',
		'ref': require('ljswitchboard-require')
	}, {
		'name': 'ljm_driver_checker',
		'loadMethod': 'set',
		'ref': require('ljswitchboard-ljm_driver_checker')
	}, {
		'name': 'win',
		'loadMethod': 'set',
		'ref': win
	}, {
		'name': 'gui',
		'loadMethod': 'set',
		'ref': require('nw.gui')
	}, {
		'name': 'window_manager',
		'loadMethod': 'set',
		'ref': window_manager
	}, {
		'name': 'splash_screen',
		'loadMethod': 'set',
		'ref': splashScreenUpdater
	}, {
		'name': 'info',
		'loadMethod': 'set',
		'ref': require('./get_cwd')
	}
];

var secondaryPackages = [
	{
		// 'name': 'ljswitchboard-static_files',
		'name': 'static_files',
		'folderName': 'ljswitchboard-static_files',
		'loadMethod': 'managed',
		'forceRefresh': false,
		'directLoad': true,
		'locations': [
			// Add path to files for development purposes, out of a repo.
			path.join(startDir, '..', 'ljswitchboard-static_files'),

			// If those files aren't found, check the node_modules directory of
			// the current application for upgrades.
			path.join(startDir, 'node_modules', 'ljswitchboard-static_files'),

			// For non-development use, check the LabJack folder/K3/downloads
			// file for upgrades.
			// TODO: Add this directory

			// If all fails, check the starting directory of the process for the
			// zipped files originally distributed with the application.
			path.join(startDir, 'ljswitchboard-static_files.zip')
		]
	},
	{
		// 'name': 'ljswitchboard-core',
		'name': 'core',
		'folderName': 'ljswitchboard-core',
		'loadMethod': 'managed',
		'forceRefresh': false,
		'startApp': false,
		'showDevTools': true,
		'directLoad': true,
		'locations': [
			// Add path to files for development purposes, out of a repo.
			path.join(startDir, '..', 'ljswitchboard-core'),

			// If those files aren't found, check the node_modules directory of
			// the current application for upgrades.
			path.join(startDir, 'node_modules', 'ljswitchboard-core'),

			// For non-development use, check the LabJack folder/K3/downloads
			// file for upgrades.
			// TODO: Add this directory

			// If all fails, check the starting directory of the process for the
			// zipped files originally distributed with the application.
			path.join(startDir, 'ljswitchboard-core.zip')
		]
	}
];

var errorMessage = {
	'core': "Make sure that you download and installed the LabJack's main installer",
	'persistentData': "Failed to initialize or re-initialize K3's persistent data"
};

var errorHandler = function(err) {
	var defered = q.defer();
	console.log('Error encountered', err);
	defered.reject(err);
	return defered.promise;
};

var initializeProgram = function() {
	var defered = q.defer();

	// Configure the splashScreenUpdater
	splashScreenUpdater.saveDocumentReference(document);

	// Show the window's dev tools
	// win.showDevTools();

	// Perform synchronous loading of modules:
	rootPackages.forEach(function(packageInfo) {
		package_loader.loadPackage(packageInfo);
	});

	// Perform async operations
	global.ljswitchboard.ljm_driver_checker.verifyCoreInstall()
	.then(function(res) {
		console.log('Core Req Check', res);
		// Make sure that the LabJack directory has been created
		if(res.overallResult) {
			var lj_folder_path = res['LabJack folder'].path;

			// Save to the global scope
			global.ljswitchboard.labjackFolderPath = lj_folder_path;
			if(gui.App.manifest.test) {
				persistentDataManager = new persistent_data_manager.create(
					lj_folder_path,
					gui.App.manifest.testPersistentDataFolderName,
					gui.App.manifest.persistentDataVersion
				);
			} else {
				persistentDataManager = new persistent_data_manager.create(
					lj_folder_path,
					gui.App.manifest.persistentDataFolderName,
					gui.App.manifest.persistentDataVersion
				);
			}

			// Save the path to the global scope
			global.ljswitchboard.appDataPath = persistentDataManager.getPath();
			var forceRefresh = gui.App.manifest.forceRefreshOfPersistentData;
			persistentDataManager.init(forceRefresh)
			.then(function(res) {
				console.log('Re-Initialized Data:', res);
				defered.resolve();
			}, function(err) {
				console.log('Failed to initialize data', err);
				defered.reject({'code': 'persistentData', 'data': err});
			});
		} else {
			defered.reject({'code': 'core', 'data': res});
			console.log('Failed core-check', err);
			splashScreenUpdater.update('Failed installation verification');
		}
	}, function(err) {
		console.log('Failed while executing verifyCoreInstall', err);
		splashScreenUpdater.update('Failed to verify installation');
	});
	return defered.promise;
};

var loadSecondaryPackages = function() {
	var defered = q.defer();
	console.log('Loading Secondary Packages');

	// Get the appDataPath
	var appDataPath = global.ljswitchboard.appDataPath;

	// Configure the package_loader with this path
	package_loader.setExtractionPath(appDataPath);

	secondaryPackages.forEach(function(packageInfo) {
		package_loader.loadPackage(packageInfo);
	});
	package_loader.runPackageManager()
	.then(function(packages) {
		console.log('Managed Packages', packages);
		var managedPackageKeyss = Object.keys(packages);
		managedPackageKeyss.forEach(function(managedPackageKey) {
			// Add the managed packages root locations to the req library.
			var baseDir = packages[managedPackageKey].packageInfo.location;
			var extraPaths = [
				'',
				'node_modules',
				'lib',
				path.join('lib', 'node_modules')
			];
			extraPaths.forEach(function(extraPath) {
				var modulesDirToAdd = path.normalize(path.join(baseDir, extraPath));
				global.ljswitchboard.req.addDirectory(modulesDirToAdd);
			});
		});

		// Instruct the window_manager to open any managed nwApps
		window_manager.openManagedApps(packages);

		// Execute test function to proove that io_manager can be used.
		// global.require('../../test.js').runProgram();

	}, function(err) {
		console.log('Failed to run package manager (sp)', err);
		splashScreenUpdater.update('Failed to run package manager (sp)');
	});

	return defered.promise;
};

win.on('loaded', function() {
	console.log('LJSwitchboard Window Loaded!');
	initializeProgram()
	.then(loadSecondaryPackages, errorHandler);
});

// Load the ljswitchboard-core
// var ljswitchboard_core = require('../ljswitchboard-core');
// console.log(ljswitchboard_core);

if(false) {
// Perform a switch based on if this is a test or not.
if(gui.App.manifest.test) {
	// If set to 'test', perform testing code

	// Load the testing window
	// win.window.location = './test/test_ljswitchboard.html';
	console.log('This is a test, starting test window');
	var test_ljswitchboard = gui.Window.open('test_index.html', {
		position: 'center',
		width: 900,
		height: 900
	});

	test_ljswitchboard.on('closed', function() {
		win = null;
	});

	// Detect when a user closes the test_window
	test_ljswitchboard.on('close', function() {
		// Hide the test_ljswitchboard window for improved user feedback.
		this.hide();

		if(win !== null) {
			// Also close the startup window
			win.close(true);
		}

		// After closing the main window, close the test_ljswitchboard window
		this.close(true);
	});
	win.on('close', function() {
		console.log('Close captured');
		// Hide the startup window for improved user feedback.
		this.hide();

		// If the test_ljswitchboard window is still open then close it.
		if(test_ljswitchboard !== null) {
			test_ljswitchboard.close(true);
		}

		// After closing the startup window, close the test_ljswitchboard.
		this.close(true);
	});

} else {
	// If this isn't a test then start ljswitchboard
	var start_ljswitchboard = require('./lib/start_ljswitchboard');
}

}<|endoftext|>


<commit_before>goog.provide('og.ShapeHandler');

goog.require('og.shape.BaseShape');
goog.require('og.shape.Sphere');
goog.require('og.shaderProgram.shape_wl');
goog.require('og.shaderProgram.shape_nl');
//goog.require('og.shaderProgram.shapePicking');

og.ShapeHandler = function (entityCollection) {

    /**
     * Picking rendering option.
     * @public
     * @type {boolean}
     */
    this.pickingEnabled = true;

    this._entityCollection = entityCollection;

    this._renderer = null;

    this._shapes = [];

    this.__staticId = og.ShapeHandler.staticCounter++;
};

og.ShapeHandler.staticCounte = 0;

og.ShapeHandler.prototype._initShaderProgram = function () {
    if (this._renderer.handler) {
        if (!this._renderer.handler.shaderPrograms.shape_nl) {
            this._renderer.handler.addShaderProgram(og.shaderProgram.shape_nl());
        }
        if (!this._renderer.handler.shaderPrograms.shape_wl) {
            this._renderer.handler.addShaderProgram(og.shaderProgram.shape_wl());
        }
        //if (!this._renderer.handler.shaderPrograms.shapePicking) {
        //    this._renderer.handler.addShaderProgram(og.shaderProgram.shapePicking());
        //}
    }
};

og.ShapeHandler.prototype.setRenderNode = function (renderNode) {
    this._renderer = renderNode.renderer;
    this._initShaderProgram()
    for (var i = 0; i < this._shapes.length; i++) {
        this._shapes[i].setRenderNode(renderNode);
    }
};

og.ShapeHandler.prototype.add = function (shape) {
    if (shape._handlerIndex == -1) {
        shape._handler = this;
        shape._handlerIndex = this._shapes.length;
        this._shapes.push(shape);
        this._entityCollection && this._entityCollection.renderNode && shape.setRenderNode(this._entityCollection.renderNode);
    }
};

og.ShapeHandler.prototype.remove = function (shape) {

};

og.ShapeHandler.prototype.draw = function () {
    var i = this._shapes.length;
    while (i--) {
        this._shapes[i].draw();
    }
};

og.ShapeHandler.prototype.drawPicking = function () {
    if (this.pickingEnabled) {
    }
};

og.ShapeHandler.prototype.clear = function () {

};<commit_msg>Shape id bug fixed.<commit_after>goog.provide('og.ShapeHandler');

goog.require('og.shape.BaseShape');
goog.require('og.shape.Sphere');
goog.require('og.shaderProgram.shape_wl');
goog.require('og.shaderProgram.shape_nl');
//goog.require('og.shaderProgram.shapePicking');

og.ShapeHandler = function (entityCollection) {

    /**
     * Picking rendering option.
     * @public
     * @type {boolean}
     */
    this.pickingEnabled = true;

    this._entityCollection = entityCollection;

    this._renderer = null;

    this._shapes = [];

    this.__staticId = og.ShapeHandler.staticCounter++;
};

og.ShapeHandler.staticCounter = 0;

og.ShapeHandler.prototype._initShaderProgram = function () {
    if (this._renderer.handler) {
        if (!this._renderer.handler.shaderPrograms.shape_nl) {
            this._renderer.handler.addShaderProgram(og.shaderProgram.shape_nl());
        }
        if (!this._renderer.handler.shaderPrograms.shape_wl) {
            this._renderer.handler.addShaderProgram(og.shaderProgram.shape_wl());
        }
        //if (!this._renderer.handler.shaderPrograms.shapePicking) {
        //    this._renderer.handler.addShaderProgram(og.shaderProgram.shapePicking());
        //}
    }
};

og.ShapeHandler.prototype.setRenderNode = function (renderNode) {
    this._renderer = renderNode.renderer;
    this._initShaderProgram()
    for (var i = 0; i < this._shapes.length; i++) {
        this._shapes[i].setRenderNode(renderNode);
    }
};

og.ShapeHandler.prototype.add = function (shape) {
    if (shape._handlerIndex == -1) {
        shape._handler = this;
        shape._handlerIndex = this._shapes.length;
        this._shapes.push(shape);
        this._entityCollection && this._entityCollection.renderNode && shape.setRenderNode(this._entityCollection.renderNode);
    }
};

og.ShapeHandler.prototype.remove = function (shape) {

};

og.ShapeHandler.prototype.draw = function () {
    var i = this._shapes.length;
    while (i--) {
        this._shapes[i].draw();
    }
};

og.ShapeHandler.prototype.drawPicking = function () {
    if (this.pickingEnabled) {
    }
};

og.ShapeHandler.prototype.clear = function () {

};<|endoftext|>


<commit_before>
/**
 * Library dependencies.
 */

var request = require('superagent');

/**
 * Expose a `Postmates` client.
 */

module.exports = Postmates;

/**
 * Initialize a new `Postmates` with Postmates developer credentials.
 */

function Postmates(customerId, apiKey){
  if (!(this instanceof Postmates)) return new Postmates(customerId, apiKey);
  if (!customerId || customerId.length === 0)
    return throw "Need to provide customerId.";
  if (!apiKey || apiKey.length === 0) return throw "Need to provide API key.";
  this.customerId = customerId;
  this.apiKey = apiKey;
  this.host = 'https://api.postmates.com/v1/customers/' + customerId + '/';
}

/**
 * Request a Delivery quote.
 *
 * @param {Object} delivery
 *   @property {String} pickup_address
 *   @property {String} dropoff_address
 * @param {Function} fn (optional)
 */

Postmates.prototype.quote = function(delivery, fn) {
  this._post('delivery_quotes', delivery, fn);
};

/**
 * Create a Delivery.
 *
 * @param {Object} delivery
 *   @property {String} manifest
 *   @property {String} pickup_name
 *   @property {String} pickup_address
 *   @property {String} pickup_phone_number
 *   @property {String} pickup_business_name
 *   @property {String} pickup_notes
 *   @property {String} dropoff_name
 *   @property {String} dropoff_address
 *   @property {String} dropoff_phone_number
 *   @property {String} dropoff_business_name
 *   @property {String} dropoff_notes
 *   @property {Integer} quote_id
 * @param {Function} fn (optional)
 */

Postmates.prototype.new = function(delivery, fn) {
  this._post('deliveries', delivery, fn);
};

/**
 * Get Delivery details.
 *
 * @param {String} id
 * @param {Function} fn (optional)
 */

Postmates.prototype.get = function(id, fn) {
  this._get('deliveries/' + id, fn);
};

/**
 * List all Deliveries.
 *
 * @param {String} filter (optional)
 * @param {Function} fn (optional)
 */

Postmates.prototype.list = function(filter, fn) {
  var path = 'deliveries/';
  if (filter) path += '?filter=' + filter;
  this._get(path, fn);
};

/**
 * Cancel a Delivery.
 *
 * @param {String} id
 * @param {Function} fn (optional)
 */

Postmates.prototype.cancel = function(id, fn) {
  this._post('deliveries/' + id + '/cancel', null, fn);
};

/**
 * Private function to form POST request.
 *
 * @param {String} path
 * @param {Object} data
 * @param {Function} fn (optional)
 */

Postmates.prototype._post = function(path, data, fn) {
  request
    .auth(this.apiKey, '')
    .post(this.host + path)
    .send(data)
    .end(fn);
};

/**
 * Private function to form GET request.
 *
 * @param {String} path
 * @param {Function} fn (optional)
 */

Postmates.prototype._get = function(path, fn) {
  request
    .auth(this.apiKey, '')
    .get(this.host + path)
    .end(fn);
};
<commit_msg>added set POST type to form urlencoded<commit_after>
/**
 * Library dependencies.
 */

var request = require('superagent');

/**
 * Expose a `Postmates` client.
 */

module.exports = Postmates;

/**
 * Initialize a new `Postmates` with Postmates developer credentials.
 */

function Postmates(customerId, apiKey){
  if (!(this instanceof Postmates)) return new Postmates(customerId, apiKey);
  if (!customerId || customerId.length === 0)
    return throw "Need to provide customerId.";
  if (!apiKey || apiKey.length === 0) return throw "Need to provide API key.";
  this.customerId = customerId;
  this.apiKey = apiKey;
  this.host = 'https://api.postmates.com/v1/customers/' + customerId + '/';
}

/**
 * Request a Delivery quote.
 *
 * @param {Object} delivery
 *   @property {String} pickup_address
 *   @property {String} dropoff_address
 * @param {Function} fn (optional)
 */

Postmates.prototype.quote = function(delivery, fn) {
  this._post('delivery_quotes', delivery, fn);
};

/**
 * Create a Delivery.
 *
 * @param {Object} delivery
 *   @property {String} manifest
 *   @property {String} pickup_name
 *   @property {String} pickup_address
 *   @property {String} pickup_phone_number
 *   @property {String} pickup_business_name
 *   @property {String} pickup_notes
 *   @property {String} dropoff_name
 *   @property {String} dropoff_address
 *   @property {String} dropoff_phone_number
 *   @property {String} dropoff_business_name
 *   @property {String} dropoff_notes
 *   @property {Integer} quote_id
 * @param {Function} fn (optional)
 */

Postmates.prototype.new = function(delivery, fn) {
  this._post('deliveries', delivery, fn);
};

/**
 * Get Delivery details.
 *
 * @param {String} id
 * @param {Function} fn (optional)
 */

Postmates.prototype.get = function(id, fn) {
  this._get('deliveries/' + id, fn);
};

/**
 * List all Deliveries.
 *
 * @param {String} filter (optional)
 * @param {Function} fn (optional)
 */

Postmates.prototype.list = function(filter, fn) {
  var path = 'deliveries/';
  if (filter) path += '?filter=' + filter;
  this._get(path, fn);
};

/**
 * Cancel a Delivery.
 *
 * @param {String} id
 * @param {Function} fn (optional)
 */

Postmates.prototype.cancel = function(id, fn) {
  this._post('deliveries/' + id + '/cancel', null, fn);
};

/**
 * Private function to form POST request.
 *
 * @param {String} path
 * @param {Object} data
 * @param {Function} fn (optional)
 */

Postmates.prototype._post = function(path, data, fn) {
  request
    .auth(this.apiKey, '')
    .type('form')
    .post(this.host + path)
    .send(data)
    .end(fn);
};

/**
 * Private function to form GET request.
 *
 * @param {String} path
 * @param {Function} fn (optional)
 */

Postmates.prototype._get = function(path, fn) {
  request
    .auth(this.apiKey, '')
    .get(this.host + path)
    .end(fn);
};
<|endoftext|>


<commit_before>import child_process from 'child_process';
export default function sign(caps) {

  /*
   * unsign package
   * zip -d <path/to/apk.apk> META-INF/\*
   *
   * sign package
   * jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <path/to/signkey> <path/to/apk.apk> alias_name
   *
   * zipalign
   * zipalign -v 4 <path/to/signed/apk.apk> <output.apk>
   */

}
<commit_msg>andoird-sign module beta<commit_after>import child_process from 'child_process';
import fs from 'fs';
import fop from 'fop';

export default function sign(settings) {

  settings.verbose = settings.verbose || false;

  let instance = {};

  instance.error = (err) => {
    return err;
  }

  instance.validate = (settings) => {

    if(settings.verbose) console.log("Validating settings");

    // check input apk path
    if(settings.apk == undefined || settings.apk == "")
      return new Error("APK path not defined");

    if(fs.accessSync(settings.apk, fs.R_OK) != undefined)
      return new Error("Cannot access APK path");

    // check signkey path
    if(settings.signkey == undefined || settings.signkey == "")
      return new Error("Signkey path not defined");

    if(fs.accessSync(settings.signkey, fs.R_OK) != undefined)
      return new Error("Cannot access Signkey path");

    // check password is defined
    if(settings.password == undefined || settings.password == "")
      return new Error("Password not defined");

    // check alias is defined
    if(settings.alias == undefined || settings.alias == "")
      return new Error("Alias not defined");

    // check outout apk path
    if(settings.output == undefined || settings.output == "")
      return new Error("Output Apk path not defined");

    let folder = fop(settings.output);
    if(fs.accessSync(folder, fs.W_OK) != undefined)
      return new Error("Cannot write on output folder");
  }

  instance.unsign = (settings) => {

    /* STEP 1
     * unsign package
     * zip -d <path/to/apk.apk> META-INF/\*
     */

    if(settings.verbose) console.log("Unsigning package");

    let child = child_process.spawnSync("zip", ["-d", settings.apk, "META-INF/\*"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
  }

  instance.jarSign = (settings) => {

    /* STEP 2
     * jarsign package
     * jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <path/to/signkey> -storepass <password> <path/to/apk.apk> <alias_name>
     */
    let params = ["-verbose", "-sigalg", "SHA1withRSA",
                  "-digestalg", "SHA1",
                  "-keystore", settings.signkey,
                  "-storepass", settings.password,
                  settings.apk, settings.alias];

    if(settings.verbose) console.log("Signing package");

    let child  = child_process.spawnSync("jarsigner", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }

    let output = child.stdout.toString();
    if(output.indexOf("jar signed")!= -1) return true;
    return output;
  }

  instance.verify = (settings) => {

    /* STEP 3
     * verify sign
     * jarsigner -verify -verbose -certs <path/signed.apk>
     */
    let params = ["-verify", "-verbose", "-certs", settings.apk];

    if(settings.verbose) console.log("Verifying package");

    let child  = child_process.spawnSync("jarsigner", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    let output = child.stdout.toString();
    if(output.indexOf("jar verified")!= -1) return true;
    return output;
  }

  instance.zipAlign = (settings) => {

    /* STEP 4
     * zipalign
     * zipalign -v 4 <path/to/signed.apk> <output.apk>
     */
    if(settings.verbose) console.log("Zipping package");

    let params = ["-v", "4", settings.apk, settings.output];

    let child  = child_process.spawnSync("zipalign", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
      return;
    }
    let output = child.stdout.toString();
    if(output.indexOf("Verification succesful") != -1) return true;
    return output;
  }

  instance.sign = (settings) => {

    let err = instance.validate(settings);
    if(err) return instance.error(err);

    try { instance.unsign(settings); }catch(e) {}

    let didSign = instance.jarSign(settings);
    if(didSign !== true) return instance.error(new Error(didSign));

    let isOK = instance.verify(settings);
    if(isOK !== true) return instance.error(new Error(isOK));

    let isZipAligned = instance.zipAlign(settings);
    if(isZipAligned === true) return true;

    return instance.error(new Error(isZipAligned));
  }

  if(!settings) return instance;

  return instance.sign(settings);
}
<|endoftext|>


<commit_before>'use strict';
// Load modules

const Path = require('path');
const Hapi = require('hapi');
const Hoek = require('hoek');
const Items = require('items');
const Joi = require('joi');

// Declare internals

const internals = {};

internals.schema = {
    options: Joi.object({
        relativeTo: Joi.string(),
        preConnections: Joi.func().allow(false),
        preRegister: Joi.func().allow(false)
    }),
    manifest: Joi.object({
        server: Joi.object(),
        connections: Joi.array(Joi.object()),
        registrations: Joi.array().items(Joi.object({
            plugin: [
                Joi.string(),
                Joi.object({ register: Joi.string() }).unknown()
            ],
            options: Joi.object()
        }))
    })
};

exports.compose = function (manifest /*, [options], [callback] */) {

    Hoek.assert(arguments.length <= 3, 'Invalid number of arguments');

    const options = arguments.length === 1 || typeof arguments[1] === 'function' ? {} : arguments[1];
    const callback = typeof arguments[arguments.length - 1] === 'function' ? arguments[arguments.length - 1] : null;

    Joi.assert(options, internals.schema.options, 'Invalid options');
    Joi.assert(manifest, internals.schema.manifest, 'Invalid manifest');

    // Return Promise if no callback provided

    if (!callback) {
        return new Promise((resolve, reject) => {

            exports.compose(manifest, options, (err, server) => {

                if (err) {
                    return reject(err);
                }

                return resolve(server);
            });
        });
    }

    // Create server

    const serverOpts = internals.parseServer(manifest.server || {}, options.relativeTo);
    const server = new Hapi.Server(serverOpts);

    const steps = [];
    steps.push((next) => {

        if (options.preConnections) {
            options.preConnections(server, next);
        }
        else {
            next();
        }
    });

    steps.push((next) => {

        // Load connections

        if (manifest.connections && manifest.connections.length > 0) {
            manifest.connections.forEach((connection) => {

                server.connection(connection);
            });
        }
        else {
            server.connection();
        }

        next();
    });

    steps.push((next) => {

        if (options.preRegister) {
            options.preRegister(server, next);
        }
        else {
            next();
        }
    });

    steps.push((next) => {

        // Load registrations

        if (manifest.registrations) {
            const registrations = manifest.registrations.map((reg) => {

                return {
                    plugin: internals.parsePlugin(reg.plugin, options.relativeTo),
                    options: reg.options || {}
                };
            });
            Items.serial(registrations, (reg, nextRegister) => {

                server.register(reg.plugin, reg.options, nextRegister);
            }, next);
        }
        else {
            next();
        }
    });

    Items.serial(steps, (step, nextStep) => {

        step(nextStep);
    }, (err) => {

        if (err) {
            return Hoek.nextTick(callback)(err);
        }

        Hoek.nextTick(callback)(null, server);
    });
};

internals.parseServer = function (server, relativeTo) {

    if (server.cache) {
        server = Hoek.clone(server);

        const caches = [];
        const config = [].concat(server.cache);
        for (let i = 0; i < config.length; ++i) {
            let item = config[i];
            if (typeof item === 'string') {
                item = { engine: item };
            }

            if (typeof item.engine === 'string') {
                let strategy = item.engine;
                if (relativeTo && strategy[0] === '.') {
                    strategy = Path.join(relativeTo, strategy);
                }

                item.engine = require(strategy);
            }

            caches.push(item);
        }

        server.cache = caches;
    }

    return server;
};

internals.parsePlugin = function (plugin, relativeTo) {

    plugin = Hoek.cloneWithShallow(plugin, ['options']);
    if (typeof plugin === 'string') {
        plugin = { register: plugin };
    }

    let path = plugin.register;
    if (relativeTo && path[0] === '.') {
        path = Path.join(relativeTo, path);
    }

    plugin.register = require(path);
    return plugin;
};
<commit_msg>Refactors Joi.array() to utilize .items() [#83]<commit_after>'use strict';
// Load modules

const Path = require('path');
const Hapi = require('hapi');
const Hoek = require('hoek');
const Items = require('items');
const Joi = require('joi');

// Declare internals

const internals = {};

internals.schema = {
    options: Joi.object({
        relativeTo: Joi.string(),
        preConnections: Joi.func().allow(false),
        preRegister: Joi.func().allow(false)
    }),
    manifest: Joi.object({
        server: Joi.object(),
        connections: Joi.array().items(Joi.object()),
        registrations: Joi.array().items(Joi.object({
            plugin: [
                Joi.string(),
                Joi.object({ register: Joi.string() }).unknown()
            ],
            options: Joi.object()
        }))
    })
};

exports.compose = function (manifest /*, [options], [callback] */) {

    Hoek.assert(arguments.length <= 3, 'Invalid number of arguments');

    const options = arguments.length === 1 || typeof arguments[1] === 'function' ? {} : arguments[1];
    const callback = typeof arguments[arguments.length - 1] === 'function' ? arguments[arguments.length - 1] : null;

    Joi.assert(options, internals.schema.options, 'Invalid options');
    Joi.assert(manifest, internals.schema.manifest, 'Invalid manifest');

    // Return Promise if no callback provided

    if (!callback) {
        return new Promise((resolve, reject) => {

            exports.compose(manifest, options, (err, server) => {

                if (err) {
                    return reject(err);
                }

                return resolve(server);
            });
        });
    }

    // Create server

    const serverOpts = internals.parseServer(manifest.server || {}, options.relativeTo);
    const server = new Hapi.Server(serverOpts);

    const steps = [];
    steps.push((next) => {

        if (options.preConnections) {
            options.preConnections(server, next);
        }
        else {
            next();
        }
    });

    steps.push((next) => {

        // Load connections

        if (manifest.connections && manifest.connections.length > 0) {
            manifest.connections.forEach((connection) => {

                server.connection(connection);
            });
        }
        else {
            server.connection();
        }

        next();
    });

    steps.push((next) => {

        if (options.preRegister) {
            options.preRegister(server, next);
        }
        else {
            next();
        }
    });

    steps.push((next) => {

        // Load registrations

        if (manifest.registrations) {
            const registrations = manifest.registrations.map((reg) => {

                return {
                    plugin: internals.parsePlugin(reg.plugin, options.relativeTo),
                    options: reg.options || {}
                };
            });
            Items.serial(registrations, (reg, nextRegister) => {

                server.register(reg.plugin, reg.options, nextRegister);
            }, next);
        }
        else {
            next();
        }
    });

    Items.serial(steps, (step, nextStep) => {

        step(nextStep);
    }, (err) => {

        if (err) {
            return Hoek.nextTick(callback)(err);
        }

        Hoek.nextTick(callback)(null, server);
    });
};

internals.parseServer = function (server, relativeTo) {

    if (server.cache) {
        server = Hoek.clone(server);

        const caches = [];
        const config = [].concat(server.cache);
        for (let i = 0; i < config.length; ++i) {
            let item = config[i];
            if (typeof item === 'string') {
                item = { engine: item };
            }

            if (typeof item.engine === 'string') {
                let strategy = item.engine;
                if (relativeTo && strategy[0] === '.') {
                    strategy = Path.join(relativeTo, strategy);
                }

                item.engine = require(strategy);
            }

            caches.push(item);
        }

        server.cache = caches;
    }

    return server;
};

internals.parsePlugin = function (plugin, relativeTo) {

    plugin = Hoek.cloneWithShallow(plugin, ['options']);
    if (typeof plugin === 'string') {
        plugin = { register: plugin };
    }

    let path = plugin.register;
    if (relativeTo && path[0] === '.') {
        path = Path.join(relativeTo, path);
    }

    plugin.register = require(path);
    return plugin;
};
<|endoftext|>


<commit_before>/*
 * Simplecrawler - Export interfaces
 * https://github.com/cgiffard/node-simplecrawler
 *
 * Copyright (c) 2011-2015, Christopher Giffard
 *
 */

module.exports = require("./crawler.js");
module.exports.queue = require("./queue.js");
module.exports.cache = require("./cache.js");
<commit_msg>Deprecation warning when using Crawler.crawl method<commit_after>/*
 * Simplecrawler - Export interfaces
 * https://github.com/cgiffard/node-simplecrawler
 *
 * Copyright (c) 2011-2015, Christopher Giffard
 *
 */

module.exports = require("./crawler.js");

module.exports.queue = require("./queue.js");
module.exports.cache = require("./cache.js");

module.exports.crawl = function () {
    throw new Error(
        "Crawler.crawl is deprecated as of version 1.0.0! " +
        "You can now pass a single URL directly to the constructor. " +
        "See the documentation for more details!"
    );
};
<|endoftext|>


<commit_before>"use strict";
var util = require('util'),
  Product = require('./model/product'),
  ApiCore = require('facet-core').ApiCore;

/**
 * Product API constructor
 *
 * @param   {Object}  options   Options object - must contain 'db' (mongoose instance)
 *                              and 'intercom' (EventEmitter instance) keys.
 *
 * @return  {void}
 */
var ProductAPI = function ( options ){
  // call the parent constructor
  ProductAPI.super_.call(this, options);

  // set the model
  this.Model = new Product( this.options );

  // set the router for automation
  this.setupRouterManifest();

  // register the api events
  this.registerEvents();
};

/**
 * Product API inherits from Core API
 */
util.inherits(ProductAPI, ApiCore);

/**
 * Sets up the router manifest for route automation
 *
 * @return   {void}
 */
ProductAPI.prototype.setupRouterManifest = function () {
  // update the router manifest
  this.routerManifest
    .setApiEventType('product')
    .setApiModelId('productId')
    .setRouteBase('/products')
    .setRoutes([
      { verb: 'GET',    route: '/:productId', emit: 'facet:product:findone' },  // GET a single Product by id
      { verb: 'GET',    route: '',            emit: 'facet:product:find'    },  // GET an array of Product objects
      { verb: 'POST',   route: '',            emit: 'facet:product:create'  },  // POST new Product
      { verb: 'PUT',    route: '/:productId', emit: 'facet:product:update'  },  // PUT single/multiple Products
      { verb: 'DELETE', route: '/:productId', emit: 'facet:product:remove'  },  // DELETE a single Product resource
    ])
    .extendRouteErrorMessages({
      container: 'The API user does not have a valid container id.',
      conditions: 'No query conditions were specified',
      query: 'Error querying for product(s): ',
      notFound: 'No product was found.',
      find: 'No product(s) matched your criteria.',
      findOne: 'No product matched your criteria.',
      update: 'No updates were specified.',
      updateMatch: 'No products were updated based on your criteria.',
      create: 'No data supplied for creating new product.',
      createMatch: 'No product was created based on your criteria.',
      remove: 'No data supplied for removing product.',
      removeMatch: 'No product was removed based on your criteria.'
    });
};

/**
 * Registers the Product API event listeners
 *
 * @return   {void}
 */
ProductAPI.prototype.registerEvents = function () {
  var _this = this;

  this.intercom.on('facet:product:data', function handleProductData( data, nodeStack ) {
    data.then( function( productData ) {
      if( null === productData ){
        _this.intercom.emit('facet:response:error', 404, 'Product was not found.');
      }
      else {
        _this.intercom.emit('facet:response:product:data', productData);
      }
    },
    function( err ) {
      _this.intercom.emit('facet:response:error', 404, 'Error querying for product(s): ' + err.message);
    }).end();
  });
  this.intercom.on( 'facet:product:find',     this.find.bind(this)    );
  this.intercom.on( 'facet:product:findone',  this.findOne.bind(this) );
  this.intercom.on( 'facet:product:create',   this.create.bind(this)  );
  this.intercom.on( 'facet:product:update',   this.update.bind(this)  );
  this.intercom.on( 'facet:product:remove',   this.remove.bind(this)  );
};

/**
 * Exports the Product API
 *
 * @type   {Object}
 */
exports = module.exports = ProductAPI;
<commit_msg>Changed the setRoutes function to addRoutes; removed the two ApiCore functions that were being called by the parent constructor<commit_after>"use strict";
var util = require('util'),
  Product = require('./model/product'),
  ApiCore = require('facet-core').ApiCore;

/**
 * Product API constructor
 *
 * @param   {Object}  options   Options object - must contain 'db' (mongoose instance)
 *                              and 'intercom' (EventEmitter instance) keys.
 *
 * @return  {void}
 */
var ProductAPI = function ( options ){

  // call the parent constructor
  ProductAPI.super_.call(this, options);

  // set the model
  this.Model = new Product( this.options );
};

/**
 * Product API inherits from Core API
 */
util.inherits(ProductAPI, ApiCore);

/**
 * Sets up the router manifest for route automation
 *
 * @return   {void}
 */
ProductAPI.prototype.setupRouterManifest = function () {
  // update the router manifest
  this.routerManifest
    .setApiEventType('product')
    .setApiModelId('productId')
    .setRouteBase('/products')
    .addRoutes([
      { verb: 'GET',    route: '/:productId', emit: 'facet:product:findone' },  // GET a single Product by id
      { verb: 'GET',    route: '',            emit: 'facet:product:find'    },  // GET an array of Product objects
      { verb: 'POST',   route: '',            emit: 'facet:product:create'  },  // POST new Product
      { verb: 'PUT',    route: '/:productId', emit: 'facet:product:update'  },  // PUT single/multiple Products
      { verb: 'DELETE', route: '/:productId', emit: 'facet:product:remove'  },  // DELETE a single Product resource
    ])
    .extendRouteErrorMessages({
      container: 'The API user does not have a valid container id.',
      conditions: 'No query conditions were specified',
      query: 'Error querying for product(s): ',
      notFound: 'No product was found.',
      find: 'No product(s) matched your criteria.',
      findOne: 'No product matched your criteria.',
      update: 'No updates were specified.',
      updateMatch: 'No products were updated based on your criteria.',
      create: 'No data supplied for creating new product.',
      createMatch: 'No product was created based on your criteria.',
      remove: 'No data supplied for removing product.',
      removeMatch: 'No product was removed based on your criteria.'
    });
};

/**
 * Registers the Product API event listeners
 *
 * @return   {void}
 */
ProductAPI.prototype.registerEvents = function () {
  var _this = this;

  this.intercom.on('facet:product:data', function handleProductData( data, nodeStack ) {
    data.then( function( productData ) {
      if( null === productData ){
        _this.intercom.emit('facet:response:error', 404, 'Product was not found.');
      }
      else {
        _this.intercom.emit('facet:response:product:data', productData);
      }
    },
    function( err ) {
      _this.intercom.emit('facet:response:error', 404, 'Error querying for product(s): ' + err.message);
    }).end();
  });
  this.intercom.on( 'facet:product:find',     this.find.bind(this)    );
  this.intercom.on( 'facet:product:findone',  this.findOne.bind(this) );
  this.intercom.on( 'facet:product:create',   this.create.bind(this)  );
  this.intercom.on( 'facet:product:update',   this.update.bind(this)  );
  this.intercom.on( 'facet:product:remove',   this.remove.bind(this)  );
};

/**
 * Exports the Product API
 *
 * @type   {Object}
 */
exports = module.exports = ProductAPI;
<|endoftext|>


<commit_before>"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.getDevServerBundleUrl = void 0;

var _path = require("path");

var _webpack = _interopRequireDefault(require("webpack"));

var _webpackDevServer = _interopRequireDefault(require("webpack-dev-server"));

var _url = _interopRequireDefault(require("url"));

var _clearRequireCache = _interopRequireDefault(require("./clearRequireCache"));

var _initHttpServer = _interopRequireDefault(require("./initHttpServer"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var getDevServerBundleUrl = function getDevServerBundleUrl(clientConfig) {
  var _clientConfig$output = clientConfig.output,
      publicPath = _clientConfig$output.publicPath,
      filename = _clientConfig$output.filename;
  return "".concat(publicPath).concat(filename);
};
/**
 * Watches server for changes, recompile and restart express
 */

exports.getDevServerBundleUrl = getDevServerBundleUrl;

var watchServerChanges = function watchServerChanges(serverConfig) {
  var initialLoad = true;
  var httpServerInitObject; // contains the httpServer itself and socket references

  var bundlePath = (0, _path.join)(serverConfig.output.path, serverConfig.output.filename);
  var serverCompiler = (0, _webpack.default)(serverConfig);
  var compilerOptions = {
    aggregateTimeout: 300,
    // wait so long for more changes
    poll: true // use polling instead of native watchers

  }; // compile server side code

  serverCompiler.watch(compilerOptions, function (err) {
    if (err) {
      console.log("Server bundling error: ".concat(JSON.stringify(err)));
      return;
    }

    (0, _clearRequireCache.default)(bundlePath);

    if (!initialLoad) {
      httpServerInitObject.httpServer.close(function () {
        httpServerInitObject = (0, _initHttpServer.default)(bundlePath);

        if (httpServerInitObject) {
          initialLoad = false;
          console.log("Server bundled & restarted ".concat(new Date()));
        } else {
          // server bundling error has occurred
          initialLoad = true;
        }
      }); // Destroy all open sockets

      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = httpServerInitObject.sockets.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var socket = _step.value;
          socket.destroy();
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return != null) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }
    } else {
      httpServerInitObject = (0, _initHttpServer.default)(bundlePath);

      if (httpServerInitObject) {
        initialLoad = false;
        console.log('Server bundled successfully');
      } else {
        // server bundling error has occurred
        initialLoad = true;
      }
    }
  });
};
/**
 * Start webpack dev server for hmr
 */

var watchClientChanges = function watchClientChanges(clientConfig) {
  var publicPath = clientConfig.output.publicPath;

  var _url$parse = _url.default.parse(publicPath),
      protocol = _url$parse.protocol,
      host = _url$parse.host,
      port = _url$parse.port;

  var webpackDevServerUrl = "".concat(protocol, "//").concat(host);
  var entry = clientConfig.entry,
      plugins = clientConfig.plugins;
  var hmrEntries = ["".concat(require.resolve('webpack-dev-server/client/'), "?").concat(webpackDevServerUrl), require.resolve('webpack/hot/dev-server')];

  if (entry.push) {
    clientConfig.entry = entry.concat(hmrEntries); // eslint-disable-line
  } else {
    clientConfig.entry = [entry].concat(hmrEntries); // eslint-disable-line
  }

  var hmrPlugin = new _webpack.default.HotModuleReplacementPlugin();

  if (!plugins) {
    clientConfig.plugins = [hmrPlugin]; // eslint-disable-line
  } else {
    plugins.push(hmrPlugin);
  }

  var compiler = (0, _webpack.default)(clientConfig);
  var devServerOptions = {
    quiet: false,
    // don’t output anything to the console.
    noInfo: false,
    // suppress boring information
    lazy: false,
    // no watching, compiles on request
    publicPath: publicPath,
    stats: 'errors-only',
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    hot: true
  };
  var server = new _webpackDevServer.default(compiler, devServerOptions);
  server.listen(port, 'localhost', function () {
    console.log("Starting webpack-dev-server on ".concat(webpackDevServerUrl));
  });
};

var main = function main(serverConfig, clientConfig) {
  // Start webpack dev server separately on a different port to avoid issues with httpServer restarts
  watchClientChanges(clientConfig); // Watch changes on the server side, re-compile and restart.

  watchServerChanges(serverConfig);
};

var _default = main;
exports.default = _default;<commit_msg>Update index.js<commit_after>"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.watchClientChanges = exports.watchServerChanges = exports.getDevServerBundleUrl = void 0;

var _path = require("path");

var _webpack = _interopRequireDefault(require("webpack"));

var _webpackDevServer = _interopRequireDefault(require("webpack-dev-server"));

var _url = _interopRequireDefault(require("url"));

var _clearRequireCache = _interopRequireDefault(require("./clearRequireCache"));

var _initHttpServer = _interopRequireDefault(require("./initHttpServer"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var getDevServerBundleUrl = function getDevServerBundleUrl(clientConfig) {
  var _clientConfig$output = clientConfig.output,
      publicPath = _clientConfig$output.publicPath,
      filename = _clientConfig$output.filename;
  return "".concat(publicPath).concat(filename);
};
/**
 * Watches server for changes, recompile and restart express
 */

exports.getDevServerBundleUrl = getDevServerBundleUrl;

var watchServerChanges = function watchServerChanges(serverConfig) {
  var initialLoad = true;
  var httpServerInitObject; // contains the httpServer itself and socket references

  var bundlePath = (0, _path.join)(serverConfig.output.path, serverConfig.output.filename);
  var serverCompiler = (0, _webpack.default)(serverConfig);
  var compilerOptions = {
    aggregateTimeout: 300,
    // wait so long for more changes
    poll: true // use polling instead of native watchers

  }; // compile server side code

  serverCompiler.watch(compilerOptions, function (err) {
    if (err) {
      console.log("Server bundling error: ".concat(JSON.stringify(err)));
      return;
    }

    (0, _clearRequireCache.default)(bundlePath);

    if (!initialLoad) {
      httpServerInitObject.httpServer.close(function () {
        httpServerInitObject = (0, _initHttpServer.default)(bundlePath);

        if (httpServerInitObject) {
          initialLoad = false;
          console.log("Server bundled & restarted ".concat(new Date()));
        } else {
          // server bundling error has occurred
          initialLoad = true;
        }
      }); // Destroy all open sockets

      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = httpServerInitObject.sockets.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var socket = _step.value;
          socket.destroy();
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return != null) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }
    } else {
      httpServerInitObject = (0, _initHttpServer.default)(bundlePath);

      if (httpServerInitObject) {
        initialLoad = false;
        console.log('Server bundled successfully');
      } else {
        // server bundling error has occurred
        initialLoad = true;
      }
    }
  });
};
/**
 * Start webpack dev server for hmr
 */

exports.watchServerChanges = watchServerChanges;

var watchClientChanges = function watchClientChanges(clientConfig) {
  var publicPath = clientConfig.output.publicPath;

  var _url$parse = _url.default.parse(publicPath),
      protocol = _url$parse.protocol,
      host = _url$parse.host,
      port = _url$parse.port;

  var webpackDevServerUrl = "".concat(protocol, "//").concat(host);
  var entry = clientConfig.entry,
      plugins = clientConfig.plugins;
  var hmrEntries = ["".concat(require.resolve('webpack-dev-server/client/'), "?").concat(webpackDevServerUrl), require.resolve('webpack/hot/dev-server')];

  if (entry.push) {
    clientConfig.entry = entry.concat(hmrEntries); // eslint-disable-line
  } else {
    clientConfig.entry = [entry].concat(hmrEntries); // eslint-disable-line
  }

  var hmrPlugin = new _webpack.default.HotModuleReplacementPlugin();

  if (!plugins) {
    clientConfig.plugins = [hmrPlugin]; // eslint-disable-line
  } else {
    plugins.push(hmrPlugin);
  }

  var compiler = (0, _webpack.default)(clientConfig);
  var devServerOptions = {
    quiet: false,
    // don’t output anything to the console.
    noInfo: false,
    // suppress boring information
    lazy: false,
    // no watching, compiles on request
    publicPath: publicPath,
    stats: 'errors-only',
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    hot: true
  };
  var server = new _webpackDevServer.default(compiler, devServerOptions);
  server.listen(port, 'localhost', function () {
    console.log("Starting webpack-dev-server on ".concat(webpackDevServerUrl));
  });
};

exports.watchClientChanges = watchClientChanges;

var main = function main(serverConfig, clientConfig) {
  // Start webpack dev server separately on a different port to avoid issues with httpServer restarts
  watchClientChanges(clientConfig); // Watch changes on the server side, re-compile and restart.

  watchServerChanges(serverConfig);
};

var _default = main;
exports.default = _default;<|endoftext|>


<commit_before>'use strict';

const Joi = require('joi');
const Path = require('path');
const Glob = require('glob');
const Async = require('async');
const methods = {};
const internals = {};

internals.injectObjectSchema = Joi.object().keys({
    prefix: Joi.string().optional(),
    includes: Joi.array().items(Joi.string(), Joi.object(), Joi.func()).required(),
    ignores: Joi.array().items(Joi.string()).optional()
});

internals.injectArraySchema = Joi.array().items(internals.injectObjectSchema);

internals.optionsSchema = Joi.object().keys({
    relativeTo: Joi.string().optional(),
    routes: internals.injectArraySchema.optional(),
    handlers: internals.injectArraySchema.optional(),
    methods: internals.injectArraySchema.optional()
});

exports.register = (server, options, next) => {

    const validateOptions = internals.optionsSchema.validate(options);
    if (validateOptions.error) {
        return next(validateOptions.error);
    }

    const relativeTo = options.relativeTo || process.cwd();

    const runGlob = (globPattern, ignorePatterns, doneRun) => {

        return Glob(globPattern, {
            nodir: true,
            strict: true,
            ignore: ignorePatterns,
            cwd: relativeTo
        }, (err, files) => {

            if (!files.length && !err) {
                err = 'No files found for pattern: ' + globPattern;
            }

            return doneRun(err, files);
        });
    };

    const getItems = (injectItem, doneGet) => {

        let itemsArr = [];

        return Async.each(injectItem.includes, (include, nextInclude) => {

            if (Joi.string().validate(include).error) {

                itemsArr.push(include);

                return nextInclude();
            }

            return runGlob(include, injectItem.ignores, (err, files) => {

                itemsArr = itemsArr.concat(files);

                return nextInclude(err);
            });

        }, (err) => {

            return doneGet(err, itemsArr);
        });
    };

    const methodInjectHelper = (methodsFilename, methodPrefix, injectModuleValue, injectModuleKey) => {

        let isValid = false;
        const moduleKey = (injectModuleKey) ? '.' + injectModuleKey : '';
        const modPrefix = (methodPrefix) ? methodPrefix + '.' : '';
        const methodName = modPrefix + methodsFilename + moduleKey;

        if (!Joi.func().validate(injectModuleValue).error) {
            server.method(methodName, injectModuleValue);
            isValid = true;
        }

        if (injectModuleValue.options && injectModuleValue.method && !Joi.func().validate(injectModuleValue.method).error) {
            server.method(methodName, injectModuleValue.method, injectModuleValue.options);
            isValid = true;
        }

        if (isValid) {
            if (injectModuleKey) {
                if (methodPrefix) {
                    methods[methodPrefix][methodsFilename][injectModuleKey] = injectModuleValue;
                }
                else {
                    methods[methodsFilename][injectModuleKey] = injectModuleValue;
                }
            }
            else {
                if (methodPrefix) {
                    methods[methodPrefix][methodsFilename] = injectModuleValue;
                }
                else {
                    methods[methodsFilename] = injectModuleValue;
                }
            }
        }

        return;
    };

    const methodInject = (nextInject) => {

        return Async.each(options.methods, (injectItem, nextInjectItem) => {

            getItems(injectItem, (err, items) => {

                if (err) {
                    return nextInjectItem(err);
                }

                if (injectItem.prefix) {
                    methods[injectItem.prefix] = {};
                }

                return Async.each(items, (item, nextFile) => {

                    let injectModule;
                    let methodsFilename;

                    if (Joi.string().validate(item).error) {
                        injectModule = item;

                        if (item.name || item.method) {
                            methodsFilename = item.name || item.method.name;
                        }
                    }
                    else {
                        injectModule = require(relativeTo + '/' + item);
                        methodsFilename = Path.basename(item, Path.extname(item));
                    }

                    if (!methodsFilename) {

                        return nextFile('Unable to identify method name. Please refer to method options API.');
                    }

                    if (injectItem.prefix) {
                        methods[injectItem.prefix][methodsFilename] = {};
                    }
                    else {
                        methods[methodsFilename] = {};
                    }

                    if (!Joi.func().validate(injectModule).error || injectModule.options) {

                        methodInjectHelper(methodsFilename, injectItem.prefix, injectModule);

                        return nextFile(err);
                    }

                    return Async.forEachOf(injectModule, (injectModuleValue, injectModuleKey, nextInjectModuleKey) => {

                        methodInjectHelper(methodsFilename, injectItem.prefix, injectModuleValue, injectModuleKey);

                        return nextInjectModuleKey();
                    }, (err) => {

                        return nextFile(err);
                    });

                }, (err) => {

                    return nextInjectItem(err);
                });
            });
        }, (err) => {

            return nextInject(err);
        });
    };

    const handlerInject = (nextInject) => {

        return Async.each(options.handlers, (injectItem, nextInjectItem) => {

            getItems(injectItem, (err, items) => {

                if (err) {
                    return nextInjectItem(err);
                }

                return Async.each(items, (item, nextFile) => {

                    if (Joi.string().validate(item).error) {
                        server.handler(item.name, item);
                    }
                    else {
                        server.handler(Path.basename(item, Path.extname(item)), require(relativeTo + '/' + item));
                    }

                    return nextFile();
                }, (err) => {

                    return nextInjectItem(err);
                });
            });
        }, (err) => {

            return nextInject(err);
        });
    };

    const routeInject = (nextInject) => {

        return Async.each(options.routes, (injectItem, nextInjectItem) => {

            getItems(injectItem, (err, items) => {

                if (err) {
                    return nextInjectItem(err);
                }

                return Async.each(items, (item, nextFile) => {

                    if (Joi.string().validate(item).error) {
                        server.route(item);
                    }
                    else {
                        server.route(require(relativeTo + '/' + item));
                    }

                    return nextFile();
                }, (err) => {

                    return nextInjectItem(err);
                });
            });
        }, (err) => {

            return nextInject(err);
        });
    };

    return Async.series([
        (done) => {

            return methodInject((err) => {

                return done(err);
            });
        },
        (done) => {

            return handlerInject((err) => {

                return done(err);
            });
        },
        (done) => {

            return routeInject((err) => {

                return done(err);
            });
        }
    ], (err) => {

        return next(err);
    });
};

exports.methods = methods;

exports.register.attributes = {
    pkg: require('../package.json')
};
<commit_msg>fix lint issues<commit_after>'use strict';

const Joi = require('joi');
const Path = require('path');
const Glob = require('glob');
const Async = require('async');
const methods = {};
const internals = {};

internals.injectObjectSchema = Joi.object().keys({
    prefix: Joi.string().optional(),
    includes: Joi.array().items(Joi.string(), Joi.object(), Joi.func()).required(),
    ignores: Joi.array().items(Joi.string()).optional()
});

internals.injectArraySchema = Joi.array().items(internals.injectObjectSchema);

internals.optionsSchema = Joi.object().keys({
    relativeTo: Joi.string().optional(),
    routes: internals.injectArraySchema.optional(),
    handlers: internals.injectArraySchema.optional(),
    methods: internals.injectArraySchema.optional()
});

exports.register = (server, options, next) => {

    const validateOptions = internals.optionsSchema.validate(options);
    if (validateOptions.error) {
        return next(validateOptions.error);
    }

    const relativeTo = options.relativeTo || process.cwd();

    const runGlob = (globPattern, ignorePatterns, doneRun) => {

        return Glob(globPattern, {
            nodir: true,
            strict: true,
            ignore: ignorePatterns,
            cwd: relativeTo
        }, (err, files) => {

            let error;

            if (!files.length && !err) {
                error = 'No files found for pattern: ' + globPattern;
            }

            return doneRun(error, files);
        });
    };

    const getItems = (injectItem, doneGet) => {

        let itemsArr = [];

        return Async.each(injectItem.includes, (include, nextInclude) => {

            if (Joi.string().validate(include).error) {

                itemsArr.push(include);

                return nextInclude();
            }

            return runGlob(include, injectItem.ignores, (err, files) => {

                itemsArr = itemsArr.concat(files);

                return nextInclude(err);
            });

        }, (err) => {

            return doneGet(err, itemsArr);
        });
    };

    const methodInjectHelper = (methodsFilename, methodPrefix, injectModuleValue, injectModuleKey) => {

        let isValid = false;
        const moduleKey = (injectModuleKey) ? '.' + injectModuleKey : '';
        const modPrefix = (methodPrefix) ? methodPrefix + '.' : '';
        const methodName = modPrefix + methodsFilename + moduleKey;

        if (!Joi.func().validate(injectModuleValue).error) {
            server.method(methodName, injectModuleValue);
            isValid = true;
        }

        if (injectModuleValue.options && injectModuleValue.method && !Joi.func().validate(injectModuleValue.method).error) {
            server.method(methodName, injectModuleValue.method, injectModuleValue.options);
            isValid = true;
        }

        if (isValid) {
            if (injectModuleKey && methodPrefix) {
                methods[methodPrefix][methodsFilename][injectModuleKey] = injectModuleValue;
            }
            else if (injectModuleKey && !methodPrefix) {
                methods[methodsFilename][injectModuleKey] = injectModuleValue;
            }
            else if (!injectModuleKey && methodPrefix) {
                methods[methodPrefix][methodsFilename] = injectModuleValue;
            }
            else {
                methods[methodsFilename] = injectModuleValue;
            }
        }
    };

    const methodInject = (nextInject) => {

        return Async.each(options.methods, (injectItem, nextInjectItem) => {

            getItems(injectItem, (err, items) => {

                if (err) {
                    return nextInjectItem(err);
                }

                if (injectItem.prefix) {
                    methods[injectItem.prefix] = {};
                }

                return Async.each(items, (item, nextFile) => {

                    let injectModule;
                    let methodsFilename;

                    if (Joi.string().validate(item).error) {
                        injectModule = item;

                        if (item.name || item.method) {
                            methodsFilename = item.name || item.method.name;
                        }
                    }
                    else {
                        injectModule = require(relativeTo + '/' + item);
                        methodsFilename = Path.basename(item, Path.extname(item));
                    }

                    if (!methodsFilename) {

                        return nextFile('Unable to identify method name. Please refer to method options API.');
                    }

                    if (injectItem.prefix) {
                        methods[injectItem.prefix][methodsFilename] = {};
                    }
                    else {
                        methods[methodsFilename] = {};
                    }

                    if (!Joi.func().validate(injectModule).error || injectModule.options) {

                        methodInjectHelper(methodsFilename, injectItem.prefix, injectModule);

                        return nextFile(err);
                    }

                    return Async.forEachOf(injectModule, (injectModuleValue, injectModuleKey, nextInjectModuleKey) => {

                        methodInjectHelper(methodsFilename, injectItem.prefix, injectModuleValue, injectModuleKey);

                        return nextInjectModuleKey();
                    }, (err) => {

                        return nextFile(err);
                    });

                }, (err) => {

                    return nextInjectItem(err);
                });
            });
        }, (err) => {

            return nextInject(err);
        });
    };

    const handlerInject = (nextInject) => {

        return Async.each(options.handlers, (injectItem, nextInjectItem) => {

            getItems(injectItem, (err, items) => {

                if (err) {
                    return nextInjectItem(err);
                }

                return Async.each(items, (item, nextFile) => {

                    if (Joi.string().validate(item).error) {
                        server.handler(item.name, item);
                    }
                    else {
                        server.handler(Path.basename(item, Path.extname(item)), require(relativeTo + '/' + item));
                    }

                    return nextFile();
                }, (err) => {

                    return nextInjectItem(err);
                });
            });
        }, (err) => {

            return nextInject(err);
        });
    };

    const routeInject = (nextInject) => {

        return Async.each(options.routes, (injectItem, nextInjectItem) => {

            getItems(injectItem, (err, items) => {

                if (err) {
                    return nextInjectItem(err);
                }

                return Async.each(items, (item, nextFile) => {

                    if (Joi.string().validate(item).error) {
                        server.route(item);
                    }
                    else {
                        server.route(require(relativeTo + '/' + item));
                    }

                    return nextFile();
                }, (err) => {

                    return nextInjectItem(err);
                });
            });
        }, (err) => {

            return nextInject(err);
        });
    };

    return Async.series([
        (done) => {

            return methodInject((err) => {

                return done(err);
            });
        },
        (done) => {

            return handlerInject((err) => {

                return done(err);
            });
        },
        (done) => {

            return routeInject((err) => {

                return done(err);
            });
        }
    ], (err) => {

        return next(err);
    });
};

exports.methods = methods;

exports.register.attributes = {
    pkg: require('../package.json')
};
<|endoftext|>


<commit_before>// Copyright 2012 Mark Cavage, Inc.  All rights reserved.
//
// Restify supports both a client and server API, and in the essence of not
// loading the kitchen sink on clients, the exports here is chunked up into
// client and server; note clients will have to opt in by setting the env
// var "RESTIFY_CLIENT_ONLY", but if you're in that boat, it's not hard to do,
// and enables much faster load times
//

var shallowCopy = require('./utils').shallowCopy;

function createClient(options) {
    if (typeof (options) === 'string') {
        options = {
            url: options
        };
    }

    var assert = require('assert-plus');
    var bunyan = require('./bunyan_helper');
    var clients = require('./clients');

    assert.object(options, 'options');

    var client;
    var opts = shallowCopy(options);
    opts.agent = options.agent;
    opts.name = opts.name || 'restify';
    opts.type = opts.type || 'application/octet-stream';
    opts.log = opts.log || bunyan.createLogger(opts.name);

    switch (opts.type) {
        case 'json':
            client = new clients.JsonClient(opts);
            break;

        case 'string':
            client = new clients.StringClient(opts);
            break;

        case 'http':
        default:
            client = new clients.HttpClient(opts);
            break;
    }

    return (client);
}

function createJsonClient(options) {
    if (typeof (options) === 'string') {
        options = {
            url: options
        };
    }

    options = options ? shallowCopy(options) : {};
    options.type = 'json';
    return (createClient(options));
}

function createStringClient(options) {
    if (typeof (options) === 'string') {
        options = {
            url: options
        };
    }

    options = options ? shallowCopy(options) : {};
    options.type = 'string';
    return (createClient(options));
}

function createHttpClient(options) {
    if (typeof (options) === 'string') {
        options = {
            url: options
        };
    }

    options = options ? shallowCopy(options) : {};
    options.type = 'http';
    return (createClient(options));
}

function createServer(options) {
    var bunyan = require('./bunyan_helper');
    var InternalError = require('./errors').InternalError;
    var Router = require('./router');
    var Server = require('./server');

    var opts = shallowCopy(options || {});
    var server;

    opts.name = opts.name || 'restify';
    opts.log = opts.log || bunyan.createLogger(opts.name);
    opts.router = opts.router || new Router(opts);

    server = new Server(opts);
    server.on('uncaughtException', function (req, res, route, e) {
        if (this.listeners('uncaughtException').length > 1 ||
            res._headerSent) {
            return (false);
        }

        res.send(new InternalError(e, e.message || 'unexpected error'));
        return (true);
    });

    return (server);
}

/**
 * Returns a string representation of a URL pattern , with its
 * parameters filled in by the passed hash.
 *
 * If a key is not found in the hash for a param, it is left alone.
 *
 * @param {Object} a hash of parameter names to values for substitution.
 */
function realizeUrl(pattern, params) {
    var p = pattern.replace(/\/:([^/]+)/g, function (match, k) {
        return (params.hasOwnProperty(k) ? '/' + params[k] : match);
    });

    return (require('./utils').sanitizePath(p));
}

///--- Exports

module.exports = {
    // Client API
    createClient: createClient,
    createJsonClient: createJsonClient,
    createJSONClient: createJsonClient,
    createStringClient: createStringClient,
    createHttpClient: createHttpClient,
    get HttpClient() {
        return (require('./clients').HttpClient);
    },
    get JsonClient() {
        return (require('./clients').JsonClient);
    },
    get StringClient() {
        return (require('./clients').StringClient);
    },

    // Miscellaneous API
    get bunyan() {
        return (require('./bunyan_helper'));
    },

    errors: {}

};

var errors = require('./errors');
Object.keys(errors).forEach(function (k) {
    module.exports.errors[k] = errors[k];
    module.exports[k] = errors[k];
});

if (!process.env.RESTIFY_CLIENT_ONLY) {

    module.exports.createServer = createServer;
    module.exports.httpDate = require('./http_date');
    module.exports.realizeUrl = realizeUrl;
    module.exports.formatters = require('./formatters');
    module.exports.plugins = {};
    var plugins = require('./plugins');
    Object.keys(plugins).forEach(function (k) {
        module.exports.plugins[k] = plugins[k];
        module.exports[k] = plugins[k];
    });
}
<commit_msg>Replace _headerSent with headersSent<commit_after>// Copyright 2012 Mark Cavage, Inc.  All rights reserved.
//
// Restify supports both a client and server API, and in the essence of not
// loading the kitchen sink on clients, the exports here is chunked up into
// client and server; note clients will have to opt in by setting the env
// var "RESTIFY_CLIENT_ONLY", but if you're in that boat, it's not hard to do,
// and enables much faster load times
//

var shallowCopy = require('./utils').shallowCopy;

function createClient(options) {
    if (typeof (options) === 'string') {
        options = {
            url: options
        };
    }

    var assert = require('assert-plus');
    var bunyan = require('./bunyan_helper');
    var clients = require('./clients');

    assert.object(options, 'options');

    var client;
    var opts = shallowCopy(options);
    opts.agent = options.agent;
    opts.name = opts.name || 'restify';
    opts.type = opts.type || 'application/octet-stream';
    opts.log = opts.log || bunyan.createLogger(opts.name);

    switch (opts.type) {
        case 'json':
            client = new clients.JsonClient(opts);
            break;

        case 'string':
            client = new clients.StringClient(opts);
            break;

        case 'http':
        default:
            client = new clients.HttpClient(opts);
            break;
    }

    return (client);
}

function createJsonClient(options) {
    if (typeof (options) === 'string') {
        options = {
            url: options
        };
    }

    options = options ? shallowCopy(options) : {};
    options.type = 'json';
    return (createClient(options));
}

function createStringClient(options) {
    if (typeof (options) === 'string') {
        options = {
            url: options
        };
    }

    options = options ? shallowCopy(options) : {};
    options.type = 'string';
    return (createClient(options));
}

function createHttpClient(options) {
    if (typeof (options) === 'string') {
        options = {
            url: options
        };
    }

    options = options ? shallowCopy(options) : {};
    options.type = 'http';
    return (createClient(options));
}

function createServer(options) {
    var bunyan = require('./bunyan_helper');
    var InternalError = require('./errors').InternalError;
    var Router = require('./router');
    var Server = require('./server');

    var opts = shallowCopy(options || {});
    var server;

    opts.name = opts.name || 'restify';
    opts.log = opts.log || bunyan.createLogger(opts.name);
    opts.router = opts.router || new Router(opts);

    server = new Server(opts);
    server.on('uncaughtException', function (req, res, route, e) {
        if (this.listeners('uncaughtException').length > 1 ||
            res.headersSent) {
            return (false);
        }

        res.send(new InternalError(e, e.message || 'unexpected error'));
        return (true);
    });

    return (server);
}

/**
 * Returns a string representation of a URL pattern , with its
 * parameters filled in by the passed hash.
 *
 * If a key is not found in the hash for a param, it is left alone.
 *
 * @param {Object} a hash of parameter names to values for substitution.
 */
function realizeUrl(pattern, params) {
    var p = pattern.replace(/\/:([^/]+)/g, function (match, k) {
        return (params.hasOwnProperty(k) ? '/' + params[k] : match);
    });

    return (require('./utils').sanitizePath(p));
}

///--- Exports

module.exports = {
    // Client API
    createClient: createClient,
    createJsonClient: createJsonClient,
    createJSONClient: createJsonClient,
    createStringClient: createStringClient,
    createHttpClient: createHttpClient,
    get HttpClient() {
        return (require('./clients').HttpClient);
    },
    get JsonClient() {
        return (require('./clients').JsonClient);
    },
    get StringClient() {
        return (require('./clients').StringClient);
    },

    // Miscellaneous API
    get bunyan() {
        return (require('./bunyan_helper'));
    },

    errors: {}

};

var errors = require('./errors');
Object.keys(errors).forEach(function (k) {
    module.exports.errors[k] = errors[k];
    module.exports[k] = errors[k];
});

if (!process.env.RESTIFY_CLIENT_ONLY) {

    module.exports.createServer = createServer;
    module.exports.httpDate = require('./http_date');
    module.exports.realizeUrl = realizeUrl;
    module.exports.formatters = require('./formatters');
    module.exports.plugins = {};
    var plugins = require('./plugins');
    Object.keys(plugins).forEach(function (k) {
        module.exports.plugins[k] = plugins[k];
        module.exports[k] = plugins[k];
    });
}
<|endoftext|>