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

var HID = require('node-hid');
var Q = require('q');

var LedgerNode = function(device, ledgerTransport, timeout, debug) {
	if (typeof timeout == "undefined") {
		timeout = 0;
	}
	this.device = device;
	this.ledgerTransport = ledgerTransport;
	this.timeout = timeout;
	this.exchangeStack = [];
	this.debug = debug;
}

LedgerNode.list_async = function() {
	var devices = HID.devices();
	var deviceList = [];
	for (var i in devices) {
		if (((devices[i].vendorId == 0x2581) && (devices[i].productId == 0x3b7c)) ||
		     (devices[i].vendorId == 0x2c97)) {
			deviceList.push(devices[i].path);
		}
	}
	return Q.fcall(function() {
		return deviceList;
	});
}

LedgerNode.prototype.exchange = function(apduHex, statusList) {

	var ledgerWrap = function(channel, command, packetSize) {
		var sequenceIdx = 0;
		var offset = 0;

		var tmp = Buffer.alloc(7);
		tmp.writeUInt16BE(channel, 0);
		tmp[2] = 0x05; // TAG_APDU
		tmp.writeUInt16BE(sequenceIdx, 3);
		sequenceIdx++;
		tmp.writeUInt16BE(command.length, 5);
		var blockSize = (command.length > packetSize - 7 ? packetSize - 7 : command.length);
		var result = Buffer.concat([tmp, command.slice(offset, offset + blockSize)], blockSize + 7);
		offset += blockSize;
		while (offset != command.length) {
			tmp = Buffer.alloc(5);
			tmp.writeUInt16BE(channel, 0);
			tmp[2] = 0x05; // TAG_APDU
			tmp.writeUInt16BE(sequenceIdx, 3);
			sequenceIdx++;
			blockSize = (command.length - offset > packetSize - 5 ? packetSize - 5 : command.length - offset);
			result = Buffer.concat([result, tmp, command.slice(offset, offset + blockSize)], result.length + blockSize + 5);
			offset += blockSize;
		}
		return result;
	}

	var ledgerUnwrap = function(channel, data, packetSize) {
		var offset = 0;
		var responseLength;
		var sequenceIdx = 0;
		var response;
		if ((typeof data == "undefined") || (data.length < 7 + 5)) {
			return;
		}
		if (data[offset++] != (channel >> 8)) {
			throw "Invalid channel;"
		}
		if (data[offset++] != (channel & 0xff)) {
			throw "Invalid channel";
		}
		if (data[offset++] != 0x05) {
			throw "Invalid tag";
		}
		if (data[offset++] != 0x00) {
			throw "Invalid sequence";
		}
		if (data[offset++] != 0x00) {
			throw "Invalid sequence";
		}
		responseLength = ((data[offset++] & 0xff) << 8);
		responseLength |= (data[offset++] & 0xff);
		if (data.length < 7 + responseLength) {
			return;
		}
		var blockSize = (responseLength > packetSize - 7 ? packetSize - 7 : responseLength);
		response = data.slice(offset, offset + blockSize);
		offset += blockSize;
		while (response.length != responseLength) {
			sequenceIdx++;
			if (offset == data.length) {
				return;
			}
			if (data[offset++] != (channel >> 8)) {
				throw "Invalid channel;"
			}
			if (data[offset++] != (channel & 0xff)) {
				throw "Invalid channel";
			}
			if (data[offset++] != 0x05) {
				throw "Invalid tag";
			}
			if (data[offset++] != (sequenceIdx >> 8)) {
				throw "Invalid sequence";
			}
			if (data[offset++] != (sequenceIdx & 0xff)) {
				throw "Invalid sequence";
			}
			blockSize = (responseLength - response.length > packetSize - 5 ? packetSize - 5 : responseLength - response.length);
			if (blockSize > data.length - offset) {
				return;
			}
			response = Buffer.concat([response, data.slice(offset, offset + blockSize)], response.length + blockSize);
			offset += blockSize;
		}
		return response;
	}

	var currentObject = this;
	var apdu = Buffer.from(apduHex, 'hex');

	var deferred = Q.defer();
	var exchangeTimeout;
	deferred.promise.apdu = apdu;
	if (!this.ledgerTransport) {
		deferred.promise.transport = apdu;
	}
	else {
		deferred.promise.transport = ledgerWrap(0x0101, apdu, 64);
	}

	if (this.timeout != 0) {
		exchangeTimeout = setTimeout(function() { // Node.js supports timeouts
			deferred.reject("timeout");
		}, this.timeout);
	}

	// enter the exchange wait list
	currentObject.exchangeStack.push(deferred);

	if (currentObject.exchangeStack.length == 1) {
		var processNextExchange = function() {

			// don't pop it now, to avoid multiple at once
			var deferred = currentObject.exchangeStack[0];

			var send_async = function(cardObject, content) {
				if (cardObject.debug) {
					console.log('=>' + content.toString('hex'));
				}
				var data = [ 0x00 ];
				for (var i=0; i<content.length; i++) {
					data.push(content[i]);
				}
				cardObject.device.write(data);
        			return Q.fcall(function() {
             				return content.length;
        			});
			}

			var recv_async = function(cardObject, size) {
				return Q.ninvoke(cardObject.device, "read").then(function(res) {
					var buffer = Buffer.from(res);
					if (cardObject.debug) {
						console.log('<=' + buffer.toString('hex'));
					}
					return buffer;
				});
			}

			var performExchange = function() {

					var deferredHidSend = Q.defer();
					var offsetSent = 0;
					var firstReceived = true;
					var toReceive = 0;

					var received = Buffer.alloc(0);
					var sendPart = function() {
						if (offsetSent == deferred.promise.transport.length) {
							return receivePart();
						}
						var blockSize = (deferred.promise.transport.length - offsetSent > 64 ? 64 : deferred.promise.transport.length - offsetSent);
						var block = deferred.promise.transport.slice(offsetSent, offsetSent + blockSize);
						var paddingSize = 64 - block.length;
						if (paddingSize != 0) {
							padding = Buffer.alloc(paddingSize).fill(0);
							block = Buffer.concat([block, padding], block.length + paddingSize);
						}
						return send_async(currentObject, block).then(
							function(result) {
								offsetSent += blockSize;
								return sendPart();
							}
						).fail(function(error) {
							deferredHidSend.reject(error);
						});
					}
					var receivePart = function() {
						if (!currentObject.ledgerTransport) {
							return recv_async(currentObject, 64).then(function(result) {
								received = Buffer.concat([received, result], received.length + result.length);
								if (firstReceived) {
									firstReceived = false;
									if ((received.length == 2) || (received[0] != 0x61)) {
										deferredHidSend.resolve(received);
									}
									else {
										toReceive = received[1];
										if (toReceive == 0) {
											toReceive == 256;
										}
										toReceive += 2;
									}
								}
								if (toReceive < 64) {
									deferredHidSend.resolve(received);
								}
								else {
									toReceive -= 64;
									return receivePart();
								}
							}).fail(function(error) {
								deferredHidSend.reject(error);
							});
						}
						else {
							return recv_async(currentObject, 64).then(function(result) {
								received = Buffer.concat([received, result], received.length + result.length);
								var response = ledgerUnwrap(0x0101, received, 64);
								if (typeof response != "undefined") {
									deferredHidSend.resolve(response);
								}
								else {
									return receivePart();
								}
							}).fail(function(error) {
								deferredHidSend.reject(error);
							});
						}
					}
					sendPart();
					return deferredHidSend.promise;
			}
			performExchange().then(function(result) {
				var resultBin = result;
				if (!currentObject.ledgerTransport) {
					if (resultBin.length == 2 || resultBin[0] != 0x61) {
						status = (resultBin[0] << 8) | (resultBin[1]);
						deferred.promise.response = resultBin.toString('hex');
					}
					else {
						var size = resultBin.byteAt(1);
						// fake T0
						if (size == 0) { size = 256; }

						deferred.promise.response = resultBin.toString('hex', 2);
						status = (resultBin[2 + size] << 8) | (resultBin[2 + size + 1]);
					}
				}
				else {
					deferred.promise.response = resultBin.toString('hex');
					status = (resultBin[resultBin.length - 2] << 8) | (resultBin[resultBin.length - 1]);
				}
				// Check the status
				var statusFound = false;
				for (var index in statusList) {
					if (statusList[index] == status) {
						statusFound = true;
						break;
					}
				}
				if (!statusFound) {
					deferred.reject("Invalid status " + status.toString(16));
				}
				// build the response
				if (this.timeout != 0) {
					clearTimeout(exchangeTimeout);
				}
				deferred.resolve(deferred.promise.response);
			})
			.fail(function(err) {
				if (this.timeout != 0) {
					clearTimeout(exchangeTimeout);
				}
				deferred.reject(err);
			})
			.finally(function () {

				// consume current promise
				currentObject.exchangeStack.shift();

				// schedule next exchange
				if (currentObject.exchangeStack.length > 0) {
					processNextExchange();
				}
			});
		}; //processNextExchange

		// schedule next exchange
		processNextExchange();
	}

	// the exchangeStack will process the promise when possible
	return deferred.promise;
}

