<commit_before>/**
 * @providesModule Notifications
 */

'use strict';

var RNNotificationsComponent = require( './component' );

var AppState = RNNotificationsComponent.state;
var RNNotifications = RNNotificationsComponent.component;

var Platform = require('react-native').Platform;

var Notifications = {
	handler: RNNotifications,
	onRegister: false,
	onError: false,
	onNotification: false,
  onRemoteFetch: false,
	isLoaded: false,
	hasPoppedInitialNotification: false,

	isPermissionsRequestPending: false,

	permissions: {
		alert: true,
		badge: true,
		sound: true
	}
};

Notifications.callNative = function(name: String, params: Array) {
	if ( typeof this.handler[name] === 'function' ) {
		if ( typeof params !== 'array' &&
			 typeof params !== 'object' ) {
			params = [];
		}

		return this.handler[name](...params);
	} else {
		return null;
	}
};

/**
 * Configure local and remote notifications
 * @param {Object}		options
 * @param {function}	options.onRegister - Fired when the user registers for remote notifications.
 * @param {function}	options.onNotification - Fired when a remote notification is received.
 * @param {function} 	options.onError - None
 * @param {Object}		options.permissions - Permissions list
 * @param {Boolean}		options.requestPermissions - Check permissions when register
 */
Notifications.configure = function(options: Object) {
	if ( typeof options.onRegister !== 'undefined' ) {
		this.onRegister = options.onRegister;
	}

	if ( typeof options.onError !== 'undefined' ) {
		this.onError = options.onError;
	}

	if ( typeof options.onNotification !== 'undefined' ) {
		this.onNotification = options.onNotification;
	}

	if ( typeof options.permissions !== 'undefined' ) {
		this.permissions = options.permissions;
	}

	if ( typeof options.senderID !== 'undefined' ) {
		this.senderID = options.senderID;
	}

	if ( typeof options.onRemoteFetch !== 'undefined' ) {
		this.onRemoteFetch = options.onRemoteFetch;
	}

	if ( this.isLoaded === false ) {
		this._onRegister = this._onRegister.bind(this);
		this._onNotification = this._onNotification.bind(this);
		this._onRemoteFetch = this._onRemoteFetch.bind(this);
		this.callNative( 'addEventListener', [ 'register', this._onRegister ] );
		this.callNative( 'addEventListener', [ 'notification', this._onNotification ] );
		this.callNative( 'addEventListener', [ 'localNotification', this._onNotification ] );
		Platform.OS === 'android' ? this.callNative( 'addEventListener', [ 'remoteFetch', this._onRemoteFetch ] ) : null

		this.isLoaded = true;
	}

	if ( this.hasPoppedInitialNotification === false &&
			( options.popInitialNotification === undefined || options.popInitialNotification === true ) ) {
		this.popInitialNotification(function(firstNotification) {
			if ( firstNotification !== null ) {
				this._onNotification(firstNotification, true);
			}
		}.bind(this));
		this.hasPoppedInitialNotification = true;
	}

	if ( options.requestPermissions !== false ) {
		this._requestPermissions();
	}

};

/* Unregister */
Notifications.unregister = function() {
	this.callNative( 'removeEventListener', [ 'register', this._onRegister ] )
	this.callNative( 'removeEventListener', [ 'notification', this._onNotification ] )
	this.callNative( 'removeEventListener', [ 'localNotification', this._onNotification ] )
	Platform.OS === 'android' ? this.callNative( 'removeEventListener', [ 'remoteFetch', this._onRemoteFetch ] ) : null
	this.isLoaded = false;
};

/**
 * Local Notifications
 * @param {Object}		details
 * @param {String}		details.message - The message displayed in the notification alert.
 * @param {String}		details.title  -  ANDROID ONLY: The title displayed in the notification alert.
 * @param {String}		details.ticker -  ANDROID ONLY: The ticker displayed in the status bar.
 * @param {Object}		details.userInfo -  iOS ONLY: The userInfo used in the notification alert.
 */
Notifications.localNotification = function(details: Object) {
	if ( Platform.OS === 'ios' ) {
		// https://developer.apple.com/reference/uikit/uilocalnotification

		let soundName = details.soundName ? details.soundName : 'default'; // play sound (and vibrate) as default behaviour

		if (details.hasOwnProperty('playSound') && !details.playSound) {
			soundName = ''; // empty string results in no sound (and no vibration)
		}

		// for valid fields see: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/IPhoneOSClientImp.html
		// alertTitle only valid for apple watch: https://developer.apple.com/library/ios/documentation/iPhone/Reference/UILocalNotification_Class/#//apple_ref/occ/instp/UILocalNotification/alertTitle

		this.handler.presentLocalNotification({
			alertTitle: details.title,
			alertBody: details.message,
			alertAction: details.alertAction,
			category: details.category,
			soundName: soundName,
			applicationIconBadgeNumber: details.number,
			userInfo: details.userInfo
		});
	} else {
		this.handler.presentLocalNotification(details);
	}
};

/**
 * Local Notifications Schedule
 * @param {Object}		details (same as localNotification)
 * @param {Date}		details.date - The date and time when the system should deliver the notification
 */
Notifications.localNotificationSchedule = function(details: Object) {
	if ( Platform.OS === 'ios' ) {
		let soundName = details.soundName ? details.soundName : 'default'; // play sound (and vibrate) as default behaviour

		if (details.hasOwnProperty('playSound') && !details.playSound) {
			soundName = ''; // empty string results in no sound (and no vibration)
		}

		const iosDetails = {
			fireDate: details.date.toISOString(),
			alertBody: details.message,
			soundName: soundName,
			applicationIconBadgeNumber: parseInt(details.number, 10),
			userInfo: details.userInfo,
			repeatInterval: details.repeatType
		}
		// ignore Android only repeatType
		if (!details.repeatType || details.repeatType === 'time') {
			delete iosDetails.repeatInterval;
		}
		this.handler.scheduleLocalNotification(iosDetails);
	} else {
		details.fireDate = details.date.getTime();
		delete details.date;
		// ignore iOS only repeatType
		if (['year', 'month'].includes(details.repeatType)) {
			delete details.repeatType;
		}
		this.handler.scheduleLocalNotification(details);
	}
};

/* Internal Functions */
Notifications._onRegister = function(token: String) {
	if ( this.onRegister !== false ) {
		this.onRegister({
			token: token,
			os: Platform.OS
		});
	}
};

Notifications._onRemoteFetch = function(notificationData: Object) {
	if ( this.onRemoteFetch !== false ) {
		this.onRemoteFetch(notificationData)
	}
};

Notifications._onNotification = function(data, isFromBackground = null) {
	if ( isFromBackground === null ) {
		isFromBackground = (
			data.foreground === false ||
			AppState.currentState === 'background'
		);
	}

	if ( this.onNotification !== false ) {
		if ( Platform.OS === 'ios' ) {
			this.onNotification({
				foreground: ! isFromBackground,
				userInteraction: isFromBackground,
				message: data.getMessage(),
				data: data.getData(),
				badge: data.getBadgeCount(),
				alert: data.getAlert(),
				sound: data.getSound()
			});
		} else {
			var notificationData = {
				foreground: ! isFromBackground,
				...data
			};

			if ( typeof notificationData.data === 'string' ) {
				try {
					notificationData.data = JSON.parse(notificationData.data);
				} catch(e) {
					/* void */
				}
			}

			this.onNotification(notificationData);
		}
	}
};

/* onResultPermissionResult */
Notifications._onPermissionResult = function() {
	this.isPermissionsRequestPending = false;
};

// Prevent requestPermissions called twice if ios result is pending
Notifications._requestPermissions = function() {
	if ( Platform.OS === 'ios' ) {
		if ( this.isPermissionsRequestPending === false ) {
			this.isPermissionsRequestPending = true;
			return this.callNative( 'requestPermissions', [ this.permissions ])
							.then(this._onPermissionResult.bind(this))
							.catch(this._onPermissionResult.bind(this));
		}
	} else if ( typeof this.senderID !== 'undefined' ) {
		return this.callNative( 'requestPermissions', [ this.senderID ]);
	}
};

// Stock requestPermissions function
Notifications.requestPermissions = function() {
	if ( Platform.OS === 'ios' ) {
		return this.callNative( 'requestPermissions', [ this.permissions ]);
	} else if ( typeof this.senderID !== 'undefined' ) {
		return this.callNative( 'requestPermissions', [ this.senderID ]);
	}
};

/* Fallback functions */
Notifications.presentLocalNotification = function() {
	return this.callNative('presentLocalNotification', arguments);
};

Notifications.scheduleLocalNotification = function() {
	return this.callNative('scheduleLocalNotification', arguments);
};

Notifications.cancelLocalNotifications = function() {
	return this.callNative('cancelLocalNotifications', arguments);
};

Notifications.cancelAllLocalNotifications = function() {
	return this.callNative('cancelAllLocalNotifications', arguments);
};

Notifications.setApplicationIconBadgeNumber = function() {
	return this.callNative('setApplicationIconBadgeNumber', arguments);
};

Notifications.getApplicationIconBadgeNumber = function() {
	return this.callNative('getApplicationIconBadgeNumber', arguments);
};

Notifications.popInitialNotification = function(handler) {
	this.callNative('getInitialNotification').then(function(result){
		handler(result);
	});
};

Notifications.abandonPermissions = function() {
	return this.callNative('abandonPermissions', arguments);
};

Notifications.checkPermissions = function() {
	return this.callNative('checkPermissions', arguments);
};

Notifications.registerNotificationActions = function() {
	return this.callNative('registerNotificationActions', arguments)
}

Notifications.clearAllNotifications = function() {
	// Only available for Android
	return this.callNative('clearAllNotifications', arguments)
}

module.exports = Notifications;
<commit_msg>made the conversion from `details.number` to applicationIconBadgeNumber in the ios code a bit more forgiving.  now `details.number` is optional (as it says in the docs)<commit_after>/**
 * @providesModule Notifications
 */

'use strict';

var RNNotificationsComponent = require( './component' );

var AppState = RNNotificationsComponent.state;
var RNNotifications = RNNotificationsComponent.component;

var Platform = require('react-native').Platform;

var Notifications = {
	handler: RNNotifications,
	onRegister: false,
	onError: false,
	onNotification: false,
  onRemoteFetch: false,
	isLoaded: false,
	hasPoppedInitialNotification: false,

	isPermissionsRequestPending: false,

	permissions: {
		alert: true,
		badge: true,
		sound: true
	}
};

Notifications.callNative = function(name: String, params: Array) {
	if ( typeof this.handler[name] === 'function' ) {
		if ( typeof params !== 'array' &&
			 typeof params !== 'object' ) {
			params = [];
		}

		return this.handler[name](...params);
	} else {
		return null;
	}
};