LedgerNode.prototype.setScrambleKey = function(scrambleKey) {
}

LedgerNode.prototype.close_async = function() {
		this.device.close();
		return Q.fcall(function() {
		});

}

LedgerNode.create_async = function(timeout, debug) {
	return LedgerNode.list_async().then(function(result) {
		if (result.length == 0) {
			throw "No device found";
		}
		return new LedgerNode(new HID.HID(result[0]), true, timeout, debug);
	});
}

module.exports = LedgerNode;
<commit_msg>Strict mode fixes<commit_after>/********************************************************************************
*   Ledger Node JS API
*   (c) 2016-2017 Ledger
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
********************************************************************************/

var HID = require('node-hid');
var Q = require('q');

var LedgerNode = function(device, ledgerTransport, timeout, debug) {
	if (typeof timeout == "undefined") {
		timeout = 0;
	}
	this.device = device;
	this.ledgerTransport = ledgerTransport;
	this.timeout = timeout;
	this.exchangeStack = [];
	this.debug = debug;
}

LedgerNode.list_async = function() {
	var devices = HID.devices();
	var deviceList = [];
	for (var i in devices) {
		if (((devices[i].vendorId == 0x2581) && (devices[i].productId == 0x3b7c)) ||
		     (devices[i].vendorId == 0x2c97)) {
			deviceList.push(devices[i].path);
		}
	}
	return Q.fcall(function() {
		return deviceList;
	});
}

LedgerNode.prototype.exchange = function(apduHex, statusList) {

	var ledgerWrap = function(channel, command, packetSize) {
		var sequenceIdx = 0;
		var offset = 0;

		var tmp = Buffer.alloc(7);
		tmp.writeUInt16BE(channel, 0);
		tmp[2] = 0x05; // TAG_APDU
		tmp.writeUInt16BE(sequenceIdx, 3);
		sequenceIdx++;
		tmp.writeUInt16BE(command.length, 5);
		var blockSize = (command.length > packetSize - 7 ? packetSize - 7 : command.length);
		var result = Buffer.concat([tmp, command.slice(offset, offset + blockSize)], blockSize + 7);
		offset += blockSize;
		while (offset != command.length) {
			tmp = Buffer.alloc(5);
			tmp.writeUInt16BE(channel, 0);
			tmp[2] = 0x05; // TAG_APDU
			tmp.writeUInt16BE(sequenceIdx, 3);
			sequenceIdx++;
			blockSize = (command.length - offset > packetSize - 5 ? packetSize - 5 : command.length - offset);
			result = Buffer.concat([result, tmp, command.slice(offset, offset + blockSize)], result.length + blockSize + 5);
			offset += blockSize;
		}
		return result;
	}

	var ledgerUnwrap = function(channel, data, packetSize) {
		var offset = 0;
		var responseLength;
		var sequenceIdx = 0;
		var response;
		if ((typeof data == "undefined") || (data.length < 7 + 5)) {
			return;
		}
		if (data[offset++] != (channel >> 8)) {
			throw "Invalid channel;"
		}
		if (data[offset++] != (channel & 0xff)) {
			throw "Invalid channel";
		}
		if (data[offset++] != 0x05) {
			throw "Invalid tag";
		}
		if (data[offset++] != 0x00) {
			throw "Invalid sequence";
		}
		if (data[offset++] != 0x00) {
			throw "Invalid sequence";
		}
		responseLength = ((data[offset++] & 0xff) << 8);
		responseLength |= (data[offset++] & 0xff);
		if (data.length < 7 + responseLength) {
			return;
		}
		var blockSize = (responseLength > packetSize - 7 ? packetSize - 7 : responseLength);
		response = data.slice(offset, offset + blockSize);
		offset += blockSize;
		while (response.length != responseLength) {
			sequenceIdx++;
			if (offset == data.length) {
				return;
			}
			if (data[offset++] != (channel >> 8)) {
				throw "Invalid channel;"
			}
			if (data[offset++] != (channel & 0xff)) {
				throw "Invalid channel";
			}
			if (data[offset++] != 0x05) {
				throw "Invalid tag";
			}
			if (data[offset++] != (sequenceIdx >> 8)) {
				throw "Invalid sequence";
			}
			if (data[offset++] != (sequenceIdx & 0xff)) {
				throw "Invalid sequence";
			}
			blockSize = (responseLength - response.length > packetSize - 5 ? packetSize - 5 : responseLength - response.length);
			if (blockSize > data.length - offset) {
				return;
			}
			response = Buffer.concat([response, data.slice(offset, offset + blockSize)], response.length + blockSize);
			offset += blockSize;
		}
		return response;
	}

	var currentObject = this;
	var apdu = Buffer.from(apduHex, 'hex');

	var deferred = Q.defer();
	var exchangeTimeout;
	deferred.promise.apdu = apdu;
	if (!this.ledgerTransport) {
		deferred.promise.transport = apdu;
	}
	else {
		deferred.promise.transport = ledgerWrap(0x0101, apdu, 64);
	}

	if (this.timeout != 0) {
		exchangeTimeout = setTimeout(function() { // Node.js supports timeouts
			deferred.reject("timeout");
		}, this.timeout);
	}

	// enter the exchange wait list
	currentObject.exchangeStack.push(deferred);

	if (currentObject.exchangeStack.length == 1) {
		var processNextExchange = function() {

			// don't pop it now, to avoid multiple at once
			var deferred = currentObject.exchangeStack[0];

			var send_async = function(cardObject, content) {
				if (cardObject.debug) {
					console.log('=>' + content.toString('hex'));
				}
				var data = [ 0x00 ];
				for (var i=0; i<content.length; i++) {
					data.push(content[i]);
				}
				cardObject.device.write(data);
        			return Q.fcall(function() {
             				return content.length;
        			});
			}

			var recv_async = function(cardObject, size) {
				return Q.ninvoke(cardObject.device, "read").then(function(res) {
					var buffer = Buffer.from(res);
					if (cardObject.debug) {
						console.log('<=' + buffer.toString('hex'));
					}
					return buffer;
				});
			}

			var performExchange = function() {

					var deferredHidSend = Q.defer();
					var offsetSent = 0;
					var firstReceived = true;
					var toReceive = 0;

					var received = Buffer.alloc(0);
					var sendPart = function() {
						if (offsetSent == deferred.promise.transport.length) {
							return receivePart();
						}
						var blockSize = (deferred.promise.transport.length - offsetSent > 64 ? 64 : deferred.promise.transport.length - offsetSent);
						var block = deferred.promise.transport.slice(offsetSent, offsetSent + blockSize);
						var paddingSize = 64 - block.length;
						if (paddingSize != 0) {
							var padding = Buffer.alloc(paddingSize).fill(0);
							block = Buffer.concat([block, padding], block.length + paddingSize);
						}
						return send_async(currentObject, block).then(
							function(result) {
								offsetSent += blockSize;
								return sendPart();
							}
						).fail(function(error) {
							deferredHidSend.reject(error);
						});
					}
					var receivePart = function() {
						if (!currentObject.ledgerTransport) {
							return recv_async(currentObject, 64).then(function(result) {
								received = Buffer.concat([received, result], received.length + result.length);
								if (firstReceived) {
									firstReceived = false;
									if ((received.length == 2) || (received[0] != 0x61)) {
										deferredHidSend.resolve(received);
									}
									else {
										toReceive = received[1];
										if (toReceive == 0) {
											toReceive == 256;
										}
										toReceive += 2;
									}
								}
								if (toReceive < 64) {
									deferredHidSend.resolve(received);
								}
								else {
									toReceive -= 64;
									return receivePart();
								}
							}).fail(function(error) {
								deferredHidSend.reject(error);
							});
						}
						else {
							return recv_async(currentObject, 64).then(function(result) {
								received = Buffer.concat([received, result], received.length + result.length);
								var response = ledgerUnwrap(0x0101, received, 64);
								if (typeof response != "undefined") {
									deferredHidSend.resolve(response);
								}
								else {
									return receivePart();
								}
							}).fail(function(error) {
								deferredHidSend.reject(error);
							});
						}
					}
					sendPart();
					return deferredHidSend.promise;
			}
			performExchange().then(function(result) {
				var resultBin = result;
				if (!currentObject.ledgerTransport) {
					if (resultBin.length == 2 || resultBin[0] != 0x61) {
						status = (resultBin[0] << 8) | (resultBin[1]);
						deferred.promise.response = resultBin.toString('hex');
					}
					else {
						var size = resultBin.byteAt(1);
						// fake T0
						if (size == 0) { size = 256; }

						deferred.promise.response = resultBin.toString('hex', 2);
						status = (resultBin[2 + size] << 8) | (resultBin[2 + size + 1]);
					}
				}
				else {
					deferred.promise.response = resultBin.toString('hex');
					status = (resultBin[resultBin.length - 2] << 8) | (resultBin[resultBin.length - 1]);
				}
				// Check the status
				var statusFound = false;
				for (var index in statusList) {
					if (statusList[index] == status) {
						statusFound = true;
						break;
					}
				}
				if (!statusFound) {
					deferred.reject("Invalid status " + status.toString(16));
				}
				// build the response
				if (currentObject.timeout != 0) {
					clearTimeout(exchangeTimeout);
				}
				deferred.resolve(deferred.promise.response);
			})
			.fail(function(err) {
				if (currentObject.timeout != 0) {
					clearTimeout(exchangeTimeout);
				}
				deferred.reject(err);
			})
			.finally(function () {

				// consume current promise
				currentObject.exchangeStack.shift();

				// schedule next exchange
				if (currentObject.exchangeStack.length > 0) {
					processNextExchange();
				}
			});
		}; //processNextExchange

		// schedule next exchange
		processNextExchange();
	}

	// the exchangeStack will process the promise when possible
	return deferred.promise;
}

LedgerNode.prototype.setScrambleKey = function(scrambleKey) {
}

LedgerNode.prototype.close_async = function() {
		this.device.close();
		return Q.fcall(function() {
		});

}

LedgerNode.create_async = function(timeout, debug) {
	return LedgerNode.list_async().then(function(result) {
		if (result.length == 0) {
			throw "No device found";
		}
		return new LedgerNode(new HID.HID(result[0]), true, timeout, debug);
	});
}

module.exports = LedgerNode;
<|endoftext|>


<commit_before>const gulp = require('gulp');
const babel = require('gulp-babel');
const sourcemaps = require('gulp-sourcemaps');
const nodemon = require('gulp-nodemon');
const eslint = require('gulp-eslint');
const changed = require('gulp-changed');

gulp.task('lint', function() {
  return gulp.src('src/**/*.js')
    //.pipe(changed('lib'))
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
});

gulp.task('compile', ['lint'], () => {
  return gulp.src('src/**/*.js')
    //.pipe(changed('lib'))
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('lib'));
});

gulp.task('server', ['compile'], () => {
  return nodemon({
    script: 'index.js',
    nodeArgs: ['--preserve-symlinks'],
    env: {
      'NODE_ENV': 'development',
      'DEBUG': 'mostly:* feathers:* playread:*',
      'APP': 'all'
    },
  });
});

gulp.task('watch', () => {
  gulp.watch('src/**/*.js', ['lint', 'compile', 'server']);
});

gulp.task('default', ['watch', 'server']);
<commit_msg>Update gulpfile<commit_after>const gulp = require('gulp');
const babel = require('gulp-babel');
const sourcemaps = require('gulp-sourcemaps');
const eslint = require('gulp-eslint');
const changed = require('gulp-changed');

gulp.task('lint', function() {
  return gulp.src('src/**/*.js')
    //.pipe(changed('lib'))
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
});

gulp.task('compile', ['lint'], () => {
  return gulp.src('src/**/*.js')
    //.pipe(changed('lib'))
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('lib'));
});

gulp.task('watch', () => {
  gulp.watch('src/**/*.js', ['lint', 'compile']);
});

gulp.task('default', ['watch']);
<|endoftext|>


<commit_before>/*
 * Modular - JavaScript AMD Framework
 * Copyright 2013 Dan Phillimore (asmblah)
 * http://asmblah.github.com/modular/
 *
 * Implements the AMD specification - see https://github.com/amdjs/amdjs-api/wiki/AMD
 *
 * Released under the MIT license
 * https://github.com/asmblah/modular/raw/master/MIT-LICENSE.txt
 */