/**
 * Configure local and remote notifications
 * @param {Object}		options
 * @param {function}	options.onRegister - Fired when the user registers for remote notifications.
 * @param {function}	options.onNotification - Fired when a remote notification is received.
 * @param {function} 	options.onError - None
 * @param {Object}		options.permissions - Permissions list
 * @param {Boolean}		options.requestPermissions - Check permissions when register
 */
Notifications.configure = function(options: Object) {
	if ( typeof options.onRegister !== 'undefined' ) {
		this.onRegister = options.onRegister;
	}

	if ( typeof options.onError !== 'undefined' ) {
		this.onError = options.onError;
	}

	if ( typeof options.onNotification !== 'undefined' ) {
		this.onNotification = options.onNotification;
	}

	if ( typeof options.permissions !== 'undefined' ) {
		this.permissions = options.permissions;
	}

	if ( typeof options.senderID !== 'undefined' ) {
		this.senderID = options.senderID;
	}

	if ( typeof options.onRemoteFetch !== 'undefined' ) {
		this.onRemoteFetch = options.onRemoteFetch;
	}

	if ( this.isLoaded === false ) {
		this._onRegister = this._onRegister.bind(this);
		this._onNotification = this._onNotification.bind(this);
		this._onRemoteFetch = this._onRemoteFetch.bind(this);
		this.callNative( 'addEventListener', [ 'register', this._onRegister ] );
		this.callNative( 'addEventListener', [ 'notification', this._onNotification ] );
		this.callNative( 'addEventListener', [ 'localNotification', this._onNotification ] );
		Platform.OS === 'android' ? this.callNative( 'addEventListener', [ 'remoteFetch', this._onRemoteFetch ] ) : null

		this.isLoaded = true;
	}

	if ( this.hasPoppedInitialNotification === false &&
			( options.popInitialNotification === undefined || options.popInitialNotification === true ) ) {
		this.popInitialNotification(function(firstNotification) {
			if ( firstNotification !== null ) {
				this._onNotification(firstNotification, true);
			}
		}.bind(this));
		this.hasPoppedInitialNotification = true;
	}

	if ( options.requestPermissions !== false ) {
		this._requestPermissions();
	}

};

/* Unregister */
Notifications.unregister = function() {
	this.callNative( 'removeEventListener', [ 'register', this._onRegister ] )
	this.callNative( 'removeEventListener', [ 'notification', this._onNotification ] )
	this.callNative( 'removeEventListener', [ 'localNotification', this._onNotification ] )
	Platform.OS === 'android' ? this.callNative( 'removeEventListener', [ 'remoteFetch', this._onRemoteFetch ] ) : null
	this.isLoaded = false;
};

/**
 * Local Notifications
 * @param {Object}		details
 * @param {String}		details.message - The message displayed in the notification alert.
 * @param {String}		details.title  -  ANDROID ONLY: The title displayed in the notification alert.
 * @param {String}		details.ticker -  ANDROID ONLY: The ticker displayed in the status bar.
 * @param {Object}		details.userInfo -  iOS ONLY: The userInfo used in the notification alert.
 */
Notifications.localNotification = function(details: Object) {
	if ( Platform.OS === 'ios' ) {
		// https://developer.apple.com/reference/uikit/uilocalnotification

		let soundName = details.soundName ? details.soundName : 'default'; // play sound (and vibrate) as default behaviour

		if (details.hasOwnProperty('playSound') && !details.playSound) {
			soundName = ''; // empty string results in no sound (and no vibration)
		}

		// for valid fields see: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/IPhoneOSClientImp.html
		// alertTitle only valid for apple watch: https://developer.apple.com/library/ios/documentation/iPhone/Reference/UILocalNotification_Class/#//apple_ref/occ/instp/UILocalNotification/alertTitle

		this.handler.presentLocalNotification({
			alertTitle: details.title,
			alertBody: details.message,
			alertAction: details.alertAction,
			category: details.category,
			soundName: soundName,
			applicationIconBadgeNumber: details.number,
			userInfo: details.userInfo
		});
	} else {
		this.handler.presentLocalNotification(details);
	}
};

/**
 * Local Notifications Schedule
 * @param {Object}		details (same as localNotification)
 * @param {Date}		details.date - The date and time when the system should deliver the notification
 */
Notifications.localNotificationSchedule = function(details: Object) {
	if ( Platform.OS === 'ios' ) {
		let soundName = details.soundName ? details.soundName : 'default'; // play sound (and vibrate) as default behaviour

		if (details.hasOwnProperty('playSound') && !details.playSound) {
			soundName = ''; // empty string results in no sound (and no vibration)
		}

		const iosDetails = {
			fireDate: details.date.toISOString(),
			alertBody: details.message,
			soundName: soundName,
			userInfo: details.userInfo,
			repeatInterval: details.repeatType
		};

		if(details.number) {
			iosDetails.applicationIconBadgeNumber = parseInt(details.number, 10);
		}

		// ignore Android only repeatType
		if (!details.repeatType || details.repeatType === 'time') {
			delete iosDetails.repeatInterval;
		}
		this.handler.scheduleLocalNotification(iosDetails);
	} else {
		details.fireDate = details.date.getTime();
		delete details.date;
		// ignore iOS only repeatType
		if (['year', 'month'].includes(details.repeatType)) {
			delete details.repeatType;
		}
		this.handler.scheduleLocalNotification(details);
	}
};

/* Internal Functions */
Notifications._onRegister = function(token: String) {
	if ( this.onRegister !== false ) {
		this.onRegister({
			token: token,
			os: Platform.OS
		});
	}
};

Notifications._onRemoteFetch = function(notificationData: Object) {
	if ( this.onRemoteFetch !== false ) {
		this.onRemoteFetch(notificationData)
	}
};

Notifications._onNotification = function(data, isFromBackground = null) {
	if ( isFromBackground === null ) {
		isFromBackground = (
			data.foreground === false ||
			AppState.currentState === 'background'
		);
	}

	if ( this.onNotification !== false ) {
		if ( Platform.OS === 'ios' ) {
			this.onNotification({
				foreground: ! isFromBackground,
				userInteraction: isFromBackground,
				message: data.getMessage(),
				data: data.getData(),
				badge: data.getBadgeCount(),
				alert: data.getAlert(),
				sound: data.getSound()
			});
		} else {
			var notificationData = {
				foreground: ! isFromBackground,
				...data
			};

			if ( typeof notificationData.data === 'string' ) {
				try {
					notificationData.data = JSON.parse(notificationData.data);
				} catch(e) {
					/* void */
				}
			}

			this.onNotification(notificationData);
		}
	}
};

/* onResultPermissionResult */
Notifications._onPermissionResult = function() {
	this.isPermissionsRequestPending = false;
};

// Prevent requestPermissions called twice if ios result is pending
Notifications._requestPermissions = function() {
	if ( Platform.OS === 'ios' ) {
		if ( this.isPermissionsRequestPending === false ) {
			this.isPermissionsRequestPending = true;
			return this.callNative( 'requestPermissions', [ this.permissions ])
							.then(this._onPermissionResult.bind(this))
							.catch(this._onPermissionResult.bind(this));
		}
	} else if ( typeof this.senderID !== 'undefined' ) {
		return this.callNative( 'requestPermissions', [ this.senderID ]);
	}
};

// Stock requestPermissions function
Notifications.requestPermissions = function() {
	if ( Platform.OS === 'ios' ) {
		return this.callNative( 'requestPermissions', [ this.permissions ]);
	} else if ( typeof this.senderID !== 'undefined' ) {
		return this.callNative( 'requestPermissions', [ this.senderID ]);
	}
};

/* Fallback functions */
Notifications.presentLocalNotification = function() {
	return this.callNative('presentLocalNotification', arguments);
};

Notifications.scheduleLocalNotification = function() {
	return this.callNative('scheduleLocalNotification', arguments);
};

Notifications.cancelLocalNotifications = function() {
	return this.callNative('cancelLocalNotifications', arguments);
};

Notifications.cancelAllLocalNotifications = function() {
	return this.callNative('cancelAllLocalNotifications', arguments);
};

Notifications.setApplicationIconBadgeNumber = function() {
	return this.callNative('setApplicationIconBadgeNumber', arguments);
};

Notifications.getApplicationIconBadgeNumber = function() {
	return this.callNative('getApplicationIconBadgeNumber', arguments);
};

Notifications.popInitialNotification = function(handler) {
	this.callNative('getInitialNotification').then(function(result){
		handler(result);
	});
};

Notifications.abandonPermissions = function() {
	return this.callNative('abandonPermissions', arguments);
};

Notifications.checkPermissions = function() {
	return this.callNative('checkPermissions', arguments);
};

Notifications.registerNotificationActions = function() {
	return this.callNative('registerNotificationActions', arguments)
}

Notifications.clearAllNotifications = function() {
	// Only available for Android
	return this.callNative('clearAllNotifications', arguments)
}

module.exports = Notifications;
<|endoftext|>


<commit_before>var path = require("path");
var to5  = require("6to5-core");
var fs   = require("fs");
var _    = require("lodash");

module.exports = function (opts) {
  opts = _.defaults(opts || {}, {
    options: {},
    dest:    "cache",
    src:     "assets"
  });

  var cache = Object.create(null);

  return function (req, res, next) {
    var url = req.url;
    if (!to5.canCompile(url)) return next();

    var dest = path.join(opts.dest, url);
    var src  = path.join(opts.src, url);
    var destStat;

    var write = function (transformed) {
      fs.writeFile(dest, transformed, function (err) {
        if (err) {
          next(err);
        } else {
          cache[url] = Date.now();
          next();
        }
      });
    };

    var compile = function () {
      var transformOpts = _.clone(opts.options);

      to5.transformFile(src, transformOpts, function (err, result) {
        if (err) return next(err);
        write(result.code);
      });
    };

    var destExists = function () {
      if (cache[url] < +destStat.mtime) {
        compile();
      } else {
        next();
      }
    };

    fs.stat(src, function (err, stat) {
      if (err && err.code === 'ENOENT') return next();
      else if (err) return next(err);

      fs.stat(dest, function (err, stat) {
        if (err && err.code !== 'ENOENT') return next(err);
        destStat = stat;

        if (!err && cache[dest]) {
          destExists();
        } else {
          compile();
        }
      });
    });
  };
};
<commit_msg>Use source mtime instead of `Date.now()`.<commit_after>var path = require("path");
var to5  = require("6to5-core");
var fs   = require("fs");
var _    = require("lodash");