/*global define */
define([
    "vendor/chai/chai",
    "root/modular",
    "vendor/sinon/sinon",
    "js/util"
], function (
    chai,
    modular,
    sinon,
    util
) {
    "use strict";

    var expect = chai.expect;

    describe("Browser modular.js", function () {
        var createdScript,
            global,
            head,
            loadModule,
            Math,
            modularScript;

        beforeEach(function (done) {
            global = {};
            Math = {
                random: sinon.stub()
            };

            util.get("/modular.js", {cache: false}).then(function (js) {
                loadModule = function () {
                    /*jshint evil:true */
                    new Function("Math", js).call(global, Math);
                };
                done();
            });
        });

        util.each([
            {
                browser: false,
                externalDefine: true,
                amdCompatible: true
            },
            {
                browser: false,
                externalDefine: false
            },
            {
                browser: true,
                externalDefine: true,
                amdCompatible: false,
                supportsDocumentBaseURI: true,
                supportsScriptOnload: true,
                baseURI: "http://world.net/path/to/righteousness",
                baseUrl: "http://world.net/path/to",
                modularSrc: "http://world.net/path/to/righteousness/modular.js",
                ModularSrc: "http://world.net/path/to/righteousness/js/Modular.js",
                dataMain: undefined,
                domReady: false,
                supportsDOMContentLoaded: true
            },
            {
                browser: true,
                externalDefine: true,
                amdCompatible: true,
                supportsDocumentBaseURI: true,
                supportsScriptOnload: true,
                baseURI: "http://world.net/path/to/righteousness",
                baseUrl: "http://world.net/path/to",
                modularSrc: "http://world.net/path/to/righteousness/modular.js",
                ModularSrc: "http://world.net/path/to/righteousness/js/Modular.js",
                dataMain: undefined,
                domReady: true,
                supportsDOMContentLoaded: false
            },
            {
                browser: true,
                externalDefine: false,
                supportsDocumentBaseURI: true,
                supportsScriptOnload: false,
                baseURI: "http://world.net/path/to/righteousness",
                baseUrl: "http://world.net/path/to",
                modularSrc: "http://world.net/path/to/righteousness/modular.js",
                ModularSrc: "http://world.net/path/to/righteousness/js/Modular.js",
                dataMain: "a/module/to/remember",
                domReady: true,
                supportsDOMContentLoaded: true
            }
        ], function (scenario) {
            describe("when the environment is" + (scenario.browser ? "": " not") + " a browser, define(...) is" + (scenario.externalDefine ? "" : " not") + " already defined" + (scenario.amdCompatible ? " and supports AMD" : "") + ", document.baseURI is" + (scenario.supportsDocumentBaseURI ? "" : " not") + " supported, script.onload is" + (scenario.supportsScriptOnload ? "" : " not") + " supported", function () {
                beforeEach(function () {
                    if (scenario.browser) {
                        modularScript = {
                            getAttribute: sinon.stub().withArgs("data-main").returns(scenario.dataMain),
                            removeAttribute: sinon.spy(),
                            src: scenario.modularSrc
                        };
                        head = {
                            firstChild: modularScript,
                            insertBefore: sinon.spy(function (element) {
                                global.document.scripts.unshift(element);
                            }),
                            removeChild: sinon.spy()
                        };
                        global.document = {
                            createElement: sinon.spy(function () {
                                createdScript = {
                                    getAttribute: sinon.stub(),
                                    removeAttribute: sinon.spy(),
                                    src: ""
                                };
                                return createdScript;
                            }),
                            getElementsByTagName: sinon.stub().withArgs("head").returns([head]),
                            scripts: [modularScript]
                        };
                        global.location = {
                            pathname: ""
                        };
                        global.setTimeout = sinon.spy();

                        if (scenario.supportsDocumentBaseURI) {
                            global.document.baseURI = scenario.baseURI;
                        } else {
                            global.location.pathname = scenario.baseURI;
                        }

                        if (!scenario.supportsScriptOnload) {
                            global.document.uniqueID = 0;
                        }

                        if (scenario.domReady) {
                            global.document.readyState = "interactive";
                        }

                        if (scenario.supportsDOMContentLoaded) {
                            global.addEventListener = sinon.spy();
                        }
                    }

                    if (scenario.externalDefine) {
                        global.define = sinon.spy();

                        if (scenario.amdCompatible) {
                            global.define.amd = {};
                        }
                    }
                });

                it("should not error", function () {
                    expect(loadModule).to.not.throw();
                });

                describe("when it does not error", function () {
                    beforeEach(function () {
                        loadModule();
                    });

                    function expectScriptToHaveLoaded(src) {
                        describe("when the script with src '" + src + "' loads", function () {
                            it("should create a script element", function () {
                                expect(global.document.createElement).to.have.been.calledOnce;
                            });

                            it("should set the script element's src to the correct URI", function () {
                                expect(createdScript.src).to.equal(src);
                            });

                            it("should insert one element in the head", function () {
                                expect(head.insertBefore).to.have.been.calledOnce;
                            });

                            it("should insert the script element in the head", function () {
                                expect(head.insertBefore).to.have.been.calledWith(createdScript);
                            });

                            it("should insert the script element as the first child in the head", function () {
                                expect(head.insertBefore).to.have.been.calledWith(sinon.match.any, head.firstChild);
                            });

                            if (scenario.supportsScriptOnload) {
                                it("should attach a function listening for script.onload", function () {
                                    expect(createdScript.onload).to.be.a("function");
                                });

                                it("should not attach a function listening for script.onreadystatechange", function () {
                                    expect(createdScript.onreadystatechange).to.not.be.a("function");
                                });

                                describe("when the script loads successfully", function () {
                                    beforeEach(function () {
                                        global.require = sinon.spy();
                                        createdScript.onload();
                                    });

                                    it("should remove one element from the head", function () {
                                        expect(head.removeChild).to.have.been.calledOnce;
                                    });

                                    it("should remove the script from the head", function () {
                                        expect(head.removeChild).to.have.been.calledWith(createdScript);
                                    });
                                });
                            } else {
                                it("should attach a function listening for script.onreadystatechange", function () {
                                    expect(createdScript.onreadystatechange).to.be.a("function");
                                });

                                it("should not attach a function listening for script.onload", function () {
                                    expect(createdScript.onload).to.not.be.a("function");
                                });
                            }
                        });
                    }

                    if (scenario.browser && (!scenario.externalDefine || scenario.amdCompatible)) {
                        if (scenario.amdCompatible) {
                            it("should call define(...) once", function () {
                                expect(global.define).to.have.been.calledOnce;
                            });

                            it("should request the Modular core module", function () {
                                expect(global.define).to.have.been.calledWith(sinon.match(["./js/Modular"]));
                            });
                        } else {
                            expectScriptToHaveLoaded(scenario.ModularSrc);
                        }

                        describe("when loading the Modular core module", function () {
                            var modular,
                                MockModular;

                            beforeEach(function () {
                                global.document.createElement.reset();
                                head.insertBefore.reset();

                                MockModular = function () {};
                                MockModular.prototype.configure = sinon.spy();

                                if (scenario.externalDefine) {
                                    modular = global.define.getCall(0).args[1](MockModular);
                                } else {
                                    global.require = sinon.spy();

                                    if (scenario.supportsScriptOnload) {
                                        createdScript.onload();
                                    } else {
                                        createdScript.readyState = "loaded";
                                        createdScript.onreadystatechange();
                                    }
                                }
                            });

                            if (!scenario.externalDefine) {
                                it("should call require(...) once", function () {
                                    expect(global.require).to.have.been.calledOnce;
                                });

                                it("should request the 'modular' special dependency", function () {
                                    expect(global.require).to.have.been.calledWith(sinon.match(["modular"]));
                                });
                            } else {
                                it("should return an instance of the requested Modular as this module's value", function () {
                                    expect(modular).to.be.an.instanceOf(MockModular);
                                });
                            }

                            describe("when the Modular core module is loaded", function () {
                                beforeEach(function () {
                                    if (!scenario.externalDefine) {
                                        modular = new MockModular();
                                        global.require.getCall(0).args[1](modular);
                                    }
                                });

                                describe("when configuring the Modular instance", function () {
                                    it("should call Modular.configure(...)", function () {
                                        expect(modular.configure).to.have.been.calledOnce;
                                    });

                                    it("should set the 'baseUrl' option correctly", function () {
                                        expect(modular.configure).to.have.been.calledWith(sinon.match.hasOwn("baseUrl", scenario.baseUrl));
                                    });

                                    it("should set the 'baseUrl' option using document.baseURI rather than location.pathname when available");

                                    describe("with the 'exclude' option", function () {
                                        var regex;

                                        beforeEach(function () {
                                            regex = modular.configure.getCall(0).args[0].exclude;
                                        });

                                        it("should exclude http://... URIs", function () {
                                            expect("http://abc.com").to.match(regex);
                                        });

                                        it("should exclude https://... URIs", function () {
                                            expect("http://abc.com").to.match(regex);
                                        });

                                        it("should not exclude paths with no protocol", function () {
                                            expect("/a/path/to/a/module").to.not.match(regex);
                                        });
                                    });

                                    describe("with the 'transport' and 'defineAnonymous' options", function () {
                                        var defineAnonymous,
                                            transport;

                                        beforeEach(function () {
                                            var options;
                                            options = modular.configure.getCall(0).args[0];
                                            defineAnonymous = options.defineAnonymous;
                                            transport = options.transport;
                                        });

                                        describe("when requesting an undefined module through the transport", function () {
                                            var callback,
                                                module;

                                            beforeEach(function () {
                                                callback = sinon.spy();
                                                module = {
                                                    config: {}
                                                };
                                            });

                                            util.each([
                                                {id: "mod/ule", allowCached: false, random: 76, src: "http://the.com/base/url/mod/ule.js"},
                                                {id: "a/module", allowCached: false, random: 123, src: "http://net.ted/uri/a/module.js"},
                                                {id: "mod/ded", allowCached: true, random: 39487.3, src: "http://the.base/mod/ded.js"}
                                            ], function (fixture) {
                                                describe("when the module's id is '" + fixture.id + "' and caching is " + (fixture.allowCached ? "" : "not ") + "allowed", function () {
                                                    beforeEach(function () {
                                                        module.config.baseUrl = scenario.baseUrl;
                                                        module.config.cache = fixture.allowCached;
                                                        module.id = fixture.id;
                                                        Math.random.returns(fixture.random);

                                                        transport(callback, module);
                                                    });

                                                    expectScriptToHaveLoaded(scenario.baseUrl + "/" + fixture.id + ".js" + (fixture.allowCached ? "" : "?__r=" + fixture.random));
                                                });
                                            });
                                        });
                                    });
                                });

                                describe("when handling data-main for the modular.js script element", function () {
                                    if (scenario.dataMain) {
                                        describe("when the element defines a 'data-main' attribute of '" + scenario.dataMain, function () {
                                            it("should remove the 'data-main' attribute", function () {
                                                expect(modularScript.removeAttribute).to.have.been.calledOnce;
                                            });
                                        });
                                    } else {
                                        describe("when the element does not define a 'data-main' attribute", function () {
                                            it("should not remove the 'data-main' attribute", function () {
                                                expect(modularScript.removeAttribute).to.not.have.been.called;
                                            });
                                        });
                                    }
                                });
                            });
                        });
                    } else {
                        it("should not throw an error", function () {
                            expect(loadModule).to.not.throw();
                        });

                        if (scenario.externalDefine) {
                            it("should not call define(...)", function () {
                                loadModule();

                                expect(global.define).to.not.have.been.called;
                            });
                        }
                    }
                });
            });
        });
    });
});
<commit_msg>Removed unused data from test fixture<commit_after>/*
 * Modular - JavaScript AMD Framework
 * Copyright 2013 Dan Phillimore (asmblah)
 * http://asmblah.github.com/modular/
 *
 * Implements the AMD specification - see https://github.com/amdjs/amdjs-api/wiki/AMD
 *
 * Released under the MIT license
 * https://github.com/asmblah/modular/raw/master/MIT-LICENSE.txt
 */

/*global define */
define([
    "vendor/chai/chai",
    "root/modular",
    "vendor/sinon/sinon",
    "js/util"
], function (
    chai,
    modular,
    sinon,
    util
) {
    "use strict";

    var expect = chai.expect;

    describe("Browser modular.js", function () {
        var createdScript,
            global,
            head,
            loadModule,
            Math,
            modularScript;

        beforeEach(function (done) {
            global = {};
            Math = {
                random: sinon.stub()
            };

            util.get("/modular.js", {cache: false}).then(function (js) {
                loadModule = function () {
                    /*jshint evil:true */
                    new Function("Math", js).call(global, Math);
                };
                done();
            });
        });

        util.each([
            {
                browser: false,
                externalDefine: true,
                amdCompatible: true
            },
            {
                browser: false,
                externalDefine: false
            },
            {
                browser: true,
                externalDefine: true,
                amdCompatible: false,
                supportsDocumentBaseURI: true,
                supportsScriptOnload: true,
                baseURI: "http://world.net/path/to/righteousness",
                baseUrl: "http://world.net/path/to",
                modularSrc: "http://world.net/path/to/righteousness/modular.js",
                ModularSrc: "http://world.net/path/to/righteousness/js/Modular.js",
                dataMain: undefined,
                domReady: false,
                supportsDOMContentLoaded: true
            },
            {
                browser: true,
                externalDefine: true,
                amdCompatible: true,
                supportsDocumentBaseURI: true,
                supportsScriptOnload: true,
                baseURI: "http://world.net/path/to/righteousness",
                baseUrl: "http://world.net/path/to",
                modularSrc: "http://world.net/path/to/righteousness/modular.js",
                ModularSrc: "http://world.net/path/to/righteousness/js/Modular.js",
                dataMain: undefined,
                domReady: true,
                supportsDOMContentLoaded: false
            },
            {
                browser: true,
                externalDefine: false,
                supportsDocumentBaseURI: true,
                supportsScriptOnload: false,
                baseURI: "http://world.net/path/to/righteousness",
                baseUrl: "http://world.net/path/to",
                modularSrc: "http://world.net/path/to/righteousness/modular.js",
                ModularSrc: "http://world.net/path/to/righteousness/js/Modular.js",
                dataMain: "a/module/to/remember",
                domReady: true,
                supportsDOMContentLoaded: true
            }
        ], function (scenario) {
            describe("when the environment is" + (scenario.browser ? "": " not") + " a browser, define(...) is" + (scenario.externalDefine ? "" : " not") + " already defined" + (scenario.amdCompatible ? " and supports AMD" : "") + ", document.baseURI is" + (scenario.supportsDocumentBaseURI ? "" : " not") + " supported, script.onload is" + (scenario.supportsScriptOnload ? "" : " not") + " supported", function () {
                beforeEach(function () {
                    if (scenario.browser) {
                        modularScript = {
                            getAttribute: sinon.stub().withArgs("data-main").returns(scenario.dataMain),
                            removeAttribute: sinon.spy(),
                            src: scenario.modularSrc
                        };
                        head = {
                            firstChild: modularScript,
                            insertBefore: sinon.spy(function (element) {
                                global.document.scripts.unshift(element);
                            }),
                            removeChild: sinon.spy()
                        };
                        global.document = {
                            createElement: sinon.spy(function () {
                                createdScript = {
                                    getAttribute: sinon.stub(),
                                    removeAttribute: sinon.spy(),
                                    src: ""
                                };
                                return createdScript;
                            }),
                            getElementsByTagName: sinon.stub().withArgs("head").returns([head]),
                            scripts: [modularScript]
                        };
                        global.location = {
                            pathname: ""
                        };
                        global.setTimeout = sinon.spy();

                        if (scenario.supportsDocumentBaseURI) {
                            global.document.baseURI = scenario.baseURI;
                        } else {
                            global.location.pathname = scenario.baseURI;
                        }

                        if (!scenario.supportsScriptOnload) {
                            global.document.uniqueID = 0;
                        }

                        if (scenario.domReady) {
                            global.document.readyState = "interactive";
                        }

                        if (scenario.supportsDOMContentLoaded) {
                            global.addEventListener = sinon.spy();
                        }
                    }

                    if (scenario.externalDefine) {
                        global.define = sinon.spy();

                        if (scenario.amdCompatible) {
                            global.define.amd = {};
                        }
                    }
                });

                it("should not error", function () {
                    expect(loadModule).to.not.throw();
                });

                describe("when it does not error", function () {
                    beforeEach(function () {
                        loadModule();
                    });

                    function expectScriptToHaveLoaded(src) {
                        describe("when the script with src '" + src + "' loads", function () {
                            it("should create a script element", function () {
                                expect(global.document.createElement).to.have.been.calledOnce;
                            });

                            it("should set the script element's src to the correct URI", function () {
                                expect(createdScript.src).to.equal(src);
                            });

                            it("should insert one element in the head", function () {
                                expect(head.insertBefore).to.have.been.calledOnce;
                            });

                            it("should insert the script element in the head", function () {
                                expect(head.insertBefore).to.have.been.calledWith(createdScript);
                            });

                            it("should insert the script element as the first child in the head", function () {
                                expect(head.insertBefore).to.have.been.calledWith(sinon.match.any, head.firstChild);
                            });

                            if (scenario.supportsScriptOnload) {
                                it("should attach a function listening for script.onload", function () {
                                    expect(createdScript.onload).to.be.a("function");
                                });

                                it("should not attach a function listening for script.onreadystatechange", function () {
                                    expect(createdScript.onreadystatechange).to.not.be.a("function");
                                });

                                describe("when the script loads successfully", function () {
                                    beforeEach(function () {
                                        global.require = sinon.spy();
                                        createdScript.onload();
                                    });

                                    it("should remove one element from the head", function () {
                                        expect(head.removeChild).to.have.been.calledOnce;
                                    });

                                    it("should remove the script from the head", function () {
                                        expect(head.removeChild).to.have.been.calledWith(createdScript);
                                    });
                                });
                            } else {
                                it("should attach a function listening for script.onreadystatechange", function () {
                                    expect(createdScript.onreadystatechange).to.be.a("function");
                                });

                                it("should not attach a function listening for script.onload", function () {
                                    expect(createdScript.onload).to.not.be.a("function");
                                });
                            }
                        });
                    }

                    if (scenario.browser && (!scenario.externalDefine || scenario.amdCompatible)) {
                        if (scenario.amdCompatible) {
                            it("should call define(...) once", function () {
                                expect(global.define).to.have.been.calledOnce;
                            });

                            it("should request the Modular core module", function () {
                                expect(global.define).to.have.been.calledWith(sinon.match(["./js/Modular"]));
                            });
                        } else {
                            expectScriptToHaveLoaded(scenario.ModularSrc);
                        }

                        describe("when loading the Modular core module", function () {
                            var modular,
                                MockModular;

                            beforeEach(function () {
                                global.document.createElement.reset();
                                head.insertBefore.reset();

                                MockModular = function () {};
                                MockModular.prototype.configure = sinon.spy();

                                if (scenario.externalDefine) {
                                    modular = global.define.getCall(0).args[1](MockModular);
                                } else {
                                    global.require = sinon.spy();

                                    if (scenario.supportsScriptOnload) {
                                        createdScript.onload();
                                    } else {
                                        createdScript.readyState = "loaded";
                                        createdScript.onreadystatechange();
                                    }
                                }
                            });

                            if (!scenario.externalDefine) {
                                it("should call require(...) once", function () {
                                    expect(global.require).to.have.been.calledOnce;
                                });

                                it("should request the 'modular' special dependency", function () {
                                    expect(global.require).to.have.been.calledWith(sinon.match(["modular"]));
                                });
                            } else {
                                it("should return an instance of the requested Modular as this module's value", function () {
                                    expect(modular).to.be.an.instanceOf(MockModular);
                                });
                            }

                            describe("when the Modular core module is loaded", function () {
                                beforeEach(function () {
                                    if (!scenario.externalDefine) {
                                        modular = new MockModular();
                                        global.require.getCall(0).args[1](modular);
                                    }
                                });

                                describe("when configuring the Modular instance", function () {
                                    it("should call Modular.configure(...)", function () {
                                        expect(modular.configure).to.have.been.calledOnce;
                                    });

                                    it("should set the 'baseUrl' option correctly", function () {
                                        expect(modular.configure).to.have.been.calledWith(sinon.match.hasOwn("baseUrl", scenario.baseUrl));
                                    });

                                    it("should set the 'baseUrl' option using document.baseURI rather than location.pathname when available");

                                    describe("with the 'exclude' option", function () {
                                        var regex;

                                        beforeEach(function () {
                                            regex = modular.configure.getCall(0).args[0].exclude;
                                        });

                                        it("should exclude http://... URIs", function () {
                                            expect("http://abc.com").to.match(regex);
                                        });

                                        it("should exclude https://... URIs", function () {
                                            expect("http://abc.com").to.match(regex);
                                        });

                                        it("should not exclude paths with no protocol", function () {
                                            expect("/a/path/to/a/module").to.not.match(regex);
                                        });
                                    });

                                    describe("with the 'transport' and 'defineAnonymous' options", function () {
                                        var defineAnonymous,
                                            transport;

                                        beforeEach(function () {
                                            var options;
                                            options = modular.configure.getCall(0).args[0];
                                            defineAnonymous = options.defineAnonymous;
                                            transport = options.transport;
                                        });

                                        describe("when requesting an undefined module through the transport", function () {
                                            var callback,
                                                module;

                                            beforeEach(function () {
                                                callback = sinon.spy();
                                                module = {
                                                    config: {}
                                                };
                                            });

                                            util.each([
                                                {id: "mod/ule", allowCached: false, random: 76},
                                                {id: "a/module", allowCached: false, random: 123},
                                                {id: "mod/ded", allowCached: true, random: 39487.3}
                                            ], function (fixture) {
                                                describe("when the module's id is '" + fixture.id + "' and caching is " + (fixture.allowCached ? "" : "not ") + "allowed", function () {
                                                    beforeEach(function () {
                                                        module.config.baseUrl = scenario.baseUrl;
                                                        module.config.cache = fixture.allowCached;
                                                        module.id = fixture.id;
                                                        Math.random.returns(fixture.random);

                                                        transport(callback, module);
                                                    });

                                                    expectScriptToHaveLoaded(scenario.baseUrl + "/" + fixture.id + ".js" + (fixture.allowCached ? "" : "?__r=" + fixture.random));
                                                });
                                            });
                                        });
                                    });
                                });

                                describe("when handling data-main for the modular.js script element", function () {
                                    if (scenario.dataMain) {
                                        describe("when the element defines a 'data-main' attribute of '" + scenario.dataMain, function () {
                                            it("should remove the 'data-main' attribute", function () {
                                                expect(modularScript.removeAttribute).to.have.been.calledOnce;
                                            });
                                        });
                                    } else {
                                        describe("when the element does not define a 'data-main' attribute", function () {
                                            it("should not remove the 'data-main' attribute", function () {
                                                expect(modularScript.removeAttribute).to.not.have.been.called;
                                            });
                                        });
                                    }
                                });
                            });
                        });
                    } else {
                        it("should not throw an error", function () {
                            expect(loadModule).to.not.throw();
                        });

                        if (scenario.externalDefine) {
                            it("should not call define(...)", function () {
                                loadModule();

                                expect(global.define).to.not.have.been.called;
                            });
                        }
                    }
                });
            });
        });
    });
});
<|endoftext|>


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