module.exports = function (opts) {
  opts = _.defaults(opts || {}, {
    options: {},
    dest:    "cache",
    src:     "assets"
  });

  var cache = Object.create(null);

  return function (req, res, next) {
    var url = req.url;
    if (!to5.canCompile(url)) return next();

    var dest = path.join(opts.dest, url);
    var src  = path.join(opts.src, url);
    var srcStat, destStat;

    var write = function (transformed) {
      fs.writeFile(dest, transformed, function (err) {
        if (err) {
          next(err);
        } else {
          cache[url] = +srcStat.mtime;
          next();
        }
      });
    };

    var compile = function () {
      var transformOpts = _.clone(opts.options);

      to5.transformFile(src, transformOpts, function (err, result) {
        if (err) return next(err);
        write(result.code);
      });
    };

    var destExists = function () {
      if (cache[url] < +destStat.mtime) {
        compile();
      } else {
        next();
      }
    };

    fs.stat(src, function (err, stat) {
      if (err && err.code === 'ENOENT') return next();
      else if (err) return next(err);
      srcStat = stat;

      fs.stat(dest, function (err, stat) {
        if (err && err.code !== 'ENOENT') return next(err);
        destStat = stat;

        if (!err && cache[dest]) {
          destExists();
        } else {
          compile();
        }
      });
    });
  };
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var fs = require('fs');
var resolve = require('resolve');
var minimatch = require('minimatch');
var browserBuiltins = require('browser-builtins');

var startClientFile = path.normalize(__dirname + '/start-client.js');

function framework(files) {
  files.push({
    pattern: startClientFile,
    included: true,
    served: true,
    watched: false
  });
}

function createPreprocessor(config, basePath, logger) {
  var log = logger.create('preprocessor.common_js');
  var seenNpmFiles = [];
  var npmFilesPerModule = {};
  var transforms = config.transforms || {};
  var autostartPatterns = config.autoRequire || ['**/*.js'];

  function shouldAutoStart(filepath) {
    for (var i = 0; i < autostartPatterns.length; i++) {
      if (minimatch(filepath, autostartPatterns[i])) {
        return true;
      }
    }
    return false;
  }

  function process(content, file, done) {
    log.debug('Processing "%s"', file.originalPath);
    // operations contains the number of files to process that
    // this scope is currently waiting for. If it's 0 at the end
    // of the scope it means we don't have to wait, and we can call
    // `done()`
    var operations = 0;

    var filePath = path.dirname(file.originalPath);
    var wrappedContent = '';

    var aliases = '';

    var wrapperHead =
      'window.__cjsModules = window.__cjsModules || {};' +
      'window.__cjsModules["' + file.originalPath + '"] = ' +
        'function (require, module, exports, global, __filename, __dirname, process) {';
    var wrapperFoot = '\n};window.__cjsModules["' + file.originalPath + '"].autostart = ' + shouldAutoStart(file.originalPath);

    // If the file is something other than a .js file, we have
    // to add .js to make Karma serve it as a js file.
    // This is for things like transforming an .html file
    // to a CommonJS module.
    if (file.path.indexOf('.js') !== file.path.length - 3) {
      file.path = file.path + '.js';
    }

    // If a file was reloaded that contained one or more
    // modules from node_modules, we have to make sure
    // that we reload them as well by removing them from
    // seenNpmFiles
    if (npmFilesPerModule[file.originalPath]) {
      npmFilesPerModule[file.originalPath].forEach(function (npmModulePath) {
        seenNpmFiles.splice(seenNpmFiles.indexOf(npmModulePath), 1);
      });
    }

    function replaceModuleName(match, moduleName) {
      var modulePath;
      try {
        if (moduleName.charAt(0) === '.') {
          modulePath = require.resolve(path.resolve(filePath, moduleName));
        } else {
          if (moduleName in browserBuiltins) {
            modulePath = browserBuiltins[moduleName];
          } else {
            var opts = {
              basedir: filePath,
              packageFilter: function (info) {
                if (typeof info.browserify === 'string' && !info.browser) {
                  info.browser = info.browserify;
                }

                if (!info.browser) {
                  return info;
                }
                // replace main
                if (typeof info.browser === 'string') {
                  info.main = info.browser;
                  return info;
                }
                var replaceMain = info.browser[info.main || './index.js'] || info.browser['./' + info.main || './index.js'];
                info.main = replaceMain || info.main;
                return info;
              }
            };
            modulePath = resolve.sync(moduleName, opts);

            // In the client we need to be able to map the npm name to
            // the absolute path, since we allow stubbing out modules.
            // So when you say you want to stub out 'jquery' in the client
            // we need to know the physical path to the jquery file.
            aliases +=
              'window.__cjsModuleAliases = window.__cjsModuleAliases || {};' +
              'window.__cjsModuleAliases["' + moduleName + '"] = "' + modulePath + '";';
          }
        }
        log.debug('Replacing require "%s" with "%s"', moduleName, modulePath);
      } catch (e) {
        modulePath = moduleName;
        log.debug('Replacing require "%s" with "%s"', moduleName, modulePath);
      }

      // Since you don't want to specify your npm modules in karma.conf.js, we check
      // for a node_modules folder in it's path. If we see it, it means that
      // we have to call `process()` on in because Karma won't call `process()` for
      // us with that file.
      // This means that if `my-module.js` requires `jquery` from node_modules,
      // we'll append the contents of `jquery` in `my-module.js` when karma serves it.
      // This has the unfortunate behaviour that any error in jquery.js will be seen
      // as the error occured in `my-module.js`, but there's not a lot to be about that.
      // At least you get the correct line numbers for errors in `my-module.js`.
      if (modulePath.indexOf('/node_modules/') !== -1 && seenNpmFiles.indexOf(modulePath) === -1) {
        operations++;

        seenNpmFiles.push(modulePath);
        if (!npmFilesPerModule[file.originalPath]) {
          npmFilesPerModule[file.originalPath] = [];
        }
        npmFilesPerModule[file.originalPath].push(modulePath);

        fs.readFile(modulePath, function (err, npmFileContent) {
          if (err) {
            log.error('Cannot read "%s"', modulePath);
            return;
          }

          process(npmFileContent.toString(), {originalPath: modulePath, path: modulePath}, function (npmContent) {
            operations--;
            wrappedContent += '\n' + npmContent;
            if (!operations) {
              log.debug('Done processing "%s"', file.originalPath);
              done(wrappedContent);
            }
          });
        });
      }
      return match.replace(/require\(.*?\)/, 'require("' + modulePath + '")');
    }

    var processedContent = content;

    // Allow Browserify streams to process the file first
    Object.keys(transforms).forEach(function (transformName) {
      if (transforms[transformName].exclude) {
        var excludePatterns = [];
        if (!Array.isArray(transforms[transformName].exclude)) {
          excludePatterns.push(transforms[transformName].exclude);
        } else {
          excludePatterns = transforms[transformName].exclude;
        }

        for (var i = 0; i < excludePatterns.length; i++) {
          var pattern = excludePatterns[i];
          if (minimatch(file.originalPath, pattern)) {
            log.debug('Excluding "' + file.originalPath + '" for the "' + transformName + '" transform');
            return;
          }
        }
      }
      log.debug('Running transform "' + transformName + '" on "' + file.originalPath + '"');
      var transformer = require(transformName);
      var stream = transformer(file.originalPath);

      stream.on('data', function (d) {
        processedContent = d;
      });
      stream.write(processedContent);
      stream.end();
    });

    var usesGlobalBuffer = (processedContent.indexOf('new Buffer') !== -1);
    var isBufferModule = (file.originalPath.indexOf('browser-builtins/node_modules/buffer/index.js') !== -1);

    // If any module uses the global Buffer constructor, we want to replace that with a call to require it first
    if (usesGlobalBuffer && !isBufferModule) {
      processedContent = processedContent.replace(/new Buffer/g, "new require('buffer').Buffer");
    }

    if (/\.json$/.test(file.originalPath)) {
      processedContent = 'module.exports = ' + processedContent;
    } else {
      processedContent = processedContent.replace(/^(?!\s*[\/\/|\*]).*require\(["']([^\)]+)["'][,\)]/mg, replaceModuleName);
    }

    wrappedContent = aliases + wrapperHead + processedContent + wrapperFoot;

    if (!operations) {
      log.debug('Done processing "%s"', file.originalPath);
      done(wrappedContent);
    }
  }

  return process;
}

framework.$inject = ['config.files'];
createPreprocessor.$inject = ['config.common_js', 'config.basePath', 'logger'];

module.exports = {
  'framework:common_js': ['factory', framework],
  'preprocessor:common_js': ['factory', createPreprocessor]
};
<commit_msg>[added] require('text!abc.html') support<commit_after>'use strict';

var path = require('path');
var fs = require('fs');
var resolve = require('resolve');
var minimatch = require('minimatch');
var browserBuiltins = require('browser-builtins');

var startClientFile = path.normalize(__dirname + '/start-client.js');

function framework(files) {
  files.push({
    pattern: startClientFile,
    included: true,
    served: true,
    watched: false
  });
}

function createPreprocessor(config, basePath, logger) {
  var log = logger.create('preprocessor.common_js');
  var seenNpmFiles = [];
  var npmFilesPerModule = {};
  var transforms = config.transforms || {};
  var autostartPatterns = config.autoRequire || ['**/*.js'];

  function shouldAutoStart(filepath) {
    for (var i = 0; i < autostartPatterns.length; i++) {
      if (minimatch(filepath, autostartPatterns[i])) {
        return true;
      }
    }
    return false;
  }

  function process(content, file, done) {
    log.debug('Processing "%s"', file.originalPath);
    // operations contains the number of files to process that
    // this scope is currently waiting for. If it's 0 at the end
    // of the scope it means we don't have to wait, and we can call
    // `done()`
    var operations = 0;

    var filePath = path.dirname(file.originalPath);
    var wrappedContent = '';

    var aliases = '';

    var wrapperHead =
      'window.__cjsModules = window.__cjsModules || {};' +
      'window.__cjsModules["' + file.originalPath + '"] = ' +
        'function (require, module, exports, global, __filename, __dirname, process) {';
    var wrapperFoot = '\n};window.__cjsModules["' + file.originalPath + '"].autostart = ' + shouldAutoStart(file.originalPath);

    // If the file is something other than a .js file, we have
    // to add .js to make Karma serve it as a js file.
    // This is for things like transforming an .html file
    // to a CommonJS module.
    if (file.path.indexOf('.js') !== file.path.length - 3) {
      file.path = file.path + '.js';
    }

    // If a file was reloaded that contained one or more
    // modules from node_modules, we have to make sure
    // that we reload them as well by removing them from
    // seenNpmFiles
    if (npmFilesPerModule[file.originalPath]) {
      npmFilesPerModule[file.originalPath].forEach(function (npmModulePath) {
        seenNpmFiles.splice(seenNpmFiles.indexOf(npmModulePath), 1);
      });
    }

    function replaceModuleName(match, moduleName) {
      var modulePath;
      try {
        var cap = moduleName.match(/^\w+!(.+)$/)
        if(cap)
          moduleName = cap[1];

        if (moduleName.charAt(0) === '.') {
          modulePath = require.resolve(path.resolve(filePath, moduleName));
        } else {
          if (moduleName in browserBuiltins) {
            modulePath = browserBuiltins[moduleName];
          } else {
            var opts = {
              basedir: filePath,
              packageFilter: function (info) {
                if (typeof info.browserify === 'string' && !info.browser) {
                  info.browser = info.browserify;
                }

                if (!info.browser) {
                  return info;
                }
                // replace main
                if (typeof info.browser === 'string') {
                  info.main = info.browser;
                  return info;
                }
                var replaceMain = info.browser[info.main || './index.js'] || info.browser['./' + info.main || './index.js'];
                info.main = replaceMain || info.main;
                return info;
              }
            };
            modulePath = resolve.sync(moduleName, opts);

            // In the client we need to be able to map the npm name to
            // the absolute path, since we allow stubbing out modules.
            // So when you say you want to stub out 'jquery' in the client
            // we need to know the physical path to the jquery file.
            aliases +=
              'window.__cjsModuleAliases = window.__cjsModuleAliases || {};' +
              'window.__cjsModuleAliases["' + moduleName + '"] = "' + modulePath + '";';
          }
        }
        log.debug('Replacing require "%s" with "%s"', moduleName, modulePath);
      } catch (e) {
        modulePath = moduleName;
        log.debug('Replacing require "%s" with "%s"', moduleName, modulePath);
      }

      // Since you don't want to specify your npm modules in karma.conf.js, we check
      // for a node_modules folder in it's path. If we see it, it means that
      // we have to call `process()` on in because Karma won't call `process()` for
      // us with that file.
      // This means that if `my-module.js` requires `jquery` from node_modules,
      // we'll append the contents of `jquery` in `my-module.js` when karma serves it.
      // This has the unfortunate behaviour that any error in jquery.js will be seen
      // as the error occured in `my-module.js`, but there's not a lot to be about that.
      // At least you get the correct line numbers for errors in `my-module.js`.
      if (modulePath.indexOf('/node_modules/') !== -1 && seenNpmFiles.indexOf(modulePath) === -1) {
        operations++;

        seenNpmFiles.push(modulePath);
        if (!npmFilesPerModule[file.originalPath]) {
          npmFilesPerModule[file.originalPath] = [];
        }
        npmFilesPerModule[file.originalPath].push(modulePath);

        fs.readFile(modulePath, function (err, npmFileContent) {
          if (err) {
            log.error('Cannot read "%s"', modulePath);
            return;
          }

          process(npmFileContent.toString(), {originalPath: modulePath, path: modulePath}, function (npmContent) {
            operations--;
            wrappedContent += '\n' + npmContent;
            if (!operations) {
              log.debug('Done processing "%s"', file.originalPath);
              done(wrappedContent);
            }
          });
        });
      }
      return match.replace(/require\(.*?\)/, 'require("' + modulePath + '")');
    }

    var processedContent = content;

    // Allow Browserify streams to process the file first
    Object.keys(transforms).forEach(function (transformName) {
      if (transforms[transformName].exclude) {
        var excludePatterns = [];
        if (!Array.isArray(transforms[transformName].exclude)) {
          excludePatterns.push(transforms[transformName].exclude);
        } else {
          excludePatterns = transforms[transformName].exclude;
        }

        for (var i = 0; i < excludePatterns.length; i++) {
          var pattern = excludePatterns[i];
          if (minimatch(file.originalPath, pattern)) {
            log.debug('Excluding "' + file.originalPath + '" for the "' + transformName + '" transform');
            return;
          }
        }
      }
      log.debug('Running transform "' + transformName + '" on "' + file.originalPath + '"');
      var transformer = require(transformName);
      var stream = transformer(file.originalPath);

      stream.on('data', function (d) {
        processedContent = d;
      });
      stream.write(processedContent);
      stream.end();
    });

    var usesGlobalBuffer = (processedContent.indexOf('new Buffer') !== -1);
    var isBufferModule = (file.originalPath.indexOf('browser-builtins/node_modules/buffer/index.js') !== -1);

    // If any module uses the global Buffer constructor, we want to replace that with a call to require it first
    if (usesGlobalBuffer && !isBufferModule) {
      processedContent = processedContent.replace(/new Buffer/g, "new require('buffer').Buffer");
    }

    if (/\.json$/.test(file.originalPath)) {
      processedContent = 'module.exports = ' + processedContent;
    } else {
      processedContent = processedContent.replace(/^(?!\s*[\/\/|\*]).*require\(["']([^\)]+)["'][,\)]/mg, replaceModuleName);
    }

    wrappedContent = aliases + wrapperHead + processedContent + wrapperFoot;

    if (!operations) {
      log.debug('Done processing "%s"', file.originalPath);
      done(wrappedContent);
    }
  }

  return process;
}

framework.$inject = ['config.files'];
createPreprocessor.$inject = ['config.common_js', 'config.basePath', 'logger'];

module.exports = {
  'framework:common_js': ['factory', framework],
  'preprocessor:common_js': ['factory', createPreprocessor]
};
<|endoftext|>


<commit_before>var assert = require('assert');
var tzdata = require('./lib/tzdata.js');
exports.tzdata = tzdata;

var _Date = Date;
exports._Date = _Date;

var timezone;

var HOUR = 60 * 60 * 1000;

var date_iso_8601_regex=/^\d\d\d\d(-\d\d(-\d\d(T\d\d\:\d\d\:\d\d(\.\d\d\d)?Z?)?)?)?$/;
var date_with_offset=/^\d\d\d\d-\d\d-\d\d \d\d\:\d\d\:\d\d(\.\d\d\d)? (Z|(\-|\+|)\d\d\:\d\d)$/;
var date_rfc_2822_regex=/^\d\d-\w\w\w-\d\d\d\d \d\d\:\d\d\:\d\d (\+|-)\d\d\d\d$/;
var local_date_regex=/^\d\d\d\d-\d\d-\d\d \d\d\:\d\d\:\d\d(\.\d\d\d)?$/;

function MockDate(param) {
  if (arguments.length === 1) {
    if (param instanceof MockDate) {
      this.d = new _Date(param.d);
    } else if (typeof param === 'string') {
      if (param.match(date_iso_8601_regex) || param.match(date_with_offset) || param.match(date_rfc_2822_regex)) {
        this.d = new _Date(param);
      } else if (param.match(local_date_regex)) {
        this.d = new _Date();
        this.fromLocal(new _Date(param.replace(' ', 'T')));
      } else {
        assert.ok(false, 'Unhandled date format passed to MockDate constructor: ' + param);
      }
    } else if (typeof param === 'number') {
      this.d = new _Date(param);
    } else {
      assert.ok(false, 'Unhandled type passed to MockDate constructor: ' + typeof param);
    }
  } else {
    this.d = new _Date();
    this.fromLocal(new _Date(_Date.UTC.apply(null, arguments)));
  }
}

MockDate.prototype.calcTZO = function (ts) {
  var data = tzdata[timezone];
  assert.ok(data, 'Unsupported timezone: ' + timezone);
  ts = (ts || this.d.getTime()) / 1000;
  for (var ii = 2; ii < data.transitions.length; ii+=2) {
    if (data.transitions[ii] > ts) {
      return -data.transitions[ii-1];
    }
  }
  assert.ok(false, ts);
};

function passthrough(fn) {
  MockDate.prototype[fn] = function () {
    var real_date;
    if (this instanceof MockDate) {
      real_date = this.d;
    } else if (this instanceof _Date) {
      // console.log calls our prototype to format regular Date objects!
      // This should only be hit while debugging MockDate itself though, as
      // there should be no _Date objects in user code when using MockDate.
      real_date = this;
    } else {
      assert(false, 'Unexpected object type');
    }
    return real_date[fn].apply(real_date, arguments);
  };
}
function localgetter(fn) {
  MockDate.prototype[fn] = function () {
    var d = new _Date(this.d.getTime() - this.calcTZO() * HOUR);
    return d['getUTC' + fn.slice(3)]();
  };
}
MockDate.prototype.fromLocal = function(d) {
  // From a Date object in the fake-timezone where the returned UTC values are
  //   meant to be interpreted as local values.
  this.d.setTime(d.getTime() + this.calcTZO(d.getTime() + this.calcTZO(d.getTime()) * HOUR) * HOUR);
};
function localsetter(fn) {
  MockDate.prototype[fn] = function () {
    var d = new _Date(this.d.getTime() - this.calcTZO() * HOUR);
    d['setUTC' + fn.slice(3)].apply(d, arguments);
    this.fromLocal(d);
  };
}
[
  'getUTCDate',
  'getUTCDay',
  'getUTCFullYear',
  'getUTCHours',
  'getUTCMilliseconds',
  'getUTCMinutes',
  'getUTCMonth',
  'getUTCSeconds',
  'getTime',
  'setTime',
  'setUTCDate',
  'setUTCFullYear',
  'setUTCHours',
  'setUTCMilliseconds',
  'setUTCMinutes',
  'setUTCMonth',
  'setUTCSeconds',
  'toGMTString',
  'toISOString',
  'toJSON',
  'toUTCString',
].forEach(passthrough);
[
  'getDate',
  'getDay',
  'getFullYear',
  'getHours',
  'getMilliseconds',
  'getMinutes',
  'getMonth',
  'getSeconds',
].forEach(localgetter);
[
  'setDate',
  'setFullYear',
  'setHours',
  'setMilliseconds',
  'setMinutes',
  'setMonth',
  'setSeconds',
].forEach(localsetter);

MockDate.prototype.getYear = function () {
  return this.getFullYear() - 1900;
};

MockDate.prototype.setYear = function (yr) {
  if (yr < 1900) {
    return this.setFullYear(1900 + yr);
  }
  return this.setFullYear(yr);
};

MockDate.prototype.getTimezoneOffset = function () {
  return this.calcTZO() * 60;
};

MockDate.prototype.toString = MockDate.prototype.toLocaleString = function () {
  if (this instanceof _Date) {
    // someone, like util.inspect, calling Date.prototype.toString.call(foo)
    return _Date.prototype.toString.call(this);
  }
  return 'Mockday ' + this.d.toISOString() + ' GMT-0' + this.calcTZO() + '00 (MockDate)';
};

MockDate.now = _Date.now;

MockDate.UTC = _Date.UTC;

// TODO:
// 'toDateString',
// 'toLocaleDateString',
// 'toLocaleTimeString',
// 'toTimeString',

function register(new_timezone) {
  timezone = new_timezone || 'US/Pacific';
  global.Date = MockDate;
}
exports.register = register;

function unregister() {
  global.Date = _Date;
}
exports.unregister = unregister;
<commit_msg>Handle case when creating a Date with no arguments<commit_after>var assert = require('assert');
var tzdata = require('./lib/tzdata.js');
exports.tzdata = tzdata;

var _Date = Date;
exports._Date = _Date;

var timezone;

var HOUR = 60 * 60 * 1000;

var date_iso_8601_regex=/^\d\d\d\d(-\d\d(-\d\d(T\d\d\:\d\d\:\d\d(\.\d\d\d)?Z?)?)?)?$/;
var date_with_offset=/^\d\d\d\d-\d\d-\d\d \d\d\:\d\d\:\d\d(\.\d\d\d)? (Z|(\-|\+|)\d\d\:\d\d)$/;
var date_rfc_2822_regex=/^\d\d-\w\w\w-\d\d\d\d \d\d\:\d\d\:\d\d (\+|-)\d\d\d\d$/;
var local_date_regex=/^\d\d\d\d-\d\d-\d\d \d\d\:\d\d\:\d\d(\.\d\d\d)?$/;

function MockDate(param) {
  if (arguments.length === 0) {
    this.d = new _Date()
  } else if (arguments.length === 1) {
    if (param instanceof MockDate) {
      this.d = new _Date(param.d);
    } else if (typeof param === 'string') {
      if (param.match(date_iso_8601_regex) || param.match(date_with_offset) || param.match(date_rfc_2822_regex)) {
        this.d = new _Date(param);
      } else if (param.match(local_date_regex)) {
        this.d = new _Date();
        this.fromLocal(new _Date(param.replace(' ', 'T')));
      } else {
        assert.ok(false, 'Unhandled date format passed to MockDate constructor: ' + param);
      }
    } else if (typeof param === 'number') {
      this.d = new _Date(param);
    } else {
      assert.ok(false, 'Unhandled type passed to MockDate constructor: ' + typeof param);
    }
  } else {
    this.d = new _Date();
    this.fromLocal(new _Date(_Date.UTC.apply(null, arguments)));
  }
}

MockDate.prototype.calcTZO = function (ts) {
  var data = tzdata[timezone];
  assert.ok(data, 'Unsupported timezone: ' + timezone);
  ts = (ts || this.d.getTime()) / 1000;
  for (var ii = 2; ii < data.transitions.length; ii+=2) {
    if (data.transitions[ii] > ts) {
      return -data.transitions[ii-1];
    }
  }
  assert.ok(false, ts);
};

function passthrough(fn) {
  MockDate.prototype[fn] = function () {
    var real_date;
    if (this instanceof MockDate) {
      real_date = this.d;
    } else if (this instanceof _Date) {
      // console.log calls our prototype to format regular Date objects!
      // This should only be hit while debugging MockDate itself though, as
      // there should be no _Date objects in user code when using MockDate.
      real_date = this;
    } else {
      assert(false, 'Unexpected object type');
    }
    return real_date[fn].apply(real_date, arguments);
  };
}
function localgetter(fn) {
  MockDate.prototype[fn] = function () {
    var d = new _Date(this.d.getTime() - this.calcTZO() * HOUR);
    return d['getUTC' + fn.slice(3)]();
  };
}
MockDate.prototype.fromLocal = function(d) {
  // From a Date object in the fake-timezone where the returned UTC values are
  //   meant to be interpreted as local values.
  this.d.setTime(d.getTime() + this.calcTZO(d.getTime() + this.calcTZO(d.getTime()) * HOUR) * HOUR);
};
function localsetter(fn) {
  MockDate.prototype[fn] = function () {
    var d = new _Date(this.d.getTime() - this.calcTZO() * HOUR);
    d['setUTC' + fn.slice(3)].apply(d, arguments);
    this.fromLocal(d);
  };
}
[
  'getUTCDate',
  'getUTCDay',
  'getUTCFullYear',
  'getUTCHours',
  'getUTCMilliseconds',
  'getUTCMinutes',
  'getUTCMonth',
  'getUTCSeconds',
  'getTime',
  'setTime',
  'setUTCDate',
  'setUTCFullYear',
  'setUTCHours',
  'setUTCMilliseconds',
  'setUTCMinutes',
  'setUTCMonth',
  'setUTCSeconds',
  'toGMTString',
  'toISOString',
  'toJSON',
  'toUTCString',
].forEach(passthrough);
[
  'getDate',
  'getDay',
  'getFullYear',
  'getHours',
  'getMilliseconds',
  'getMinutes',
  'getMonth',
  'getSeconds',
].forEach(localgetter);
[
  'setDate',
  'setFullYear',
  'setHours',
  'setMilliseconds',
  'setMinutes',
  'setMonth',
  'setSeconds',
].forEach(localsetter);

MockDate.prototype.getYear = function () {
  return this.getFullYear() - 1900;
};

MockDate.prototype.setYear = function (yr) {
  if (yr < 1900) {
    return this.setFullYear(1900 + yr);
  }
  return this.setFullYear(yr);
};

MockDate.prototype.getTimezoneOffset = function () {
  return this.calcTZO() * 60;
};

MockDate.prototype.toString = MockDate.prototype.toLocaleString = function () {
  if (this instanceof _Date) {
    // someone, like util.inspect, calling Date.prototype.toString.call(foo)
    return _Date.prototype.toString.call(this);
  }
  return 'Mockday ' + this.d.toISOString() + ' GMT-0' + this.calcTZO() + '00 (MockDate)';
};

MockDate.now = _Date.now;

MockDate.UTC = _Date.UTC;

// TODO:
// 'toDateString',
// 'toLocaleDateString',
// 'toLocaleTimeString',
// 'toTimeString',

function register(new_timezone) {
  timezone = new_timezone || 'US/Pacific';
  global.Date = MockDate;
}
exports.register = register;

function unregister() {
  global.Date = _Date;
}
exports.unregister = unregister;
<|endoftext|>


<commit_before>/**
 *@file index.js
 *@description 合并ajax请求 请求格式eg:
 *@author xtx1130
 *@example:
	$.ajax({
		url:'http://127.0.0.1:8086',
		type:'post',
		data:{
			0:{
				url:'http://url',
				type:'get',
				data:'qipuId=1'
			},
			1:{
				url:'http://url',
				type:'get',
				data:'qipuId=1'
			}
		},
		success:function(data){
			console.log(JSON.parse(data))
		}
	})
 *@tips:后台必须restful接口规则，规则相应修改见app/deps/httpRequest line 34
**/
'use strict';
const koa = require('koa');
//const env = require('./config/index.js');
//middleware
const midentryLog = require('./app/middleware/entryLog');
const res = require('./app/controller/res.js');
const combine = require('./app/middleware/interCombine');
const apis = require('./app/routes/apis');
const otherRouter = require('./app/routes/useless');
const rootRouter = require('./app/routes/rootRouter');
//const v8Router = require('./app/routes/v8test');
const helmet = require('koa-helmet');
const testing = require('testing');
const app = new koa();
let args = process.argv.slice(2);
let port = (args[0] && /^\d+$/.test(args[0])) ? parseInt(args[0]) : 8031;
//app.use(helmet());
//错误日志
let middleWare = [midentryLog,res,apis.routes(),combine,rootRouter.routes(),otherRouter.routes()];
let regester = (arg) => {
	arg.forEach(fn=>app.use(fn))
}
regester(middleWare)
// app.use(midentryLog);
// //res 500 404 200 option 以及跨域头
// app.use(res);
// //app.use(v8Router.routes(), v8Router.allowedMethods());
// app.use(apis.routes());
// app.use(apis.allowedMethods())
// app.use(combine);
// app.use(rootRouter.routes());
// app.use(rootRouter.allowedMethods());
// app.use(otherRouter.routes());
// app.use(otherRouter.allowedMethods())
app.listen(port);

//testing
let testStartServer = callback =>{
	let options = {
		port: 10531,
	};
	regester(middleWare)
	let server = app.listen(options.port)
	server.close(function(error){
		testing.check(error, 'Could not stop server', callback);
		testing.success(callback);
	});
}
module.exports.test = callback => {
	testing.run([testStartServer], 5000, callback);
};
console.log(`Server up and running! On port ${port}!`);<commit_msg>add test coverage for middleware:wrench:<commit_after>/**
 *@file index.js
 *@description 合并ajax请求 请求格式eg:
 *@author xtx1130
 *@example:
	$.ajax({
		url:'http://127.0.0.1:8086',
		type:'post',
		data:{
			0:{
				url:'http://url',
				type:'get',
				data:'qipuId=1'
			},
			1:{
				url:'http://url',
				type:'get',
				data:'qipuId=1'
			}
		},
		success:function(data){
			console.log(JSON.parse(data))
		}
	})
 *@tips:后台必须restful接口规则，规则相应修改见app/deps/httpRequest line 34
**/
'use strict';
const koa = require('koa');
//const env = require('./config/index.js');
//middleware
const midentryLog = require('./app/middleware/entryLog');
const res = require('./app/controller/res.js');
const combine = require('./app/middleware/interCombine');
const apis = require('./app/routes/apis');
const otherRouter = require('./app/routes/useless');
const rootRouter = require('./app/routes/rootRouter');
//const v8Router = require('./app/routes/v8test');
const helmet = require('koa-helmet');
const testing = require('testing');
const app = new koa();
let args = process.argv.slice(2);
let port = (args[0] && /^\d+$/.test(args[0])) ? parseInt(args[0]) : 8031;
//app.use(helmet());
//错误日志
let middleWare = [midentryLog,res,apis.routes(),combine,rootRouter.routes(),otherRouter.routes()];
let regester = (arg) => {
	arg.forEach(fn=>app.use(fn))
}
regester(middleWare)
// app.use(midentryLog);
// //res 500 404 200 option 以及跨域头
// app.use(res);
// //app.use(v8Router.routes(), v8Router.allowedMethods());
// app.use(apis.routes());
// app.use(apis.allowedMethods())
// app.use(combine);
// app.use(rootRouter.routes());
// app.use(rootRouter.allowedMethods());
// app.use(otherRouter.routes());
// app.use(otherRouter.allowedMethods())
app.listen(port);

//testing
let testStartServer = callback =>{
	let options = {
		port: 10531,
	};
	regester(middleWare)
	let server = app.listen(options.port)
	server.close(function(error){
		testing.check(error, 'Could not stop server', callback);
		testing.success(callback);
	});
}
if (__filename == process.argv[1])
{
	exports.test(testing.show);
}
module.exports.test = callback => {
	testing.run([testStartServer], 5000, callback);
};
console.log(`Server up and running! On port ${port}!`);<|endoftext|>


<commit_before>'use strict';

var
  express = require('express'),
  app = express(),
  parser = require('body-parser'),
  PORT = process.env.PORT;

app.use(parser.json());

app.get('/', function (req, res, next) {
  res.json('Welcome!!');
  return next();
});

app.get('/ping', function (req, res, next) {
  res.json('PONG');
  return next();
});

app.get('/notfound', function (req, res, next) {
  res.status(404).json('NotFound');
  return next();
});

app.post('/badrequest', function (req, res, next) {
  res.status(400).json('BadRequest');
  return next();
})

app.listen(port, function () {
  console.log('Server running with port', port);
});<commit_msg>Fix typo<commit_after>'use strict';

var
  express = require('express'),
  app = express(),
  parser = require('body-parser'),
  PORT = process.env.PORT;

app.use(parser.json());

app.get('/', function (req, res, next) {
  res.json('Welcome!!');
  return next();
});

app.get('/ping', function (req, res, next) {
  res.json('PONG');
  return next();
});

app.get('/notfound', function (req, res, next) {
  res.status(404).json('NotFound');
  return next();
});

app.post('/badrequest', function (req, res, next) {
  res.status(400).json('BadRequest');
  return next();
})

app.listen(PORT, function () {
  console.log('Server running with port', PORT);
});<|endoftext|>


<commit_before>var diff     = require('adiff').diff
var RArray   = require('r-array')
var inherits = require('util').inherits

function patch (a, changes) {
  changes.forEach(function (patch) {
    a.splice.apply(a, patch)
  })
  return a
}

function split(str) {
  return str.split('\n').map(function (l, i, a) {
    if(i != a.length - 1)
      return l + '\n'
    return l
  })
}

module.exports = REdit

inherits(REdit, RArray)

function REdit() {
  if(!(this instanceof REdit)) return new REdit()
  RArray.call(this)
}

var R = REdit.prototype

R.text  = function text (text) {
  if(!arguments.length)
    return this.toJSON().join('')

  var old = this.toJSON()
  text = split(text)
  //got to adjust the user's selection on the text area...
  var p = diff(old, text)
  patch(this, p)
}

R.wrap = function (ta) {
  var cursor = 0, start
  var self = this
  this.on('preupdate', function (ch) {
    //force update when recieve message.
    cursor = 0
    start = ta.selectionStart
    end   = ta.selectionEnd
    //what atom contains the cursor?
    var startKey, sum = 0
    for (var i in self.keys) {
      var key = self.keys[i]
      if((sum = self.store[key].length + sum) >= start) {
        startKey = key; break
      }
    }
    //how much will be inserted into the document?
    for(var key in ch) {
      if(key < startKey)
        cursor +=
          (ch[key] ? ch[key].length : 0)
        - (self.store[key] ? self.store[key].length : 0)
    }
    //THIS IS ACTUALLY WRONG. CAN'T insert into a selection!
    start = start + cursor
    end   = end   + cursor
  })
  this.on('_update', function (update) {
    if(update[2] !== self.id) {
      ta.value = self.toJSON().join('')
      ta.selectionStart = ta.selectionEnd = start
    }
  })
  var pending = false
  ta.addEventListener('input', function () {
    //if(pending) return
    //pending = true
    //setTimeout(function () {
    //pending = false
    self.text(ta.value)
    //}, 300)
  })
  ta.addEventListener('keydown', function () {
    start = ta.selectionStart
    end   = ta.selectionEnd
  })
  ta.addEventListener('focus', function () {
    ta.selectionStart = ta.selectionEnd = start
  })
  ta.value = this.text()

  return this
}
<commit_msg>unwrap textarea, incase you are using the same textarea multiple times!<commit_after>var diff     = require('adiff').diff
var RArray   = require('r-array')
var inherits = require('util').inherits

function patch (a, changes) {
  changes.forEach(function (patch) {
    a.splice.apply(a, patch)
  })
  return a
}

function split(str) {
  return str.split('\n').map(function (l, i, a) {
    if(i != a.length - 1)
      return l + '\n'
    return l
  })
}

module.exports = REdit

inherits(REdit, RArray)

function REdit() {
  if(!(this instanceof REdit)) return new REdit()
  RArray.call(this)
}

var R = REdit.prototype

R.text  = function text (text) {
  if(!arguments.length)
    return this.toJSON().join('')

  var old = this.toJSON()
  text = split(text)
  //got to adjust the user's selection on the text area...
  var p = diff(old, text)
  patch(this, p)
}

R.unwrap = function () {

}

R.wrap = function (ta) {
  var cursor = 0, start
  var self = this

  if(this.wrapped)
    throw new Error('rEdit is already wrapping a textarea. unwrap it first!')

  if(ta._rEditWrapper)
    ta._rEditWrapper.unwrap()
  ta._rEditWrapper = this
  this.wrapped = ta

  console.log('WRAP', this.text())
  ta.value = this.text()

  function onPreupdate (ch) {
    //force update when recieve message.
    cursor = 0
    start = ta.selectionStart
    end   = ta.selectionEnd
    //what atom contains the cursor?
    var startKey, sum = 0
    for (var i in self.keys) {
      var key = self.keys[i]
      if((sum = self.store[key].length + sum) >= start) {
        startKey = key; break
      }
    }
    //how much will be inserted into the document?
    for(var key in ch) {
      if(key < startKey)
        cursor +=
          (ch[key] ? ch[key].length : 0)
        - (self.store[key] ? self.store[key].length : 0)
    }
    //THIS IS ACTUALLY WRONG. CAN'T insert into a selection!
    start = start + cursor
    end   = end   + cursor
  }
  this.on('preupdate', onPreupdate)
  function on_update (update) {
    if(update[2] !== self.id) {
      ta.value = self.toJSON().join('')
      ta.selectionStart = ta.selectionEnd = start
    }
  }
  this.on('_update', on_update)
  var pending = false
  function onInput () {
    //if(pending) return
    //pending = true
    //setTimeout(function () {
    //pending = false
    self.text(ta.value)
    //}, 300)
  }
  function onKeydown () {
    start = ta.selectionStart
    end   = ta.selectionEnd
  }
  function onFocus () {
    ta.selectionStart = ta.selectionEnd = start
  }
  ta.addEventListener('input', onInput)
  ta.addEventListener('keydown', onKeydown)
  ta.addEventListener('focus', onFocus )

  this.unwrap = function () {
    ta.removeEventListener('input'  , onInput)
    ta.removeEventListener('keydown', onKeydown)
    ta.removeEventListener('focus'  , onFocus)
    this.removeListener('preupdate' , onPreupdate)
    this.removeListener('_update'   , on_update)
    this.unwrap = function () {}
  }

  return this
}
<|endoftext|>


<commit_before>/*
 * A Soundcloud plugin for CSH DJ.
 *
 * Configuration:
 *  auth: {
 *    client_id: "your_client_id_here",
 *    client_secret: "your_client_secret_here"
 *  }
 *
 */

var Q = require("q");
var soundcloud = require("soundclouder");

var log;

exports.display_name = "Soundcloud";

function format_result(result) {
	return {
		id: result.id,
		title: result.title,
		artist: result.user.username,
		thumbnail_url: result.artwork_url,
		image_url: result.artwork_url.replace("large", "t300x300")
	};
}

exports.init = function(_log, config) {
	var deferred = Q.defer();
	log = _log;

	if(!config.auth) {
		deferred.reject(new Error("Please configure auth settings."));
	}
	else if(!config.auth.client_id) {
		deferred.reject(new Error("Please configure client ID."));
	}
	else if(!config.auth.client_secret) {
		deferred.reject(new Error("Please configure client secret."));
	}
	else {
		soundcloud.init(config.auth.client_id, config.auth.client_secret, null);
		deferred.resolve();
	}

	return deferred.promise;
}

exports.search = function(max_results, query) {
	var deferred = Q.defer();

	soundcloud.get('/tracks', '', { q: query, limit: max_results }, function(error, data) {
		if(error) {
			deferred.reject(error);
			return;
		}

		deferred.resolve(data.map(format_result));
	});

	return deferred.promise;
}

exports.fetch = function(id, download_location) {
	var deferred = Q.defer();

	id = encodeURIComponent(id);
	var download_path = download_location + id + ".mp3";
	var ws = fs.createWriteStream(download_path);

	soundcloud.get('/tracks/' + id + '/stream', '', {}, function(error, data) {
		if(error) {
			deferred.reject(error);
			return;
		}

		ws.write(data);
		deferred.resolve(download_path);
	});

	return deferred.promise;
}
<commit_msg>Add fs require<commit_after>/*
 * A Soundcloud plugin for CSH DJ.
 *
 * Configuration:
 *  auth: {
 *    client_id: "your_client_id_here",
 *    client_secret: "your_client_secret_here"
 *  }
 *
 */

var Q = require("q");
var soundcloud = require("soundclouder");
var fs = require("fs");

var log;

exports.display_name = "Soundcloud";

function format_result(result) {
	return {
		id: result.id,
		title: result.title,
		artist: result.user.username,
		thumbnail_url: result.artwork_url,
		image_url: result.artwork_url.replace("large", "t300x300")
	};
}

exports.init = function(_log, config) {
	var deferred = Q.defer();
	log = _log;

	if(!config.auth) {
		deferred.reject(new Error("Please configure auth settings."));
	}
	else if(!config.auth.client_id) {
		deferred.reject(new Error("Please configure client ID."));
	}
	else if(!config.auth.client_secret) {
		deferred.reject(new Error("Please configure client secret."));
	}
	else {
		soundcloud.init(config.auth.client_id, config.auth.client_secret, null);
		deferred.resolve();
	}

	return deferred.promise;
}

exports.search = function(max_results, query) {
	var deferred = Q.defer();

	soundcloud.get('/tracks', '', { q: query, limit: max_results }, function(error, data) {
		if(error) {
			deferred.reject(error);
			return;
		}

		deferred.resolve(data.map(format_result));
	});

	return deferred.promise;
}

exports.fetch = function(id, download_location) {
	var deferred = Q.defer();

	id = encodeURIComponent(id);
	var download_path = download_location + id + ".mp3";
	var ws = fs.createWriteStream(download_path);

	soundcloud.get('/tracks/' + id + '/stream', '', {}, function(error, data) {
		if(error) {
			deferred.reject(error);
			return;
		}

		ws.write(data);
		deferred.resolve(download_path);
	});

	return deferred.promise;
}
<|endoftext|>


<commit_before>module.exports = require("./lib/unzippy");
<commit_msg>change index.js exports<commit_after>"use strict";

var Unzippy = require("./lib/unzippy.js"),
	Parser = require("./lib/parser.js")
	;

function unzippy(options) {
	return new Unzippy(options);
}

unzippy.Unzippy = Unzippy;
unzippy.Parser = Parser;

module.exports = unzippy;<|endoftext|>


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

var css = require('atomify-css')
  , js = require('atomify-js')
  , hb = require('handlebars')
  , program = require('commander')
  , fs = require('fs')
  , http = require('http')
  , lingo = require('lingo')
  , path = require('path')
  , atomify = require('atomify')
  , pkgPath = path.join(process.cwd(), 'package.json')
  , pkg = {}

if(fs.existsSync(pkgPath)) {
  pkg = require(pkgPath)
}

program
  .option('-c, --css [entry]', 'the entry file for the css, defaults to `./entry.css`', pkg.style || 'entry.css')
  .option('-j, --js [entry]', 'the entry file for the js, defaults to `./entry.js`', pkg.main || 'entry.js')
  .option('-o, --output [output]'
        , 'the name of the file to output to ' +
          '(eg. "bundle" will make "bundle.css" and "bundle.js")', "bundle")
  .option('atoms', 'will create an atoms directory and fill it with an atom for each common html tag.')
  .option('uncommon', 'will create atoms in the atoms directory for the uncommon html tags (run separately).')
  .option('test', 'will start a server to test your atom while you develop it.')
  .parse(process.argv)

var options = {
  js: {
    entry: path.join(process.cwd(), program.js)
  }
, css: {
    entry: path.join(process.cwd(), program.css)
  }
, output: program.output
}

var cssTemp = hb.compile('@import "../global";\n\
\n\
{{tagname}} {\n\
\n\
}\n\
');

var jsTemp = hb.compile("var Base = require('ribcage-view')\n\
\n\
var {{ctor}} = Base.extend({\n\
  tagname: '{{tagname}}'\n\
})\n\
\n\
module.exports = {{ctor}}\n\
");

// Lets build some atoms
if (program.atoms) {
  var common = [
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
    'address', 'p', 'hr', 'pre', 'blockquote',
    'ol', 'ul', 'li',
    'dl', 'dt', 'dd',
    'a', 'em', 'strong', 'small', 'code',
    'sub', 'sup', 'i', 'b', 'u',
    'span', 'ins', 'del',
    'img', 'video', 'audio', 'caption',
    'table', 'colgroup', 'col', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th',
    'form', 'fieldset', 'legend', 'label', 'input', 'button', 'select',
    'option', 'textarea', 'menu', 'menuitem'
  ];

  var uncommon = [
    'section', 'nav', 'article', 'aside', 'header', 'footer', 'main',
    's', 'cite', 'q', 'dfn', 'abbr', 'time', 'var', 'samp', 'kbd', 'mark',
    'ruby', 'rt', 'rp', 'bdi', 'bdo', 'br', 'wbr',
    'iframe', 'embed', 'object', 'param', 'source', 'track',
    'canvas', 'map', 'area', 'svg', 'math',
    'datalist', 'optgroup', 'keygen', 'progress', 'meter', 'summary', 'details'
  ];

  if (program.uncommon) {
    var tags = uncommon;
  } else {
    var tags = common;
  }

  if (!fs.existsSync('atoms')) {
    fs.mkdirSync('atoms');
  }

  for (var i in tags) {

    console.log('creating: '+tags[i]);

    if (fs.existsSync('atoms/'+tags[i])) {
      console.log('... already exists');
      continue;
    }

    fs.mkdirSync('atoms/'+tags[i]);

    var opts = {
      tagname: tags[i]
    , ctor: lingo.capitalize(tags[i])
    }
    fs.writeFileSync(path.join('atoms', tags[i], tags[i] + '.css'), cssTemp(opts));
    fs.writeFileSync(path.join('atoms', tags[i], tags[i] + '.js'), jsTemp(opts));

    var packageObj = {
      style: tags[i]+'.css'
    , main: tags[i]+'.js'
    }
    fs.writeFileSync(path.join('atoms', tags[i], 'package.json'), JSON.stringify(packageObj, null, 2));

  }

  console.log('done')

}
else if (program.test) {

  var opts = {}

  if (pkg.main) {
    opts.js = {entry: path.join(process.cwd(), pkg.main)}
  }

  if (pkg.style) {
    opts.css = {entry: path.join(process.cwd(), pkg.style)}
  }

  var atom = atomify(opts);

  var html = '<link href="/style.css" rel="stylesheet"/>'

  http.createServer(function (req, res) {

    console.log('requesting', req.url)

    if (req.url == '/style.css' && pkg.style) atom.css(req, res)
    else if (req.url == '/index.js' && pkg.main) atom.js(req, res)
    else if (req.url == '/') res.end(html)
    else {
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end('Not Found\n');
    }

  }).listen(9001);
  console.log('Server running at http://localhost:9001/');

}
// This is a normal bundle command
else {

  js(options.js, function (err, src) {
    if (err) return console.log('error:', err.stack)
    fs.writeFileSync(options.output+'.js', src);
  });

  if (fs.existsSync(options.css)) {
    css(options.css, function (err, src) {
      if (err) return console.log('error:', err.stack)
      fs.writeFileSync(options.output+'.css', src);
    });
  }

}
<commit_msg>Update help text<commit_after>#!/usr/bin/env node

var css = require('atomify-css')
  , js = require('atomify-js')
  , hb = require('handlebars')
  , program = require('commander')
  , fs = require('fs')
  , http = require('http')
  , lingo = require('lingo')
  , path = require('path')
  , atomify = require('atomify')
  , pkgPath = path.join(process.cwd(), 'package.json')
  , pkg = {}

if(fs.existsSync(pkgPath)) {
  pkg = require(pkgPath)
}

program
  .option('-c, --css [entry]', 'the entry file for the css, defaults to `package.json` style key, otherwise `./entry.css`', pkg.style || 'entry.css')
  .option('-j, --js [entry]', 'the entry file for the js, defaults to `package.json` main key, otherwise `./entry.js`', pkg.main || 'entry.js')
  .option('-o, --output [output]'
        , 'the name of the file to output to ' +
          '(eg. "bundle" will make "bundle.css" and "bundle.js")', "bundle")
  .option('atoms', 'will create an atoms directory and fill it with an atom for each common html tag.')
  .option('uncommon', 'will create atoms in the atoms directory for the uncommon html tags (run separately).')
  .option('test', 'will start a server to test your atom while you develop it.')
  .parse(process.argv)

var options = {
  js: {
    entry: path.join(process.cwd(), program.js)
  }
, css: {
    entry: path.join(process.cwd(), program.css)
  }
, output: program.output
}

var cssTemp = hb.compile('@import "../global";\n\
\n\
{{tagname}} {\n\
\n\
}\n\
');

var jsTemp = hb.compile("var Base = require('ribcage-view')\n\
\n\
var {{ctor}} = Base.extend({\n\
  tagname: '{{tagname}}'\n\
})\n\
\n\
module.exports = {{ctor}}\n\
");

// Lets build some atoms
if (program.atoms) {
  var common = [
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
    'address', 'p', 'hr', 'pre', 'blockquote',
    'ol', 'ul', 'li',
    'dl', 'dt', 'dd',
    'a', 'em', 'strong', 'small', 'code',
    'sub', 'sup', 'i', 'b', 'u',
    'span', 'ins', 'del',
    'img', 'video', 'audio', 'caption',
    'table', 'colgroup', 'col', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th',
    'form', 'fieldset', 'legend', 'label', 'input', 'button', 'select',
    'option', 'textarea', 'menu', 'menuitem'
  ];

  var uncommon = [
    'section', 'nav', 'article', 'aside', 'header', 'footer', 'main',
    's', 'cite', 'q', 'dfn', 'abbr', 'time', 'var', 'samp', 'kbd', 'mark',
    'ruby', 'rt', 'rp', 'bdi', 'bdo', 'br', 'wbr',
    'iframe', 'embed', 'object', 'param', 'source', 'track',
    'canvas', 'map', 'area', 'svg', 'math',
    'datalist', 'optgroup', 'keygen', 'progress', 'meter', 'summary', 'details'
  ];

  if (program.uncommon) {
    var tags = uncommon;
  } else {
    var tags = common;
  }

  if (!fs.existsSync('atoms')) {
    fs.mkdirSync('atoms');
  }

  for (var i in tags) {

    console.log('creating: '+tags[i]);

    if (fs.existsSync('atoms/'+tags[i])) {
      console.log('... already exists');
      continue;
    }

    fs.mkdirSync('atoms/'+tags[i]);

    var opts = {
      tagname: tags[i]
    , ctor: lingo.capitalize(tags[i])
    }
    fs.writeFileSync(path.join('atoms', tags[i], tags[i] + '.css'), cssTemp(opts));
    fs.writeFileSync(path.join('atoms', tags[i], tags[i] + '.js'), jsTemp(opts));

    var packageObj = {
      style: tags[i]+'.css'
    , main: tags[i]+'.js'
    }
    fs.writeFileSync(path.join('atoms', tags[i], 'package.json'), JSON.stringify(packageObj, null, 2));

  }

  console.log('done')

}
else if (program.test) {

  var opts = {}

  if (pkg.main) {
    opts.js = {entry: path.join(process.cwd(), pkg.main)}
  }

  if (pkg.style) {
    opts.css = {entry: path.join(process.cwd(), pkg.style)}
  }

  var atom = atomify(opts);

  var html = '<link href="/style.css" rel="stylesheet"/>'

  http.createServer(function (req, res) {

    console.log('requesting', req.url)

    if (req.url == '/style.css' && pkg.style) atom.css(req, res)
    else if (req.url == '/index.js' && pkg.main) atom.js(req, res)
    else if (req.url == '/') res.end(html)
    else {
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end('Not Found\n');
    }

  }).listen(9001);
  console.log('Server running at http://localhost:9001/');

}
// This is a normal bundle command
else {

  js(options.js, function (err, src) {
    if (err) return console.log('error:', err.stack)
    fs.writeFileSync(options.output+'.js', src);
  });

  if (fs.existsSync(options.css)) {
    css(options.css, function (err, src) {
      if (err) return console.log('error:', err.stack)
      fs.writeFileSync(options.output+'.css', src);
    });
  }

}
<|endoftext|>


<commit_before>var SQSWorker = require('sqs-worker');
var Accessory, Service, Characteristic, UUIDGen;

module.exports = function(homebridge) {

  // Accessory must be created from PlatformAccessory Constructor
  Accessory = homebridge.platformAccessory;

  // Service and Characteristic are from hap-nodejs
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  UUIDGen = homebridge.hap.uuid;

  // For platform plugin to be considered as dynamic platform plugin,
  // registerPlatform(pluginName, platformName, constructor, dynamic), dynamic must be true
  homebridge.registerPlatform("homebridge-platform-sqs", "SQS", SQSPlatform, true);
}

function SQSPlatform(log, config, api) {

  //just capture the input, we'll set it up in accessories
  this.log = log;
  this.config = config;
  this.api = api;
}

SQSPlatform.prototype = {
  accessories: function(callback) {
    //For each device in cfg, create an accessory!
    var foundAccessories = this.config.accessories;
    var myAccessories = [];

    for (var i = 0; i < foundAccessories.length; i++) {
      var accessory = new SQSAccessory(this.log, foundAccessories[i]);
      myAccessories.push(accessory);
      this.log('Created ' + accessory.name + ' Accessory');
    }
    callback(myAccessories);
  }
}

//an accessorary, eg a button. This one is mostly just an on/off state button.
//SQS message toggles it, as does pressing it in the home app
function SQSAccessory(log, accessory) {
  this.log = log;
  this.accessory = accessory;
  this.name = this.accessory.name;
  this.buttonIsOn = false;
  this.startListener();
}

SQSAccessory.prototype = {
  startListener: function() {
    var self = this;

    //setup the SQS queue listener
    var options = {
      url: this.accessory.queueurl,
      region: this.accessory.region,
      accessKeyId: this.accessory.accesskey,
      secretAccessKey: this.accessory.secret,

      //eat the logging, make it goes out the Homebridge logging
      // mostly cos sqsworker is a bit noisy
      log: {
        info: function(a, b) {
          self.log(a + " " + b);
        },
        error: function(a, b) {
          self.log("err:" + a + " " + b);
        }
      }
    };

    //setup the queue.
    this.queue = new SQSWorker(options, function(event, done) {
      if (self.accessory.verbose) {
        self.log(event);
      }

      self.toggleButton();

      //report back to SQS that we are done - otherwise it'll resubmit the message
      var success = true;

      // Call `done` when you are done processing a message.
      // If everything went successfully and you don't want to see it any more,
      // set the second parameter to `true`.
      done(null, success);
    });

    //we should start by purging the queue, 'cos you dont want a load of state changes
    //coming in on startup
    this.queue.client.purgeQueue({
      QueueUrl: options.url
    }, function(err, data) {
      if (err) {
        self.log(err);
      }
      self.log("Purged the queue");
    });

  },

  toggleButton: function() {
    this.log("toggle");
    //toggle the internal state of the button
    this.buttonIsOn = !this.buttonIsOn;
    this.log(`${this.name}: SQS Button state change. New state is ${this.buttonIsOn}`);
    this.service.setCharacteristic(Characteristic.On, this.buttonIsOn);
  },
  getServices: function() {
    //get the services this accessory supports
    //this is were we setup the button, but if it was, eg, a fan, you'd make a fan here.

    var services = [];

    var informationService = new Service.AccessoryInformation();
    informationService
      .setCharacteristic(Characteristic.Manufacturer, 'AmazonSQS');

    var switchService = new Service.Switch(this.accessory.name);
    switchService
      .getCharacteristic(Characteristic.On)
      .on('get', this.getSPState.bind(this))
      .on('set', this.setSPState.bind(this));

    informationService
      .setCharacteristic(Characteristic.Model, 'QueueButton')
      .setCharacteristic(Characteristic.SerialNumber, '1.0');

    services.push(switchService, informationService);

    //keep the service, so we can turn it on/off later.
    this.service = switchService;

    return services;
  },

  getSPState: function(callback) {
    this.log("getState");
    //homekit calling into us to get the state
    this.log(`${this.name}: Get State: ${this.buttonIsOn}`);
    callback(null, this.buttonIsOn);
  },

  setSPState: function(state, callback) {

    //homekit calling into us to set the state. state is 1 or 0
    if (state) {
      this.buttonIsOn = true;
    } else {
      this.buttonIsOn = false;
    }
    this.log(`${this.name}: Set State to ${this.buttonIsOn}`);
    callback(null, this.buttonIsOn);

  }
}
<commit_msg>:lipstick:<commit_after>var SQSWorker = require('sqs-worker');
var Accessory, Service, Characteristic, UUIDGen;

module.exports = function(homebridge) {

  // Accessory must be created from PlatformAccessory Constructor
  Accessory = homebridge.platformAccessory;

  // Service and Characteristic are from hap-nodejs
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  UUIDGen = homebridge.hap.uuid;

  // For platform plugin to be considered as dynamic platform plugin,
  // registerPlatform(pluginName, platformName, constructor, dynamic), dynamic must be true
  homebridge.registerPlatform("homebridge-platform-sqs", "SQS", SQSPlatform, true);
}

function SQSPlatform(log, config, api) {

  //just capture the input, we'll set it up in accessories
  this.log = log;
  this.config = config;
  this.api = api;
}

SQSPlatform.prototype = {
  accessories: function(callback) {
    //For each device in cfg, create an accessory!
    var foundAccessories = this.config.accessories;
    var myAccessories = [];

    for (var i = 0; i < foundAccessories.length; i++) {
      var accessory = new SQSAccessory(this.log, foundAccessories[i]);
      myAccessories.push(accessory);
      this.log('Created ' + accessory.name + ' Accessory');
    }
    callback(myAccessories);
  }
}

//an accessorary, eg a button. This one is mostly just an on/off state button.
//SQS message toggles it, as does pressing it in the home app
function SQSAccessory(log, accessory) {
  this.log = log;
  this.accessory = accessory;
  this.name = this.accessory.name;
  this.buttonIsOn = false;
  this.startListener();
}

SQSAccessory.prototype = {
  startListener: function() {
    var self = this;

    //setup the SQS queue listener
    var options = {
      url: this.accessory.queueurl,
      region: this.accessory.region,
      accessKeyId: this.accessory.accesskey,
      secretAccessKey: this.accessory.secret,

      //eat the logging, make it goes out the Homebridge logging
      // mostly cos sqsworker is a bit noisy
      log: {
        info: function(a, b) {
          self.log(a + " " + b);
        },
        error: function(a, b) {
          self.log("err:" + a + " " + b);
        }
      }
    };

    //setup the queue.
    this.queue = new SQSWorker(options, function(event, done) {
      if (self.accessory.verbose) {
        self.log(event);
      }

      self.toggleButton();

      //report back to SQS that we are done - otherwise it'll resubmit the message
      var success = true;

      // Call `done` when you are done processing a message.
      // If everything went successfully and you don't want to see it any more,
      // set the second parameter to `true`.
      done(null, success);
    });

    //we should start by purging the queue, 'cos you dont want a load of state changes
    //coming in on startup
    this.queue.client.purgeQueue({
      QueueUrl: options.url
    }, function(err, data) {
      if (err) {
        self.log(err);
      }
      self.log("Purged the queue");
    });

  },

  toggleButton: function() {
    //toggle the internal state of the button
    this.buttonIsOn = !this.buttonIsOn;
    this.log(`${this.name}: SQS Button state change. New state is ${this.buttonIsOn}`);
    this.service.setCharacteristic(Characteristic.On, this.buttonIsOn);
  },
  getServices: function() {
    //get the services this accessory supports
    //this is were we setup the button, but if it was, eg, a fan, you'd make a fan here.

    var services = [];

    var informationService = new Service.AccessoryInformation();
    informationService
      .setCharacteristic(Characteristic.Manufacturer, 'AmazonSQS');

    var switchService = new Service.Switch(this.accessory.name);
    switchService
      .getCharacteristic(Characteristic.On)
      .on('get', this.getSPState.bind(this))
      .on('set', this.setSPState.bind(this));

    informationService
      .setCharacteristic(Characteristic.Model, 'QueueButton')
      .setCharacteristic(Characteristic.SerialNumber, '1.0');

    services.push(switchService, informationService);

    //keep the service, so we can turn it on/off later.
    this.service = switchService;

    return services;
  },

  getSPState: function(callback) {
    //homekit calling into us to get the state
    this.log(`${this.name}: Get State: ${this.buttonIsOn}`);
    callback(null, this.buttonIsOn);
  },

  setSPState: function(state, callback) {

    //homekit calling into us to set the state. state is 1 or 0
    if (state) {
      this.buttonIsOn = true;
    } else {
      this.buttonIsOn = false;
    }
    this.log(`${this.name}: Set State to ${this.buttonIsOn}`);
    callback(null, this.buttonIsOn);

  }
}
<|endoftext|>


<commit_before>var triangulate = require('delaunay-triangulate')
var defaults = require('lodash.defaults')

module.exports = function (points, opts) {
  opts = opts || {}
  defaults(opts, {top: 1, bottom: 0, closed: true})

  var n = points.length
  var positions
  var cells

  (opts.top === opts.bottom) ? flat() : full()

  function flat () {
    positions = points.map(function (p) { return [p[0], p[1], opts.top] })
    cells = triangulate(points)
  }

  function full () {
    positions = []
    points.forEach(function (p) { positions.push([p[0], p[1], opts.top]) })
    points.forEach(function (p) { positions.push([p[0], p[1], opts.bottom]) })

    cells = []
    for (var i = 0; i < n; i++) {
      if (i === (n - 1)) {
        cells.push([i, n, i + n])
        cells.push([i, 0, n])
      } else {
        cells.push([i, i + n + 1, i + n])
        cells.push([i, i + 1, i + n + 1])
      }
    }

    if (opts.closed) {
      var top = triangulate(points).map(function (p) { return p.sort() })
      var bottom = top.map(function (p) { return p.map(function (v) { return v + n }) })
      cells = cells.concat(top).concat(bottom)
    }
  }

  return {
    positions: positions,
    cells: cells
  }
}
<commit_msg>Fix ordering<commit_after>var triangulate = require('delaunay-triangulate')
var defaults = require('lodash.defaults')

module.exports = function (points, opts) {
  opts = opts || {}
  defaults(opts, {top: 1, bottom: 0, closed: true})

  var n = points.length
  var positions
  var cells

  (opts.top === opts.bottom) ? flat() : full()

  function flat () {
    positions = points.map(function (p) { return [p[0], p[1], opts.top] })
    cells = triangulate(points).map(function (p) {return p.sort()})
  }

  function full () {
    positions = []
    points.forEach(function (p) { positions.push([p[0], p[1], opts.top]) })
    points.forEach(function (p) { positions.push([p[0], p[1], opts.bottom]) })

    cells = []
    for (var i = 0; i < n; i++) {
      if (i === (n - 1)) {
        cells.push([i + n, n, i])
        cells.push([0, i, n])
      } else {
        cells.push([i + n, i + n + 1, i])
        cells.push([i + 1, i, i + n + 1])
      }
    }

    if (opts.closed) {
      var top = triangulate(points).map(function (p) { return p.sort() })
      var bottom = top.map(function (p) { return p.map(function (v) { return v + n }) })
      bottom = bottom.map(function (p) { return [p[0], p[2], p[1]]})
      cells = cells.concat(top).concat(bottom)
    }
  }

  return {
    positions: positions,
    cells: cells
  }
}
<|endoftext|>