var gulp = require('gulp'),
    babelify = require('babelify'),
    browserify = require('browserify'),
    connect = require('gulp-connect'),
    del = require('del'),
    source = require('vinyl-source-stream'),
    exorcist   = require('exorcist'),
    KarmaServer = require('karma').Server,
    uglify = require('gulp-uglify'),
    streamify = require('gulp-streamify'),
    js = 'src/js/**/*.js';

gulp.task('compilejs', function () {
    return browserify('src/js/paAnimations.js', {
            debug: true
        })
        .transform(babelify)
        .bundle()
        .on("error", function(err) {
            console.log("Error : " + err.message);
        })
        .pipe(exorcist('dist/src/paAnimations.js.map'))
        .pipe(source('paAnimations.js'))
        .pipe(gulp.dest('dist/src'));
});

gulp.task('build', function () {
    return browserify('src/js/paAnimations.js')
        .transform(babelify)
        .bundle()
        .on("error", function(err) {
            console.log("Error : " + err.message);
        })
        .pipe(source('paAnimations.min.js'))
        .pipe(streamify(uglify()))
        .pipe(gulp.dest('dist/build'));
});

gulp.task('karma', function (done) {
    new KarmaServer({
        configFile: __dirname + '/karma.conf.js'
    }, done).start();
});

gulp.task('server', function () {
    connect.server({
        root: ['example', 'bower_components', 'dist']
    });
});

gulp.task('watch', function () {
    gulp.watch([js], ['del:dist', 'compilejs']);
});

gulp.task('del:dist', function (done) {
    del([
        'dist/**/*'
    ], done);
});

gulp.task('default', ['del:dist', 'compilejs', 'server', 'watch']);
<commit_msg>[lint] Remove doublequotes<commit_after>//jshint node:true
'use strict';

var gulp = require('gulp'),
    babelify = require('babelify'),
    browserify = require('browserify'),
    connect = require('gulp-connect'),
    del = require('del'),
    source = require('vinyl-source-stream'),
    exorcist   = require('exorcist'),
    KarmaServer = require('karma').Server,
    uglify = require('gulp-uglify'),
    streamify = require('gulp-streamify'),
    js = 'src/js/**/*.js';

gulp.task('compilejs', function () {
    return browserify('src/js/paAnimations.js', {
            debug: true
        })
        .transform(babelify)
        .bundle()
        .on('error', function (err) {
            console.log('Error : ' + err.message);
        })
        .pipe(exorcist('dist/src/paAnimations.js.map'))
        .pipe(source('paAnimations.js'))
        .pipe(gulp.dest('dist/src'));
});

gulp.task('build', function () {
    return browserify('src/js/paAnimations.js')
        .transform(babelify)
        .bundle()
        .on('error', function (err) {
            console.log('Error : ' + err.message);
        })
        .pipe(source('paAnimations.min.js'))
        .pipe(streamify(uglify()))
        .pipe(gulp.dest('dist/build'));
});

gulp.task('karma', function (done) {
    new KarmaServer({
        configFile: __dirname + '/karma.conf.js'
    }, done).start();
});

gulp.task('server', function () {
    connect.server({
        root: ['example', 'bower_components', 'dist']
    });
});

gulp.task('watch', function () {
    gulp.watch([js], ['del:dist', 'compilejs']);
});

gulp.task('del:dist', function (done) {
    del([
        'dist/**/*'
    ], done);
});

gulp.task('default', ['del:dist', 'compilejs', 'server', 'watch']);
<|endoftext|>


<commit_before>/**
 * @license MIT License
 *
 * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
'use strict';

let babel = require('gulp-babel');
let babelify = require('babelify');
let browserify = require('browserify');
let childProcess = require('child_process');
let del = require('del');
let gulp = require('gulp');
let path = require('path');
let source = require('vinyl-source-stream');
let uglify = require('gulp-uglifyjs');

const isRelease = process.env.NODE_ENV === 'production';

const CLIENT_SRC = [
    'client/js/libs/handlebars.js',
    'client/js/libs/handlebars/**/*.js',
    'client/js/libs/jquery.js',
    'client/js/libs/jquery/**/*.js',
    'client/js/libs/moment.js',
    'client/js/libs/stringcolor.js',
    'client/js/libs/uri.js',
];

const SERVER_SRC = [
    './server/**/*.js'
];

const DIST_SERVER = './dist/server/';
const DIST_CLIENT = './dist/client/';
const DIST_CLIENT_OBJ = path.resolve(DIST_CLIENT, './__obj/');
const DIST_CLIENT_JS = path.resolve(DIST_CLIENT, './js/');
const NPM_MOD_DIR = path.resolve(__dirname, './node_modules/');

/**
 *  # The rules of task name
 *
 *  ## public task
 *  - This is completed in itself.
 *  - This is callable as `gulp <taskname>`.
 *
 *  ## private task
 *  - This has some sideeffect in dependent task trees
 *    and it cannot recovery by self.
 *  - This is __callable only from public task__.
 *    DONT CALL as `gulp <taskname>`.
 *  - MUST name `__taskname`.
 */

gulp.task('__uglify', ['clean:client'], function () {
    return gulp.src(CLIENT_SRC)
        .pipe(uglify('libs.min.js', {
            compress: false,
        }))
        .pipe(gulp.dest(DIST_CLIENT_JS));
});

gulp.task('__handlebars', ['clean:client'], function () {
    let handlebars = path.resolve(NPM_MOD_DIR, './handlebars/bin/handlebars');
    let args = [
        String(handlebars),
        'client/views/',
        '-e', 'tpl',
        '-f', path.resolve(DIST_CLIENT_JS, './karen.templates.js'),
    ];

    let option = {
        cwd: path.relative(__dirname, ''),
        stdio: 'inherit',
    };
    childProcess.spawn('node', args, option);
});

gulp.task('__cp_client', ['clean:client'], function () {
    return gulp.src('./client/script/**/*.js')
        .pipe(gulp.dest(DIST_CLIENT_OBJ));
});

gulp.task('__typescript', ['clean:client'], function (callback) {
    const args = [
        path.join(NPM_MOD_DIR, './.bin', 'tsc'),
    ];
    const option = {
        cwd: path.relative(__dirname, ''),
        stdio: 'inherit',
    };
    const tsc = childProcess.spawn('iojs', args, option);
    tsc.on('exit', callback);
});

gulp.task('__browserify', ['clean:client', '__cp_client', '__typescript'], function () {
    const ENTRY_POINT = [
        path.resolve(DIST_CLIENT_OBJ, './karen.js'),
    ];

    const option = {
        insertGlobals: false,
        debug: !isRelease,
    };

    const babel = babelify.configure({
        optional: [],
    });

    return browserify(ENTRY_POINT, option)
        .transform(babel)
        .bundle()
        .pipe(source('karen.js'))
        .pipe(gulp.dest(DIST_CLIENT_JS));
});

gulp.task('jslint', function (callback) {
    const src = [
        './gulpfile.js',
        './client/script/',
        './defaults/',
        './server/',
    ];

    const bin = path.join(NPM_MOD_DIR, './.bin', 'eslint');

    const args = [
        '--ext', '.js',
    ].concat(src);

    const option = {
        cwd: path.relative(__dirname, ''),
        stdio: 'inherit',
    };

    const eslint = childProcess.spawn(bin, args, option);
    eslint.on('exit', callback);
});

gulp.task('__babel:server', ['clean:server'], function () {
    return gulp.src(SERVER_SRC)
        .pipe(babel({
            // For io.js, we need not some transforms:
            blacklist: [
                'es6.blockScoping',
                'es6.classes',
                'es6.constants',
                'es6.forOf',
                'es6.properties.shorthand',
                'es6.templateLiterals',
            ],
            sourceMaps: false,
        }))
        .pipe(gulp.dest(DIST_SERVER));
});

gulp.task('clean:client', function () {
    const deleter = function (dir) {
        return new Promise(function(resolve){
            del(path.join(dir, '**', '*.*'), resolve);
        });
    };

    const obj = deleter(DIST_CLIENT_OBJ);
    const dist = deleter(DIST_CLIENT);

    return Promise.all([obj, dist]);
});

gulp.task('clean:server', function (callback) {
    return del(path.join(DIST_SERVER, '**', '*.*'), callback);
});

gulp.task('__build:server', ['__babel:server']);
gulp.task('__build:client', ['__handlebars', '__uglify', '__browserify']);

gulp.task('build:server', ['jslint', '__build:server']);
gulp.task('build:client', ['jslint', '__build:client']);
gulp.task('build', ['jslint', '__build:client', '__build:server']);
gulp.task('clean', ['clean:client', 'clean:server']);
gulp.task('default', ['build']);
<commit_msg>Fix the build fails on Windows.<commit_after>/**
 * @license MIT License
 *
 * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
'use strict';

let babel = require('gulp-babel');
let babelify = require('babelify');
let browserify = require('browserify');
let childProcess = require('child_process');
let del = require('del');
let gulp = require('gulp');
let path = require('path');
let source = require('vinyl-source-stream');
let uglify = require('gulp-uglifyjs');

const isRelease = process.env.NODE_ENV === 'production';

const CLIENT_SRC = [
    'client/js/libs/handlebars.js',
    'client/js/libs/handlebars/**/*.js',
    'client/js/libs/jquery.js',
    'client/js/libs/jquery/**/*.js',
    'client/js/libs/moment.js',
    'client/js/libs/stringcolor.js',
    'client/js/libs/uri.js',
];

const SERVER_SRC = [
    './server/**/*.js'
];

const DIST_SERVER = './dist/server/';
const DIST_CLIENT = './dist/client/';
const DIST_CLIENT_OBJ = path.resolve(DIST_CLIENT, './__obj/');
const DIST_CLIENT_JS = path.resolve(DIST_CLIENT, './js/');
const NPM_MOD_DIR = path.resolve(__dirname, './node_modules/');

/**
 *  # The rules of task name
 *
 *  ## public task
 *  - This is completed in itself.
 *  - This is callable as `gulp <taskname>`.
 *
 *  ## private task
 *  - This has some sideeffect in dependent task trees
 *    and it cannot recovery by self.
 *  - This is __callable only from public task__.
 *    DONT CALL as `gulp <taskname>`.
 *  - MUST name `__taskname`.
 */

gulp.task('__uglify', ['clean:client'], function () {
    return gulp.src(CLIENT_SRC)
        .pipe(uglify('libs.min.js', {
            compress: false,
        }))
        .pipe(gulp.dest(DIST_CLIENT_JS));
});

gulp.task('__handlebars', ['clean:client'], function () {
    let handlebars = path.resolve(NPM_MOD_DIR, './handlebars/bin/handlebars');
    let args = [
        String(handlebars),
        'client/views/',
        '-e', 'tpl',
        '-f', path.resolve(DIST_CLIENT_JS, './karen.templates.js'),
    ];

    let option = {
        cwd: path.relative(__dirname, ''),
        stdio: 'inherit',
    };
    childProcess.spawn('node', args, option);
});

gulp.task('__cp_client', ['clean:client'], function () {
    return gulp.src('./client/script/**/*.js')
        .pipe(gulp.dest(DIST_CLIENT_OBJ));
});

gulp.task('__typescript', ['clean:client'], function (callback) {
    const args = [
        path.resolve(NPM_MOD_DIR, './typescript', './bin', './tsc'),
    ];
    const option = {
        cwd: path.relative(__dirname, ''),
        stdio: 'inherit',
    };
    const tsc = childProcess.spawn('iojs', args, option);
    tsc.on('exit', callback);
});

gulp.task('__browserify', ['clean:client', '__cp_client', '__typescript'], function () {
    const ENTRY_POINT = [
        path.resolve(DIST_CLIENT_OBJ, './karen.js'),
    ];

    const option = {
        insertGlobals: false,
        debug: !isRelease,
    };

    const babel = babelify.configure({
        optional: [],
    });

    return browserify(ENTRY_POINT, option)
        .transform(babel)
        .bundle()
        .pipe(source('karen.js'))
        .pipe(gulp.dest(DIST_CLIENT_JS));
});

gulp.task('jslint', function (callback) {
    const src = [
        './gulpfile.js',
        './client/script/',
        './defaults/',
        './server/',
    ];

    const bin = path.resolve(NPM_MOD_DIR, './eslint', './bin', './eslint.js');

    const args = [
        bin,
        '--ext', '.js',
    ].concat(src);

    const option = {
        cwd: path.relative(__dirname, ''),
        stdio: 'inherit',
    };

    const eslint = childProcess.spawn('iojs', args, option);
    eslint.on('exit', callback);
});

gulp.task('__babel:server', ['clean:server'], function () {
    return gulp.src(SERVER_SRC)
        .pipe(babel({
            // For io.js, we need not some transforms:
            blacklist: [
                'es6.blockScoping',
                'es6.classes',
                'es6.constants',
                'es6.forOf',
                'es6.properties.shorthand',
                'es6.templateLiterals',
            ],
            sourceMaps: false,
        }))
        .pipe(gulp.dest(DIST_SERVER));
});

gulp.task('clean:client', function () {
    const deleter = function (dir) {
        return new Promise(function(resolve){
            del(path.join(dir, '**', '*.*'), resolve);
        });
    };

    const obj = deleter(DIST_CLIENT_OBJ);
    const dist = deleter(DIST_CLIENT);

    return Promise.all([obj, dist]);
});

gulp.task('clean:server', function (callback) {
    return del(path.join(DIST_SERVER, '**', '*.*'), callback);
});

gulp.task('__build:server', ['__babel:server']);
gulp.task('__build:client', ['__handlebars', '__uglify', '__browserify']);

gulp.task('build:server', ['jslint', '__build:server']);
gulp.task('build:client', ['jslint', '__build:client']);
gulp.task('build', ['jslint', '__build:client', '__build:server']);
gulp.task('clean', ['clean:client', 'clean:server']);
gulp.task('default', ['build']);
<|endoftext|>


<commit_before>var gulp       = require('gulp'),
    gulpif     = require('gulp-if'),
    less       = require('gulp-less'),
    concat     = require('gulp-concat'),
    minifyCSS  = require('gulp-minify-css'),
    uglify     = require('gulp-uglify'),
    watch      = require('gulp-watch'),
    rename     = require('gulp-rename'),
    imagemin   = require('gulp-imagemin'),
    argv       = require('yargs').argv,
    prefix     = require('gulp-autoprefixer'),
    connect    = require('gulp-connect'),
    shell      = require('gulp-shell'),
    rev        = require('gulp-rev');

// Options
var options = {
    target: argv.target || 'public',
    host: argv.host || 'localhost',
    port: argv.port || 8000,
    env: argv.env || 'local',
    livereload: argv.livereload || false
};

// Is a production build
var IS_PROD_BUILD = (options.env === 'production');

// Error catcher
function swallowError (err) {
    console.error(err);
    throw err;
}

// Compile Less and save to stylesheets directory
gulp.task('less', function () {

    var destDir = options.target + '/assets/stylesheets/',
        destFile = 'bootstrap.css';

    return gulp.src('source/assets/stylesheets/bootstrap.less')
        .pipe(less())
        .on('error', swallowError)
        .pipe(prefix('last 2 versions', '> 1%', 'Explorer 7', 'Android 2'))
        .pipe(gulpif(IS_PROD_BUILD, minifyCSS()))
        .pipe(rename(destFile))
        .pipe(gulp.dest(destDir));
});

// Publish Images
gulp.task('images', function () {
    if (IS_PROD_BUILD) {
        var destDir = options.target + '/assets/images';

        return gulp.src('source/assets/images/*')
            .pipe(imagemin({
                progressive: true,
                svgoPlugins: [{removeViewBox: false}]
            }))
            .pipe(gulp.dest(destDir));
    }
});

// Publish JavaScript
gulp.task('js', function () {

    var destDir = options.target + '/assets/javascripts/',
        destFile = 'app.js';

    return gulp.src([
            'source/assets/javascripts/bootstrap-modal.js',
            'source/assets/javascripts/bootstrap-dropdown.js',
            'source/assets/javascripts/bootstrap-scrollspy.js',
            'source/assets/javascripts/bootstrap-tabs.js',
            'source/assets/javascripts/bootstrap-twipsy.js',
            'source/assets/javascripts/bootstrap-popover.js',
            'source/assets/javascripts/default.js'
        ])
        .on('error', swallowError)
        .pipe(concat(destFile))
        .pipe(gulpif(IS_PROD_BUILD, uglify()))
        .pipe(gulp.dest(destDir));
});

// Webserver
gulp.task('webserver', function() {
    connect.server({
        host: options.host,
        port: options.port,
        livereload: options.livereload,
        root: options.target
    });
});

// Run skosh build command on pages
gulp.task('compile-pages', shell.task([
    'php skosh build --part=pages'
]));

// Run skosh build command on static content
gulp.task('compile-images', shell.task([
    'php skosh build --part=static'
]));

// What tasks does running gulp trigger?
gulp.task('default', ['build']);

gulp.task('serve', ['compile-pages', 'compile-images', 'webserver', 'watch']);

gulp.task('watch', ['build'], function() {
    gulp.watch('source/assets/stylesheets/**/*.less', ['less']);
    gulp.watch('source/assets/javascripts/**/*.js', ['js']);
    gulp.watch('source/assets/images/*', ['compile-images']);
    gulp.watch('source/**/*.{textile,twig,md}', ['compile-pages']);
});

gulp.task('build', ['images', 'less', 'js'], function () {
    // Create manifest of assets
    if (IS_PROD_BUILD) {
        return gulp.src(options.target + '/assets/**/*.{css,js,svg,png,gif,jpg,jpeg}')
            .pipe(gulp.dest(options.target + '/assets/'))
            .pipe(rev())
            .pipe(gulp.dest(options.target + '/assets/'))
            .pipe(rev.manifest())
            .pipe(gulp.dest('./'));
    }
});<commit_msg>Cleanup gulp<commit_after>var gulp       = require('gulp'),
    gulpif     = require('gulp-if'),
    less       = require('gulp-less'),
    concat     = require('gulp-concat'),
    minifyCSS  = require('gulp-minify-css'),
    uglify     = require('gulp-uglify'),
    watch      = require('gulp-watch'),
    rename     = require('gulp-rename'),
    imagemin   = require('gulp-imagemin'),
    argv       = require('yargs').argv,
    prefix     = require('gulp-autoprefixer'),
    connect    = require('gulp-connect'),
    shell      = require('gulp-shell'),
    rev        = require('gulp-rev');

// Options
var options = {
    target: argv.target || 'public',
    host: argv.host || 'localhost',
    port: argv.port || 8000,
    env: argv.env || 'local',
    livereload: argv.livereload || false
};

// Is a production build
var IS_PROD_BUILD = (options.env === 'production');

// Error catcher
function swallowError (err) {
    console.error(err);
    throw err;
}

// Compile Less and save to stylesheets directory
gulp.task('less', function () {

    var destDir = options.target + '/assets/stylesheets/',
        destFile = 'bootstrap.css';

    return gulp.src('source/assets/stylesheets/bootstrap.less')
        .pipe(less())
        .on('error', swallowError)
        .pipe(prefix('last 2 versions', '> 1%', 'Explorer 7', 'Android 2'))
        .pipe(gulpif(IS_PROD_BUILD, minifyCSS()))
        .pipe(rename(destFile))
        .pipe(gulp.dest(destDir));
});

// Publish Images
gulp.task('images', function () {
    if (IS_PROD_BUILD) {
        var destDir = options.target + '/assets/images';

        return gulp.src('source/assets/images/*')
            .pipe(imagemin({
                progressive: true,
                svgoPlugins: [{removeViewBox: false}]
            }))
            .pipe(gulp.dest(destDir));
    }
});

// Publish JavaScript
gulp.task('js', function () {

    var destDir = options.target + '/assets/javascripts/',
        destFile = 'app.js';

    return gulp.src([
            'source/assets/javascripts/bootstrap-modal.js',
            'source/assets/javascripts/bootstrap-dropdown.js',
            'source/assets/javascripts/bootstrap-scrollspy.js',
            'source/assets/javascripts/bootstrap-tabs.js',
            'source/assets/javascripts/bootstrap-twipsy.js',
            'source/assets/javascripts/bootstrap-popover.js',
            'source/assets/javascripts/default.js'
        ])
        .on('error', swallowError)
        .pipe(concat(destFile))
        .pipe(gulpif(IS_PROD_BUILD, uglify()))
        .pipe(gulp.dest(destDir));
});

// Webserver
gulp.task('webserver', function() {
    connect.server({
        host: options.host,
        port: options.port,
        livereload: options.livereload,
        root: options.target
    });
});

// Run skosh build command on pages
gulp.task('compile-pages', shell.task([
    'php skosh build --part=pages'
]));

// Run skosh build command on static content
gulp.task('compile-images', shell.task([
    'php skosh build --part=static'
]));

// What tasks does running gulp trigger?
gulp.task('default', ['build']);

gulp.task('serve', ['webserver', 'watch']);

gulp.task('watch', ['compile-pages', 'compile-images', 'build'], function() {
    gulp.watch('source/assets/stylesheets/**/*.less', ['less']);
    gulp.watch('source/assets/javascripts/**/*.js', ['js']);
    gulp.watch('source/assets/images/*', ['compile-images']);
    gulp.watch('source/**/*.{textile,twig,md}', ['compile-pages']);
});

gulp.task('build', ['images', 'less', 'js'], function () {
    // Create manifest of assets
    if (IS_PROD_BUILD) {
        return gulp.src(options.target + '/assets/**/*.{css,js,svg,png,gif,jpg,jpeg}')
            .pipe(gulp.dest(options.target + '/assets/'))
            .pipe(rev())
            .pipe(gulp.dest(options.target + '/assets/'))
            .pipe(rev.manifest())
            .pipe(gulp.dest('./'));
    }
});<|endoftext|>


<commit_before>var babelify = require('babelify');
var browserify = require('browserify');
var gulp = require('gulp');
var gulpPlumber = require('gulp-plumber');
var gulpRename = require('gulp-rename');
var vinylTransform  = require('vinyl-transform');
var vinylSourceStream  = require('vinyl-source-stream');

var JS_REQUIREMENTS = [
  'backbone',
  'react'
];

var WATCHED_ES6_SOURCES = [
  './es6/**/*.es6'
];

//var bundleES6 = function bundleES6() {
//  return transform(function(fileName) {
//    return browserify(fileName, {
//        debug: true
//      })
//      .transform(babelify)
//      .require()
//      .bundle()
//      .on('error', function(err){
//        console.error(err.message);
//        this.emit('end');
//      })
//    ;
//  });
//}

var onError = function onError(err) {
  console.error(err.stack || err);
  this.emit('end');
};

gulp.task('build-js-simple', function() {
  return browserify('./js/use-requirements.js', {
      debug: true
    })
    .bundle()
    .pipe(vinylSourceStream('bundle.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('build-js-requirements', function() {
  return browserify({
      debug: true
    })
    .require(JS_REQUIREMENTS)
    .bundle()
    .pipe(vinylSourceStream('requirements.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('build-js-app', function() {
  return browserify('./js/index.js', {
      debug: true
    })
    .external(JS_REQUIREMENTS)
    .bundle()
    .pipe(vinylSourceStream('bundle.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('build-es6-simple', function() {
  return browserify('./es6/index.es6', {
      debug: true,
      extensions: ['.es6']
    })
    .transform(babelify)
    .bundle()
    .pipe(vinylSourceStream('bundle.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('build-es6-app', function() {
  return browserify('./es6/index.es6', {
      debug: true,
      extensions: ['.es6']
    })
    .transform(babelify)
    .external(JS_REQUIREMENTS)
    .bundle()
    // これで標準エラー処理を書き換えているので、コンパイル時にエラーに成っても終了しない
    // watch が落ちないのはいいけど、build が正常終了になる
    // 今のところ、同じようなタスクを2つ作って、片方はonError外すという方法しか不明
    .on('error', onError)
    .pipe(vinylSourceStream('bundle.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('watch-es6', function() {
  gulp.watch(WATCHED_ES6_SOURCES, function() {
    return gulp.start('build-es6-app');
  });
});
<commit_msg>Refactoring<commit_after>var babelify = require('babelify');
var browserify = require('browserify');
var gulp = require('gulp');
var gulpPlumber = require('gulp-plumber');
var gulpRename = require('gulp-rename');
var vinylTransform  = require('vinyl-transform');
var vinylSourceStream  = require('vinyl-source-stream');

var JS_REQUIREMENTS = [
  'backbone',
  'react'
];

var WATCHED_ES6_SOURCES = [
  './es6/**/*.es6'
];

//var bundleES6 = function bundleES6() {
//  return transform(function(fileName) {
//    return browserify(fileName, {
//        debug: true
//      })
//      .transform(babelify)
//      .require()
//      .bundle()
//      .on('error', function(err){
//        console.error(err.message);
//        this.emit('end');
//      })
//    ;
//  });
//}

var onIgnoreError = function onIgnoreError(err) {
  console.error(err.stack || err);
  this.emit('end');
};

gulp.task('build-js-simple', function() {
  return browserify('./js/use-requirements.js', {
      debug: true
    })
    .bundle()
    .pipe(vinylSourceStream('bundle.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('build-js-requirements', function() {
  return browserify({
      debug: true
    })
    .require(JS_REQUIREMENTS)
    .bundle()
    .pipe(vinylSourceStream('requirements.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('build-js-app', function() {
  return browserify('./js/index.js', {
      debug: true
    })
    .external(JS_REQUIREMENTS)
    .bundle()
    .pipe(vinylSourceStream('bundle.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('build-es6-simple', function() {
  return browserify('./es6/index.es6', {
      debug: true,
      extensions: ['.es6']
    })
    .transform(babelify)
    .bundle()
    .pipe(vinylSourceStream('bundle.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('build-es6-app', function() {
  return browserify('./es6/index.es6', {
      debug: true,
      extensions: ['.es6']
    })
    .transform(babelify)
    .external(JS_REQUIREMENTS)
    .bundle()
    // これで標準エラー処理を書き換えているので、コンパイル時にエラーに成っても終了しない
    // watch が落ちないのはいいけど、build が正常終了になる
    // 今のところ、同じようなタスクを2つ作って、片方は外すという方法しか不明
    .on('error', onIgnoreError)
    .pipe(vinylSourceStream('bundle.js'))
    .pipe(gulp.dest('./public'))
  ;
});

gulp.task('watch-es6', function() {
  gulp.watch(WATCHED_ES6_SOURCES, function() {
    return gulp.start('build-es6-app');
  });
});
<|endoftext|>