<commit_before>require('setimmediate')
var debug = require('debug')('DynamoDBStream')
var _ = require('lodash')
var async = require('async')
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var DynamoDBValue = require('dynamodb-value')

module.exports = DynamoDBStream

inherits(DynamoDBStream, EventEmitter)
function DynamoDBStream(ddbStreams, streamArn) {
	if ( !(this instanceof DynamoDBStream) ) return new DynamoDBStream(ddbStreams, streamArn)

	EventEmitter.call(this)

	if (typeof ddbStreams !== 'object') throw new Error('missing DynamoDBStreams instance')
	if (typeof streamArn !== 'string') throw new Error('missing stream arn, expected string but it was ' + streamArn)

	this._ddbStreams = ddbStreams
	this._streamArn = streamArn
	this._shards = {}
	this._shardsCount = 0

	this._emitErrorFunctor = _.bind(this._emitErrorEvent, this)
	this._fetchStreamShardsFunctor = _.bind(this.fetchStreamShards, this)
	this._fetchStreamRecordsFunctor = _.bind(this.fetchStreamRecords, this)

	debug('created stream instance %s', streamArn)
}

/**
 * this will update the stream, shards and records included
 *
 */
DynamoDBStream.prototype.fetchStreamState = function (callback) {
	debug('fetchStreamState')

	if (callback && typeof callback !== 'function') {
		throw new Error('invalid argument, can be a callback function or nothing')
	}

	async.series([
		this._fetchStreamShardsFunctor,
		this._fetchStreamRecordsFunctor
	], callback || this._emitErrorFunctor)
}

/**
 * get latest updates from the underlying stream
 *
 */
DynamoDBStream.prototype.fetchStreamRecords = function (callback) {
	debug('fetchStreamRecords')

	if (callback && typeof callback !== 'function') {
		throw new Error('invalid argument, can be a callback function or nothing')
	}

	if (this._shardsCount === 0) {
		debug('no shards found')
		return setImmediate(callback)
	}

	var params = {
		StreamArn: this._streamArn
	}

	var self = this

	var work = [
		_.bind(this._getShardIterators, this),
		_.bind(this._getRecords, this)
	]

	async.waterfall(work, function (err, records) {
		if (err) {
			return callback ? callback(err) : self._emitErrorEvent(err)
		}

		debug(records)

		self._trimShards()

		setImmediate(_.bind(self._emitRecordEvents, self, records))

		if (callback) {
			callback()
		}
	})
}

/**
 * update the shard state of the stream
 * this will emit new shards / remove shards events
 */
DynamoDBStream.prototype.fetchStreamShards = function(callback) {
	debug('fetchStreamShards')

	if (callback && typeof callback !== 'function') {
		throw new Error('invalid argument, can be a callback function or nothing')
	}

	this._trimShards()

	var params = {
		StreamArn: this._streamArn
	}

	var self = this

	this._ddbStreams.describeStream(params, function(err, data) {
		if (err) {
			return callback ? callback(err) : self._emitErrorEvent(err)
		}

		debug('describeStream data')

		var shards = data.StreamDescription.Shards
		var newShardIds = []

		// collect all the new shards of this stream
		for (var i = 0; i < shards.length; i++) {
			var newShardEntry = shards[i]
			var shardEntry = self._shards[newShardEntry.ShardId]

			if (!shardEntry) {
				self._shards[newShardEntry.ShardId] = {
					shardId: newShardEntry.ShardId
				}
				newShardIds.push(newShardEntry.ShardId)
			}
		}

		if (newShardIds.length > 0) {
			self._shardsCount += newShardIds.length
			debug('Added %d new shards', newShardIds.length)
			self._emitNewShardsEvent(newShardIds)
		}

		if (callback) {
			callback()
		}
	})
}

DynamoDBStream.prototype._getShardIterators = function (callback) {
	debug('_getShardIterators')

	async.eachLimit(this._shards, 10, _.bind(this._getShardIterator, this), callback)
}

DynamoDBStream.prototype._getShardIterator = function(shardData, callback) {
	debug('_getShardIterator')
	debug(shardData)

	// no need to get an iterator if this shard already has NextShardIterator
	if (shardData.nextShardIterator) {
		debug('shard %s already has an iterator, skipping', shardData.shardId)
		return callback()
	}

	var params = {
		ShardId: shardData.shardId,
		ShardIteratorType: 'LATEST',
		StreamArn: this._streamArn
	}

	this._ddbStreams.getShardIterator(params, function (err, result) {
		if (err) return callback(err)
		shardData.nextShardIterator = result.ShardIterator
		callback()
	})
}

DynamoDBStream.prototype._getRecords = function (callback) {
	debug('_getRecords')

	var records = []

	async.eachLimit(this._shards, 10, _.bind(this._getShardRecords, this, records), function (err) {
		if (err) return callback(err)
		callback(null, records)
	})
}

DynamoDBStream.prototype._getShardRecords = function (records, shardData, callback) {
	debug('_getShardRecords')
	var self = this

	this._ddbStreams.getRecords({ ShardIterator: shardData.nextShardIterator }, function (err, result) {
		if (err) return callback(err)

		if (result.Records) {
			records.push.apply(records, result.Records)

			if (result.NextShardIterator) {
				shardData.nextShardIterator = result.NextShardIterator
			} else {
				shardData.nextShardIterator = null
			}
		}

		callback()
	})
}

DynamoDBStream.prototype._trimShards = function () {
	debug('_trimShards')

	var removedShards = []

	for (var shardId in this._shards) {
		var shardData = this._shards[shardId]

		if (shardData.nextShardIterator === null) {
			debug('deleting shard %s', shardId)
			delete this._shards[shardId]
			this._shardsCount--
			removedShards.push(shardId)
		}
	}

	if (removedShards.length > 0) {
		this._emitRemoveShardsEvent(removedShards)
	}
}

DynamoDBStream.prototype._emitRecordEvents = function (events) {
	debug('_emitRecordEvents')

	for (var i = 0; i < events.length; i++) {
		var event = events[i]

		switch (event.eventName) {
			case 'INSERT':
				this.emit('insert record', DynamoDBValue.toJavascript(event.dynamodb.NewImage))
				break

			case 'MODIFY':
				var newRecord = DynamoDBValue.toJavascript(event.dynamodb.NewImage)
				var oldRecord = DynamoDBValue.toJavascript(event.dynamodb.OldImage)
				this.emit('modify record', newRecord, oldRecord)
				break

			case 'REMOVE':
				this.emit('remove record', DynamoDBValue.toJavascript(event.dynamodb.OldImage))
				break

			default:
				 this._emitErrorEvent(new Error('unknown dynamodb event ' + event.eventName))
		}
	}
}

DynamoDBStream.prototype._emitErrorEvent = function (err) {
	this.emit('error', err)
}

DynamoDBStream.prototype._emitNewShardsEvent = function (shardIds) {
	setImmediate(_.bind(this.emit, this, 'new shards', shardIds))
}

DynamoDBStream.prototype._emitRemoveShardsEvent = function (shardIds) {
	setImmediate(_.bind(this.emit, this, 'remove shards', shardIds))
}

DynamoDBStream.prototype.getShardState = function () {
	return _.cloneDeep(this._shards)
}

DynamoDBStream.prototype.setShardState = function (shards) {
	this._shardsCount = Object.keys(shards).length
	this._shards = shards
}<commit_msg>added handling logic for expired iterators<commit_after>require('setimmediate')
var debug = require('debug')('DynamoDBStream')
var _ = require('lodash')
var async = require('async')
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var DynamoDBValue = require('dynamodb-value')

module.exports = DynamoDBStream

inherits(DynamoDBStream, EventEmitter)
function DynamoDBStream(ddbStreams, streamArn) {
	if ( !(this instanceof DynamoDBStream) ) return new DynamoDBStream(ddbStreams, streamArn)

	EventEmitter.call(this)

	if (typeof ddbStreams !== 'object') throw new Error('missing DynamoDBStreams instance')
	if (typeof streamArn !== 'string') throw new Error('missing stream arn, expected string but it was ' + streamArn)

	this._ddbStreams = ddbStreams
	this._streamArn = streamArn
	this._shards = {}
	this._shardsCount = 0

	this._emitErrorFunctor = _.bind(this._emitErrorEvent, this)
	this._fetchStreamShardsFunctor = _.bind(this.fetchStreamShards, this)
	this._fetchStreamRecordsFunctor = _.bind(this.fetchStreamRecords, this)

	debug('created stream instance %s', streamArn)
}

/**
 * this will update the stream, shards and records included
 *
 */
DynamoDBStream.prototype.fetchStreamState = function (callback) {
	debug('fetchStreamState')

	if (callback && typeof callback !== 'function') {
		throw new Error('invalid argument, can be a callback function or nothing')
	}

	async.series([
		this._fetchStreamShardsFunctor,
		this._fetchStreamRecordsFunctor
	], callback || this._emitErrorFunctor)
}

/**
 * get latest updates from the underlying stream
 *
 */
DynamoDBStream.prototype.fetchStreamRecords = function (callback) {
	debug('fetchStreamRecords')

	if (callback && typeof callback !== 'function') {
		throw new Error('invalid argument, can be a callback function or nothing')
	}

	if (this._shardsCount === 0) {
		debug('no shards found')
		return setImmediate(callback)
	}

	var params = {
		StreamArn: this._streamArn
	}

	var self = this

	var work = [
		_.bind(this._getShardIterators, this),
		_.bind(this._getRecords, this)
	]

	async.waterfall(work, function (err, records) {
		if (err) {
			return callback ? callback(err) : self._emitErrorEvent(err)
		}

		debug(records)

		self._trimShards()

		setImmediate(_.bind(self._emitRecordEvents, self, records))

		if (callback) {
			callback()
		}
	})
}

/**
 * update the shard state of the stream
 * this will emit new shards / remove shards events
 */
DynamoDBStream.prototype.fetchStreamShards = function(callback) {
	debug('fetchStreamShards')

	if (callback && typeof callback !== 'function') {
		throw new Error('invalid argument, can be a callback function or nothing')
	}

	this._trimShards()

	var params = {
		StreamArn: this._streamArn
	}

	var self = this

	this._ddbStreams.describeStream(params, function(err, data) {
		if (err) {
			return callback ? callback(err) : self._emitErrorEvent(err)
		}

		debug('describeStream data')

		var shards = data.StreamDescription.Shards
		var newShardIds = []

		// collect all the new shards of this stream
		for (var i = 0; i < shards.length; i++) {
			var newShardEntry = shards[i]
			var shardEntry = self._shards[newShardEntry.ShardId]

			if (!shardEntry) {
				self._shards[newShardEntry.ShardId] = {
					shardId: newShardEntry.ShardId
				}
				newShardIds.push(newShardEntry.ShardId)
			}
		}

		if (newShardIds.length > 0) {
			self._shardsCount += newShardIds.length
			debug('Added %d new shards', newShardIds.length)
			self._emitNewShardsEvent(newShardIds)
		}

		if (callback) {
			callback()
		}
	})
}

DynamoDBStream.prototype._getShardIterators = function (callback) {
	debug('_getShardIterators')

	async.eachLimit(this._shards, 10, _.bind(this._getShardIterator, this), callback)
}

DynamoDBStream.prototype._getShardIterator = function(shardData, callback) {
	debug('_getShardIterator')
	debug(shardData)

	// no need to get an iterator if this shard already has NextShardIterator
	if (shardData.nextShardIterator) {
		debug('shard %s already has an iterator, skipping', shardData.shardId)
		return callback()
	}

	var params = {
		ShardId: shardData.shardId,
		ShardIteratorType: 'LATEST',
		StreamArn: this._streamArn
	}

	this._ddbStreams.getShardIterator(params, function (err, result) {
		if (err) return callback(err)
		shardData.nextShardIterator = result.ShardIterator
		callback()
	})
}

DynamoDBStream.prototype._getRecords = function (callback) {
	debug('_getRecords')

	var records = []

	async.eachLimit(this._shards, 10, _.bind(this._getShardRecords, this, records), function (err) {
		if (err) return callback(err)
		callback(null, records)
	})
}

DynamoDBStream.prototype._getShardRecords = function (records, shardData, callback) {
	debug('_getShardRecords')
	var self = this

	this._ddbStreams.getRecords({ ShardIterator: shardData.nextShardIterator }, function (err, result) {
		if (err) {
			if (err.code === 'ExpiredIteratorException') {
      	shardData.nextShardIterator = undefined;
        return callback();
      }
			return callback(err);
		}

		if (result.Records) {
			records.push.apply(records, result.Records)

			if (result.NextShardIterator) {
				shardData.nextShardIterator = result.NextShardIterator
			} else {
				shardData.nextShardIterator = null
			}
		}

		callback()
	})
}

DynamoDBStream.prototype._trimShards = function () {
	debug('_trimShards')

	var removedShards = []

	for (var shardId in this._shards) {
		var shardData = this._shards[shardId]

		if (shardData.nextShardIterator === null) {
			debug('deleting shard %s', shardId)
			delete this._shards[shardId]
			this._shardsCount--
			removedShards.push(shardId)
		}
	}

	if (removedShards.length > 0) {
		this._emitRemoveShardsEvent(removedShards)
	}
}

DynamoDBStream.prototype._emitRecordEvents = function (events) {
	debug('_emitRecordEvents')

	for (var i = 0; i < events.length; i++) {
		var event = events[i]

		switch (event.eventName) {
			case 'INSERT':
				this.emit('insert record', DynamoDBValue.toJavascript(event.dynamodb.NewImage))
				break

			case 'MODIFY':
				var newRecord = DynamoDBValue.toJavascript(event.dynamodb.NewImage)
				var oldRecord = DynamoDBValue.toJavascript(event.dynamodb.OldImage)
				this.emit('modify record', newRecord, oldRecord)
				break

			case 'REMOVE':
				this.emit('remove record', DynamoDBValue.toJavascript(event.dynamodb.OldImage))
				break

			default:
				 this._emitErrorEvent(new Error('unknown dynamodb event ' + event.eventName))
		}
	}
}

DynamoDBStream.prototype._emitErrorEvent = function (err) {
	this.emit('error', err)
}

DynamoDBStream.prototype._emitNewShardsEvent = function (shardIds) {
	setImmediate(_.bind(this.emit, this, 'new shards', shardIds))
}

DynamoDBStream.prototype._emitRemoveShardsEvent = function (shardIds) {
	setImmediate(_.bind(this.emit, this, 'remove shards', shardIds))
}

DynamoDBStream.prototype.getShardState = function () {
	return _.cloneDeep(this._shards)
}

DynamoDBStream.prototype.setShardState = function (shards) {
	this._shardsCount = Object.keys(shards).length
	this._shards = shards
}
<|endoftext|>


<commit_before>require('dotenv').config()
var path = require('path')
var fs = require('fs')
var readDir = require('readdir')
var watch = require('node-watch');
const exec = require('child_process').exec

const SUPPORTED_FORMATS = [".mov", ".mpeg4", ".mp4", ".avi", ".wmv", ".mpegps", ".flv", ".3gpp", ".webm", ".mkv"]

function uploadVideo(filePath) {
  return new Promise((yes, no) => {
    const { PRIVACY, CLIENT_SECRETS, DELETE_AFTER_UPLOAD } = process.env;
    const { name, base } = path.parse(filePath)
    const cmd = `youtube-upload --title="${name}" --privacy=${PRIVACY} --credentials-file=credentials.json --client-secrets=${CLIENT_SECRETS} "${filePath}"`
    console.log(cmd);
    exec(cmd, function(err, stdout, stderr) {
      console.log(`youtube id ${stdout}`);
      //a video id
      if (stdout.indexOf(" ") < 0) {
        yes(filePath)
      } else {
        no(filePath)
      }
    });
  })
}

watch(process.env.DOWNLOAD_DIR, { recursive: true }, function(evt, name) {
  switch (evt) {
    case 'created':
    case 'update':
      const ext = path.parse(name).ext;
      const containerFolder = fs.lstatSync(name).isDirectory() ? name : null
      if (SUPPORTED_FORMATS.indexOf(ext) > -1 && !fs.lstatSync(name).isDirectory()) {
        console.log(name);
        uploadVideo(name)
          .then(filePath => {
            const {dir} = path.parse(filePath)
            const { DELETE_AFTER_UPLOAD } = process.env;
            if (Boolean(DELETE_AFTER_UPLOAD)) {
              const fileToDelete = containerFolder || filePath
              exec(`rm -rf "${fileToDelete}"`, function(err, stdout, stderr) {
                console.log(`Deleted ${fileToDelete}`);
                if(containerFolder){
                  fs.rmdir(containerFolder)
                  console.log(`Deleted directory${fileToDelete}`);
                }
              })
            }
          })
          .catch(err => {

          })
          /*if (fs.lstatSync(name).isDirectory()) {
            const files = readDir.readSync( name, SUPPORTED_FORMATS.map(p=>(`**${p}`)), readDir.ABSOLUTE_PATHS );
            console.log(files);
          } else {
          }*/

      }
      break;
  }
});
<commit_msg>log process<commit_after>require('dotenv').config()
var path = require('path')
var fs = require('fs')
var readDir = require('readdir')
var watch = require('node-watch');
const exec = require('child_process').exec

console.log(process.env);

const SUPPORTED_FORMATS = [".mov", ".mpeg4", ".mp4", ".avi", ".wmv", ".mpegps", ".flv", ".3gpp", ".webm", ".mkv"]

function uploadVideo(filePath) {
  return new Promise((yes, no) => {
    const { PRIVACY, CLIENT_SECRETS, DELETE_AFTER_UPLOAD } = process.env;
    const { name, base } = path.parse(filePath)
    const cmd = `youtube-upload --title="${name}" --privacy=${PRIVACY} --credentials-file=credentials.json --client-secrets=${CLIENT_SECRETS} "${filePath}"`
    console.log(cmd);
    exec(cmd, function(err, stdout, stderr) {
      console.log(`youtube id ${stdout}`);
      //a video id
      if (stdout.indexOf(" ") < 0) {
        yes(filePath)
      } else {
        no(filePath)
      }
    });
  })
}

watch(process.env.DOWNLOAD_DIR, { recursive: true }, function(evt, name) {
  switch (evt) {
    case 'created':
    case 'update':
      const ext = path.parse(name).ext;
      const containerFolder = fs.lstatSync(name).isDirectory() ? name : null
      if (SUPPORTED_FORMATS.indexOf(ext) > -1 && !fs.lstatSync(name).isDirectory()) {
        console.log(name);
        uploadVideo(name)
          .then(filePath => {
            const {dir} = path.parse(filePath)
            const { DELETE_AFTER_UPLOAD } = process.env;
            if (Boolean(DELETE_AFTER_UPLOAD)) {
              const fileToDelete = containerFolder || filePath
              exec(`rm -rf "${fileToDelete}"`, function(err, stdout, stderr) {
                console.log(`Deleted ${fileToDelete}`);
                if(containerFolder){
                  fs.rmdir(containerFolder)
                  console.log(`Deleted directory${fileToDelete}`);
                }
              })
            }
          })
          .catch(err => {

          })
          /*if (fs.lstatSync(name).isDirectory()) {
            const files = readDir.readSync( name, SUPPORTED_FORMATS.map(p=>(`**${p}`)), readDir.ABSOLUTE_PATHS );
            console.log(files);
          } else {
          }*/

      }
      break;
  }
});
<|endoftext|>


<commit_before>/*******************************
	ImportJS Version 1.0.1

    A basic package-structuring import system for JavaScript Objects.

	The MIT License (MIT)

	Copyright (c) 2013 Greg McLeod <cleod9{at}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.
*******************************/

var ImportJS={pkgs:{},uncompiled:[],compiled:[],settings:{debug:false,delimiter:".",node_flag:false},pack:function(e,t,n){if(typeof e!="string")throw new Error("ImportJS Error: Provided package ID must be a string.");if(typeof t!="object"&&typeof t!="function")throw new Error("ImportJS Error: Provided class was not an Object or Function.");var r=e.split(ImportJS.settings.delimiter);if(r.length>0){var i=function(r,s){if(s.length==1){if(typeof r[s[0]]!="undefined")throw new Error("ImportJS Error: Package "+e+" already exists.");else{if(n===false){ImportJS.uncompiled.push(e);r[s[0]]=t}else{ImportJS.compiled.push(e);r[s[0]]=t()}}}else{if(typeof r[s[0]]=="undefined")r[s[0]]={};i(r[s[0]],s.slice(1))}};i(ImportJS.pkgs,r)}else throw new Error("ImportJS Error: Invalid package ID.")},unpack:function(e){if(typeof e!="string")throw new Error("ImportJS Error: Provided package ID must be a string.");var t=e.split(ImportJS.settings.delimiter);if(t.length>0){var n=function(t,r){if(typeof t[r[0]]=="undefined")throw new Error("ImportJS Error: Package ID "+e+" does not exist.");if(r.length==1){if(ImportJS.uncompiled.indexOf(e)>=0){var i=t[r[0]]();ImportJS.uncompiled.splice(ImportJS.uncompiled.indexOf(e),1);ImportJS.compiled.push(e);t[r[0]]=i[0];i[1]()}return t[r[0]]}else return n(t[r[0]],r.slice(1))};return n(ImportJS.pkgs,t)}else throw new Error("Package.js Error: Invalid package ID.")},compile:function(){while(ImportJS.uncompiled.length>0){ImportJS.unpack(ImportJS.uncompiled[0])}},preload:function(params){if(typeof params!="object")throw new Error("ImportJS Error: No parameters supplied.");var settings={baseUrl:params.baseUrl||"",files:params.files||[],ready:params.ready||null,error:params.error||null,removeTags:params.removeTags===false?false:true,strict:params.strict===false?false:true,timeout:params.timeout?params.timeout:5e3,libs:params.libs||[],autocompile:params.autocompile===false?false:true};if(settings.baseUrl=="./"||settings.baseUrl=="")settings.baseUrl=".";if(settings.baseUrl.lastIndexOf("/")==settings.baseUrl.length-1)settings.baseUrl=settings.baseUrl.substr(0,settings.baseUrl.length-1);var i;var filesArr=typeof settings.files.length=="number"?settings.files:[];var libsArr=settings.libs;var packageArr=[];var loadedFiles=[];var erroredFiles=[];var objToPath=function(e,t,n){for(var r in e){if(typeof e[r]=="string"){filesArr.push(t+"/"+e[r]);packageArr.push((n+ImportJS.settings.delimiter+r).substr(ImportJS.settings.delimiter.length))}else if(typeof e[r]=="object")objToPath(e[r],t+"/"+r,n+ImportJS.settings.delimiter+r);else throw new Error("ImportJS Error: Paths can only contain Objects and String values.")}};if(filesArr.length==0){objToPath(settings.files,settings.baseUrl,"")}else{for(i=0;i<settings.files.length;i++){var clsPath=settings.files[i].split("/").join(ImportJS.settings.delimiter);clsPath=clsPath.substr(0,clsPath.length-3);packageArr.push(clsPath)}}if(filesArr.length==0){if(typeof settings.ready=="function")settings.ready()}var loadScript=function(filePath,clsPath){if(ImportJS.settings.node_flag){if(!fs)return;try{var source=fs.readFileSync(filePath).toString();eval(source);if(clsPath&&settings.strict){if(ImportJS.compiled.indexOf(clsPath)<0&&ImportJS.uncompiled.indexOf(clsPath)<0)throw new Error("Import js Error: Invalid or missing package definition for "+clsPath+" (using strict)")}loadedFiles.push(filePath);if(loadedFiles.length==filesArr.length+libsArr.length){if(settings.autocompile){ImportJS.compile()}if(typeof settings.ready=="function")settings.ready(loadedFiles)}}catch(e){console.log(e);erroredFiles.push(filePath);if(typeof settings.error=="function")settings.error(erroredFiles)}return}var done=false;var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");var timeout=null;script.type="text/javascript";var loadFunc=function(){if(settings.removeTags)head.removeChild(script);done=true;clearTimeout(timeout);if(clsPath&&settings.strict){if(ImportJS.compiled.indexOf(clsPath)<0&&ImportJS.uncompiled.indexOf(clsPath)<0)throw new Error("Import js Error: Invalid or missing package definition for "+clsPath+" (using strict)")}loadedFiles.push(filePath);if(loadedFiles.length==filesArr.length+libsArr.length){if(settings.autocompile){ImportJS.compile()}if(typeof settings.ready=="function")settings.ready(loadedFiles)}};var errorFunc=function(){if(settings.removeTags)head.removeChild(script);erroredFiles.push(filePath);clearTimeout(timeout);if(loadedFiles.length+erroredFiles.length>=filesArr.length+libsArr.length){if(typeof settings.error=="function")settings.error(erroredFiles);if(ImportJS.settings.debug)console.log("ImportJS Error: Could not preload the following files: ["+erroredFiles.join(", ")+"]")}};timeout=setTimeout(function(){if(ImportJS.settings.debug)console.log("ImportJS Error: Timed out on file: "+filePath);errorFunc()},settings.timeout);script.onreadystatechange=function(){if(!done&&(!script.readyState||this.readyState=="complete"||this.readyState=="loaded")){loadFunc()}};script.onload=loadFunc;script.onerror=errorFunc;script.src=filePath;head.appendChild(script)};var loadPackageScripts=function(){for(var e=0;e<filesArr.length;e++)loadScript(filesArr[e],packageArr[e])};if(libsArr.length>0){var currentLib=0;var loadChainer=function(e,t,n){ImportJS.preload({baseUrl:settings.baseUrl,removeTags:settings.removeTags,strict:false,timeout:settings.timeout,autocompile:false,files:[e],ready:t,error:n})};var success,fail;success=function(e){loadedFiles.push(e[0]);if(currentLib<libsArr.length)loadChainer(libsArr[currentLib++],success,fail);else if(filesArr.length<=0){if(typeof settings.ready=="function")settings.ready(loadedFiles)}else{loadPackageScripts()}};fail=function(e){erroredFiles.push(e[0]);if(ImportJS.settings.debug)console.log("ImportJS Error: Could not preload the following files: ["+e.join(", ")+"]");if(typeof settings.error=="function")settings.error(erroredFiles)};loadChainer(libsArr[currentLib++],success,fail)}else{loadPackageScripts()}}}<commit_msg>-Updated minified version<commit_after>/*******************************
	ImportJS Version 1.0.1

    A basic package-structuring import system for JavaScript Objects.

	The MIT License (MIT)

	Copyright (c) 2013 Greg McLeod <cleod9{at}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.
*******************************/
var ImportJS={pkgs:{},uncompiled:[],compiled:[],settings:{debug:false,delimiter:"."},pack:function(e,t,n){if(typeof e!="string")throw new Error("ImportJS Error: Provided package ID must be a string.");if(typeof t!="object"&&typeof t!="function")throw new Error("ImportJS Error: Provided class was not an Object or Function.");var r=e.split(ImportJS.settings.delimiter);if(r.length>0){var i=function(r,s){if(s.length===1){if(typeof r[s[0]]!="undefined")throw new Error("ImportJS Error: Package "+e+" already exists.");else{if(n===false){ImportJS.uncompiled.push(e);r[s[0]]=t}else{ImportJS.compiled.push(e);r[s[0]]=t()}}}else{if(typeof r[s[0]]==="undefined")r[s[0]]={};i(r[s[0]],s.slice(1))}};i(ImportJS.pkgs,r)}else throw new Error("ImportJS Error: Invalid package ID.")},unpack:function(e){if(typeof e!="string")throw new Error("ImportJS Error: Provided package ID must be a string.");var t=e.split(ImportJS.settings.delimiter);if(t.length>0){var n=function(t,r){if(typeof t[r[0]]==="undefined")throw new Error("ImportJS Error: Package ID "+e+" does not exist.");if(r.length===1){if(ImportJS.uncompiled.indexOf(e)>=0){var i=t[r[0]]();ImportJS.uncompiled.splice(ImportJS.uncompiled.indexOf(e),1);ImportJS.compiled.push(e);t[r[0]]=i[0];i[1]()}return t[r[0]]}else return n(t[r[0]],r.slice(1))};return n(ImportJS.pkgs,t)}else throw new Error("Package.js Error: Invalid package ID.")},compile:function(){while(ImportJS.uncompiled.length>0){ImportJS.unpack(ImportJS.uncompiled[0])}},preload:function(e){if(typeof e!="object")throw new Error("ImportJS Error: No parameters supplied.");var t=ImportJS.settings.require||null;var n={baseUrl:e.baseUrl||"",files:e.files||[],ready:e.ready||null,error:e.error||null,removeTags:e.removeTags===false?false:true,strict:e.strict===false?false:true,timeout:e.timeout?e.timeout:5e3,libs:e.libs||[],autocompile:e.autocompile===false?false:true};if(n.baseUrl==="./"||n.baseUrl==="")n.baseUrl=".";if(n.baseUrl.lastIndexOf("/")===n.baseUrl.length-1)n.baseUrl=n.baseUrl.substr(0,n.baseUrl.length-1);var r;var i=typeof n.files.length==="number"?n.files:[];var s=n.libs;var o=[];var u=[];var a=[];var f=function(e,t,n){for(var r in e){if(typeof e[r]==="string"){i.push(t+"/"+e[r]);o.push((n+ImportJS.settings.delimiter+r).substr(ImportJS.settings.delimiter.length))}else if(typeof e[r]==="object")f(e[r],t+"/"+r,n+ImportJS.settings.delimiter+r);else throw new Error("ImportJS Error: Paths can only contain Objects and String values.")}};if(i.length===0){f(n.files,n.baseUrl,"")}else{for(r=0;r<n.files.length;r++){var l=n.files[r].split("/").join(ImportJS.settings.delimiter);l=l.substr(0,l.length-3);o.push(l)}}if(i.length===0){if(typeof n.ready==="function")n.ready()}var c=function(e,r){if(t){try{if(e.charAt(0)!=="/"&&e.charAt(0)!=="."){e="./"+e}var o=t(e);ImportJS.pack.apply(this,o);if(r&&n.strict){if(ImportJS.compiled.indexOf(r)<0&&ImportJS.uncompiled.indexOf(r)<0)throw new Error("ImportJS Error: Invalid or missing package definition for "+r+" (using strict)")}u.push(e);if(u.length===i.length+s.length){if(n.autocompile){ImportJS.compile()}if(typeof n.ready==="function")n.ready(u)}}catch(f){if(ImportJS.settings.debug)console.log(f);a.push(e);if(typeof n.error==="function")n.error(a)}return}var l=false;var c=document.getElementsByTagName("head")[0];var h=document.createElement("script");var p=null;h.type="text/javascript";var d=function(){if(n.removeTags)c.removeChild(h);l=true;clearTimeout(p);if(r&&n.strict){if(ImportJS.compiled.indexOf(r)<0&&ImportJS.uncompiled.indexOf(r)<0)throw new Error("ImportJS Error: Invalid or missing package definition for "+r+" (using strict)")}u.push(e);if(u.length===i.length+s.length){if(n.autocompile){ImportJS.compile()}if(typeof n.ready==="function")n.ready(u)}};var v=function(){if(n.removeTags)c.removeChild(h);a.push(e);clearTimeout(p);if(u.length+a.length>=i.length+s.length){if(typeof n.error==="function")n.error(a);if(ImportJS.settings.debug)console.log("ImportJS Error: Could not preload the following files: ["+a.join(", ")+"]")}};p=setTimeout(function(){if(ImportJS.settings.debug)console.log("ImportJS Error: Timed out on file: "+e);v()},n.timeout);h.onreadystatechange=function(){if(!l&&(!h.readyState||this.readyState==="complete"||this.readyState==="loaded")){d()}};h.onload=d;h.onerror=v;h.src=e;c.appendChild(h)};var h=function(){for(var e=0;e<i.length;e++)c(i[e],o[e])};if(s.length>0){var p=0;var d=function(e,t,r){ImportJS.preload({baseUrl:n.baseUrl,removeTags:n.removeTags,strict:false,timeout:n.timeout,autocompile:false,files:[e],ready:t,error:r})};var v,m;v=function(e){u.push(e[0]);if(p<s.length)d(s[p++],v,m);else if(i.length<=0){if(typeof n.ready==="function")n.ready(u)}else{h()}};m=function(e){a.push(e[0]);if(ImportJS.settings.debug)console.log("ImportJS Error: Could not preload the following files: ["+e.join(", ")+"]");if(typeof n.error==="function")n.error(a)};d(s[p++],v,m)}else{h()}}}<|endoftext|>


<commit_before>'use strict';

const get = require('lodash.get');
const set = require('lodash.set');
const values = require('lodash.values');
const map = require('lodash.map');
const reduce = require('lodash.reduce');
const express = require('express');
const path = require('path');
const assert = require('assert');
const semver = require('semver');

const SWAGGER_VERSION = '2.0';
const SWAGGER_BASE_PATH = '__swagger__';
const MINIMAL_VERSION_REQUIRED = '0.8.17';

const DEFAULT_RESPONSES = {
  default: { description: 'Default responses' }
};

// Install swagger plugin
function buildSwaggerConfig(app, options) {
  options = options || {};
  let defaultResponses = options.defaultResponses || DEFAULT_RESPONSES;
  let tags = [];
  let paths = {};
  let definitions = Object.assign({}, get(options, 'swagger.definitions') || {});

  let addedTags = {};

  let supportTypes = app.get('adapterOptions.supportedTypes') || [
    'application/json'
  ];

  let acceptTypes = [
    'application/json',
    'application/x-www-form-urlencoded',
    'multipart/form-data'
  ];

  // Default swagger config
  let swagger = Object.assign({
    basePath: '/',
    schemes: ['http'],
    host: '',
    swagger: SWAGGER_VERSION,
    info: {
      title: app.get('title') || '',
      description: app.get('description') || '',
      version: app.get('version')
    }
  }, options.swagger || {});

  // Build security
  let securities = map(swagger.securityDefinitions || {}, function(security, name) {
    let res = {};
    if (security.type === 'oauth2') {
      res[name] = Object.keys(security.scopes || {});
    } else {
      res[name] = [];
    }
    return res;
  });

  // Transfer `:id` like parameter to `{id}`
  function pathReplacer(path) {
    return path.replace(/:([a-zA-Z0-9\-\_]+)/g, function(__, capture) {
      return `{${capture}}`;
    });
  }

  // extract required names for definitions according to params
  function extractRequiredNames(params) {
    let requireds = [];
    map(params, function(param) {
      param.required && requireds.push(param.name);
    });
    return requireds;
  }

  // Detect whether parameters should be placed in body, formData or query
  // Header currently is not supported
  function chooseParameterPositionBy(verb, params) {
    if (['get', 'options'].indexOf(verb) > -1) return 'query';

    let shouldInBody;

    if (params.length) {
      shouldInBody = reduce(params, function(res, param) {
        if (param.params) {
          return res || true;
        } else {
          return res || false;
        }
      }, false);
    } else {
      // Set parameter position as `body` when there is on params required
      shouldInBody = true;
    }

    return shouldInBody ? 'body' : 'formData';
  }

  // Build swagger compatible parameters
  function buildParameters(method, params, definitionPrefix, buildForDefinitiion) {
    let defaultIn = buildForDefinitiion ?
                    'query' :
                    chooseParameterPositionBy(method.route.verb, params);

    let path = method.fullPath();

    let bodyDefinitionKey = `${method.fullName()}.params`;
    definitionPrefix = definitionPrefix || `${bodyDefinitionKey}.`;

    let result = {};
    let body = {};
    let isInBody = defaultIn === 'body';

    // Iterate over all parameters
    map(params, function(param) {
      let conf = {
        description: param.description,
        default: param.default
      };

      // Prepare definitiion for complex structure
      let definitionKey;
      let ref;
      if (param.params) {
        definitionKey = definitionPrefix + param.name;
        ref = `#/definitions/${definitionKey}`;

        definitions[definitionKey] = {
          type: 'object',
          required: extractRequiredNames(param.params),
          properties: buildParameters(method, param.params, definitionKey + '.', true)
        };
      }

      // Analyze param type and related schema
      // Hanlde array type
      if (Array.isArray(param.type)) {
        conf.type = 'array';

        if (param.params) {
          conf.items = { $ref: ref };
        } else {
          conf.items = { type: param.type[0] };
        }

        // Add enum support
        if (param.enum && param.enum.length) conf.items.enum = param.enum;
      } else {
        // Handle Object type
        if (param.params) {
          conf.schema = { $ref: ref };
        }

        // Handle other types
        else {
          if (param.type === 'date') {
            conf.type = 'string';
            conf.format = 'date-time';
          } else {
            conf.type = param.type;
          }

          if (param.enum && param.enum.length) conf.enum = param.enum;
        }
      }

      // Build for definitions' properties
      if (buildForDefinitiion) {
        result[param.name] = conf;
      }

      // Build for parameters
      else {
        // check whether parameter in path
        let paramInPath = path.indexOf(`:${param.name}`) > -1;
        if (paramInPath) conf.in = 'path';

        // If param is not in path and in body, add it to body schema
        if (isInBody && !paramInPath) {
          if (conf.schema) {
            body[param.name] = conf.schema;
          } else {
            body[param.name] = conf;
          }
        }

        // If param is not in body, add it to parameters directly
        else {
          // add `name`, `in`, `required` property
          conf.in = conf.in || defaultIn;
          conf.name = param.name;

          // Param in path must be required
          conf.required = paramInPath ? true : param.required;

          result[param.name] = conf;
        }
      }
    });

    if (buildForDefinitiion) {
      return result;
    } else {
      result = values(result);
      if (isInBody) {
        if (Object.keys(body).length) {
          definitions[bodyDefinitionKey] = {
            type: 'object',
            properties: body
          };

          result.push({
            in: 'body',
            name: 'body',
            description: 'body',
            required: true,
            schema: {
              $ref: `#/definitions/${bodyDefinitionKey}`
            }
          });
        } else {
          // Allow pass json body to post action
          result.push({
            in: 'body',
            name: 'body',
            description: 'body',
            required: false,
            schema: {
              type: 'object'
            }
          });
        }
      }

      return result;
    }
  }

  // Add tag by name and description
  function addTag(name, description) {
    if (addedTags[name]) return;
    tags.push({
      name: name,
      description: description
    });

    addedTags[name] = true;
  }

  // Choose content type
  function chooseContentType(params) {
    let consumes = ['application/json'];
    for (let i = 0; i < params.length; i++) {
      let param = params[i] || {};
      if (param.type === 'file') {
        consumes = ['multipart/form-data'];
        break;
      }

      if (param.in === 'formData') {
        consumes = ['application/x-www-form-urlencoded'];
        break;
      }
    }

    return consumes;
  }

  // add path by method
  function addPath(method) {
    if (method.name === '__swagger__') return;

    let path = pathReplacer(method.fullPath());
    let httpMethod = method.route.verb;

    if (httpMethod === 'use') return;

    let pathConfig = get(paths, path) || {};

    let tagName = get(method, 'parent.name') || '';
    let tagDesc = get(method, 'parent.description') || get(method, 'parent.settings.description') || '';

    addTag(tagName, tagDesc);

    let parameters = buildParameters(method, method.params);

    // Choose content-type
    let consumes = chooseContentType(parameters);

    pathConfig[httpMethod] = {
      tags: [tagName],
      summary: `${method.fullName()} => ${method.description}`,
      description: method.notes,
      consumes: consumes,
      produces: supportTypes,
      parameters: parameters,
      responses: defaultResponses || {},
      security: securities
    };

    set(paths, path, pathConfig);
  }

  app.allMethods().map(addPath);

  swagger.tags = tags;
  swagger.paths = paths;
  swagger.definitions = definitions;
  swagger.consumes = acceptTypes;
  swagger.produces = supportTypes;

  return swagger;
}

// Swagger Plugin
function swaggerPlugin(app, options) {
  // Check baiji version
  assert(
    semver.satisfies(app.constructor.VERSION, `>= ${MINIMAL_VERSION_REQUIRED}`),
    `baiji-swagger plugin require baiji version larger than ${MINIMAL_VERSION_REQUIRED}`
  );

  app.on('mount', function() {
    let config = buildSwaggerConfig(this, options);

    function createSwaggerServer(url) {
      let swaggerApp = express();

      // Set view config
      swaggerApp.set('view engine', 'ejs');
      swaggerApp.set('views', path.join(__dirname, 'views'));

      // Static files support
      swaggerApp.use(
        express.static(
          path.dirname(require.resolve('swagger-ui-dist/index.html')),
          { index: false }
        )
      );

      // Swagger config api
      swaggerApp.get('/config', function(req, res) {
        res.send(config);
      });

      // Swagger ui
      swaggerApp.get('/', function(req, res) {
        res.render('index', { title: get(config, 'info.title'), configUrl: url });
      });

      return swaggerApp;
    }

    // use swagger service middleware
    this.use(
      createSwaggerServer(
        path.posix.join(
          config.basePath || '/',
          this.fullPath(),
          SWAGGER_BASE_PATH,
          'config'
        )
      ),
      {
        name: SWAGGER_BASE_PATH,
        description: 'swagger documentation plugin',
        mountPath: SWAGGER_BASE_PATH
      }
    );
  });

  return null;
}

module.exports = swaggerPlugin;
<commit_msg>bugfix: `all` methods not listed<commit_after>'use strict';

const get = require('lodash.get');
const set = require('lodash.set');
const values = require('lodash.values');
const map = require('lodash.map');
const reduce = require('lodash.reduce');
const express = require('express');
const path = require('path');
const assert = require('assert');
const semver = require('semver');

const SWAGGER_VERSION = '2.0';
const SWAGGER_BASE_PATH = '__swagger__';
const MINIMAL_VERSION_REQUIRED = '0.8.17';

const DEFAULT_RESPONSES = {
  default: { description: 'Default responses' }
};

// Install swagger plugin
function buildSwaggerConfig(app, options) {
  options = options || {};
  let defaultResponses = options.defaultResponses || DEFAULT_RESPONSES;
  let tags = [];
  let paths = {};
  let definitions = Object.assign({}, get(options, 'swagger.definitions') || {});

  let addedTags = {};

  let supportTypes = app.get('adapterOptions.supportedTypes') || [
    'application/json'
  ];

  let acceptTypes = [
    'application/json',
    'application/x-www-form-urlencoded',
    'multipart/form-data'
  ];

  // Default swagger config
  let swagger = Object.assign({
    basePath: '/',
    schemes: ['http'],
    host: '',
    swagger: SWAGGER_VERSION,
    info: {
      title: app.get('title') || '',
      description: app.get('description') || '',
      version: app.get('version')
    }
  }, options.swagger || {});

  // Build security
  let securities = map(swagger.securityDefinitions || {}, function(security, name) {
    let res = {};
    if (security.type === 'oauth2') {
      res[name] = Object.keys(security.scopes || {});
    } else {
      res[name] = [];
    }
    return res;
  });

  // Transfer `:id` like parameter to `{id}`
  function pathReplacer(path) {
    return path.replace(/:([a-zA-Z0-9\-_]+)/g, function(__, capture) {
      return `{${capture}}`;
    });
  }

  // extract required names for definitions according to params
  function extractRequiredNames(params) {
    let requireds = [];
    map(params, function(param) {
      param.required && requireds.push(param.name);
    });
    return requireds;
  }

  // Detect whether parameters should be placed in body, formData or query
  // Header currently is not supported
  function chooseParameterPositionBy(verb, params) {
    if (['get', 'options'].indexOf(verb) > -1) return 'query';

    let shouldInBody;

    if (params.length) {
      shouldInBody = reduce(params, function(res, param) {
        if (param.params) {
          return res || true;
        } else {
          return res || false;
        }
      }, false);
    } else {
      // Set parameter position as `body` when there is on params required
      shouldInBody = true;
    }

    return shouldInBody ? 'body' : 'formData';
  }

  // Build swagger compatible parameters
  function buildParameters(method, params, definitionPrefix, buildForDefinitiion) {
    let defaultIn = buildForDefinitiion ?
      'query' :
      chooseParameterPositionBy(method.route.verb, params);

    let path = method.fullPath();

    let bodyDefinitionKey = `${method.fullName()}.params`;
    definitionPrefix = definitionPrefix || `${bodyDefinitionKey}.`;

    let result = {};
    let body = {};
    let isInBody = defaultIn === 'body';

    // Iterate over all parameters
    map(params, function(param) {
      let conf = {
        description: param.description,
        default: param.default
      };

      // Prepare definitiion for complex structure
      let definitionKey;
      let ref;
      if (param.params) {
        definitionKey = definitionPrefix + param.name;
        ref = `#/definitions/${definitionKey}`;

        definitions[definitionKey] = {
          type: 'object',
          required: extractRequiredNames(param.params),
          properties: buildParameters(method, param.params, definitionKey + '.', true)
        };
      }

      // Analyze param type and related schema
      // Hanlde array type
      if (Array.isArray(param.type)) {
        conf.type = 'array';

        if (param.params) {
          conf.items = { $ref: ref };
        } else {
          conf.items = { type: param.type[0] };
        }

        // Add enum support
        if (param.enum && param.enum.length) conf.items.enum = param.enum;
      } else {
        // Handle Object type
        if (param.params) {
          conf.schema = { $ref: ref };
        }

        // Handle other types
        else {
          if (param.type === 'date') {
            conf.type = 'string';
            conf.format = 'date-time';
          } else {
            conf.type = param.type;
          }

          if (param.enum && param.enum.length) conf.enum = param.enum;
        }
      }

      // Build for definitions' properties
      if (buildForDefinitiion) {
        result[param.name] = conf;
      }

      // Build for parameters
      else {
        // check whether parameter in path
        let paramInPath = path.indexOf(`:${param.name}`) > -1;
        if (paramInPath) conf.in = 'path';

        // If param is not in path and in body, add it to body schema
        if (isInBody && !paramInPath) {
          if (conf.schema) {
            body[param.name] = conf.schema;
          } else {
            body[param.name] = conf;
          }
        }

        // If param is not in body, add it to parameters directly
        else {
          // add `name`, `in`, `required` property
          conf.in = conf.in || defaultIn;
          conf.name = param.name;

          // Param in path must be required
          conf.required = paramInPath ? true : param.required;

          result[param.name] = conf;
        }
      }
    });

    if (buildForDefinitiion) {
      return result;
    } else {
      result = values(result);
      if (isInBody) {
        if (Object.keys(body).length) {
          definitions[bodyDefinitionKey] = {
            type: 'object',
            properties: body
          };

          result.push({
            in: 'body',
            name: 'body',
            description: 'body',
            required: true,
            schema: {
              $ref: `#/definitions/${bodyDefinitionKey}`
            }
          });
        } else {
          // Allow pass json body to post action
          result.push({
            in: 'body',
            name: 'body',
            description: 'body',
            required: false,
            schema: {
              type: 'object'
            }
          });
        }
      }

      return result;
    }
  }

  // Add tag by name and description
  function addTag(name, description) {
    if (addedTags[name]) return;
    tags.push({
      name: name,
      description: description
    });

    addedTags[name] = true;
  }

  // Choose content type
  function chooseContentType(params) {
    let consumes = ['application/json'];
    for (let i = 0; i < params.length; i++) {
      let param = params[i] || {};
      if (param.type === 'file') {
        consumes = ['multipart/form-data'];
        break;
      }

      if (param.in === 'formData') {
        consumes = ['application/x-www-form-urlencoded'];
        break;
      }
    }

    return consumes;
  }

  // add path by method
  function addPath(method) {
    if (method.name === '__swagger__') return;

    let path = pathReplacer(method.fullPath());
    let httpMethod = method.route.verb;

    if (httpMethod === 'use') return;

    let pathConfig = get(paths, path) || {};

    let tagName = get(method, 'parent.name') || '';
    let tagDesc = get(method, 'parent.description') || get(method, 'parent.settings.description') || '';

    addTag(tagName, tagDesc);

    let parameters = buildParameters(method, method.params);

    // Choose content-type
    let consumes = chooseContentType(parameters);

    if (httpMethod === 'all') {
      ['get', 'post', 'put', 'delete', 'patch'].forEach(function(verb) {
        pathConfig[verb] = {
          tags: [tagName],
          summary: `${method.fullName()} => ${method.description}`,
          description: method.notes,
          consumes: consumes,
          produces: supportTypes,
          parameters: parameters,
          responses: defaultResponses || {},
          security: securities
        };
      });
    } else {
      pathConfig[httpMethod] = {
        tags: [tagName],
        summary: `${method.fullName()} => ${method.description}`,
        description: method.notes,
        consumes: consumes,
        produces: supportTypes,
        parameters: parameters,
        responses: defaultResponses || {},
        security: securities
      };
    }

    set(paths, path, pathConfig);
  }

  app.allMethods().map(addPath);

  swagger.tags = tags;
  swagger.paths = paths;
  swagger.definitions = definitions;
  swagger.consumes = acceptTypes;
  swagger.produces = supportTypes;

  return swagger;
}

// Swagger Plugin
function swaggerPlugin(app, options) {
  // Check baiji version
  assert(
    semver.satisfies(app.constructor.VERSION, `>= ${MINIMAL_VERSION_REQUIRED}`),
    `baiji-swagger plugin require baiji version larger than ${MINIMAL_VERSION_REQUIRED}`
  );

  app.on('mount', function() {
    let config = buildSwaggerConfig(this, options);

    function createSwaggerServer(url) {
      let swaggerApp = express();

      // Set view config
      swaggerApp.set('view engine', 'ejs');
      swaggerApp.set('views', path.join(__dirname, 'views'));

      // Static files support
      swaggerApp.use(
        express.static(
          path.dirname(require.resolve('swagger-ui-dist/index.html')),
          { index: false }
        )
      );

      // Swagger config api
      swaggerApp.get('/config', function(req, res) {
        res.send(config);
      });

      // Swagger ui
      swaggerApp.get('/', function(req, res) {
        res.render('index', { title: get(config, 'info.title'), configUrl: url });
      });

      return swaggerApp;
    }

    // use swagger service middleware
    this.use(
      createSwaggerServer(
        path.posix.join(
          config.basePath || '/',
          this.fullPath(),
          SWAGGER_BASE_PATH,
          'config'
        )
      ),
      {
        name: SWAGGER_BASE_PATH,
        description: 'swagger documentation plugin',
        mountPath: SWAGGER_BASE_PATH
      }
    );
  });

  return null;
}

module.exports = swaggerPlugin;
<|endoftext|>


<commit_before>'use strict';

// Node.js built-ins

const path = require('path');

// foreign modules

const argvOne = require('argv-one');
const parseArgs = require('minimist');
const updateNotifier = require('update-notifier');

// local modules

const exec = require('./lib/commands').exec;
const pkg = require('./package.json');

// this module

updateNotifier({pkg}).notify();

const cmd = path.basename(argvOne({ argv: process.argv, pkg }));

const parsedArgs = parseArgs(process.argv.slice(2));

function showHelp () {
  console.log(`usage:\n  ${cmd} <command> ...\n`);
  console.log(`example:\n  ${cmd} list-commands`);
}

if (!parsedArgs._.length) {
  showHelp();
  return;
}

const command = parsedArgs._[0];

if (command === 'list-commands') {
  require('./commands/list-commands');
  return;
}

exec(command)
  .catch((err) => {
    if (err && err.code === 'ENOENT') {
      console.error(`Error: "${command}" is not an available ${cmd} command\n`);
      showHelp();
      process.exit(1);
    }
  });
<commit_msg>ESLint: avoid using `return` outside of functions<commit_after>'use strict';

// Node.js built-ins

const path = require('path');

// foreign modules

const argvOne = require('argv-one');
const parseArgs = require('minimist');
const updateNotifier = require('update-notifier');

// local modules

const exec = require('./lib/commands').exec;
const pkg = require('./package.json');

// this module

updateNotifier({pkg}).notify();

const cmd = path.basename(argvOne({ argv: process.argv, pkg }));

const parsedArgs = parseArgs(process.argv.slice(2));

function showHelp () {
  console.log(`usage:\n  ${cmd} <command> ...\n`);
  console.log(`example:\n  ${cmd} list-commands`);
}

if (!parsedArgs._.length) {
  showHelp();
  process.exit(0);
}

const command = parsedArgs._[0];

if (command === 'list-commands') {
  require('./commands/list-commands');
  process.exit(0);
}

exec(command)
  .catch((err) => {
    if (err && err.code === 'ENOENT') {
      console.error(`Error: "${command}" is not an available ${cmd} command\n`);
      showHelp();
      process.exit(1);
    }
  });
<|endoftext|>


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

/*
  Determine Basal

  Released under MIT license. See the accompanying LICENSE.txt file for
  full terms and conditions

  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.
*/
function usage ( ) {
  console.error('usage: ', process.argv.slice(0, 2), '<iob.json> <currenttemp.json> <glucose.json> <profile.json> [autosens.json] [meal.json]');

}
/* istanbul ignore next */
if (!module.parent) {
    var determinebasal = init();

    var argv = require('yargs')
      .usage("$0 iob.json currenttemp.json glucose.json profile.json [meal.json]")
      .option('auto-sens', {
        alias: 'a',
        describe: "Auto-sensitivity configuration",
        default: true

      })

      .strict(true)
      .help('help')
    ;

    var params = argv.argv;

    var iob_input = params._.slice(0, 1).pop();
    if ([null, '--help', '-h', 'help'].indexOf(iob_input) > 0) {
      usage( );
      process.exit(0)
    }
    var currenttemp_input = params._.slice(1, 2).pop();
    var glucose_input = params._.slice(2, 3).pop();
    var profile_input = params._.slice(3, 4).pop();
    var meal_input = params._.slice(4, 5).pop();
    var autosens_input = params.autoSens;

    if (!iob_input || !currenttemp_input || !glucose_input || !profile_input) {
        usage( );
        process.exit(1);
    }

    var fs = require('fs');
    try {
        var cwd = process.cwd();
        var glucose_data = require(cwd + '/' + glucose_input);
        var currenttemp = require(cwd + '/' + currenttemp_input);
        var iob_data = require(cwd + '/' + iob_input);
        var profile = require(cwd + '/' + profile_input);
        var glucose_status = determinebasal.getLastGlucose(glucose_data);
    } catch (e) {
        return console.error("Could not parse input data: ", e);
    }

    //console.log(carbratio_data);
    var meal_data = { };
    //console.error("meal_input",meal_input);
    if (typeof meal_input != 'undefined') {
        try {
            meal_data = JSON.parse(fs.readFileSync(meal_input, 'utf8'));
            console.error(JSON.stringify(meal_data));
        } catch (e) {
            var msg = {
              msg: "Optional feature Meal Assist enabled, but could not read required meal data."
            , file: meal_input
            , error: e
            };
            console.error(msg.msg);
            console.log(JSON.stringify(msg));
            process.exit(1);
        }
    }
    //if (meal_input) { meal_data = require(cwd + '/' + meal_input); }

    //console.error(autosens_input);
    var autosens_data = null;
    if (autosens_input) {
      // { "ratio":1 };
      autosens_data = { "ratio": 1 };
      if (autosens_input !== true && autosens_input.length) {
        try {
            autosens_data = JSON.parse(fs.readFileSync(autosens_input, 'utf8'));
            console.error(JSON.stringify(autosens_data));
        } catch (e) {
            var msg = {
              msg: "Optional feature Auto Sensitivity enabled.  Could not find specified auto-sens: " + autosens_input
            , error: e
            };
            console.error(msg.msg);
            console.error(e);
            console.log(JSON.stringify(msg));
            process.exit(1);
        }
      }
    }
    //if old reading from Dexcom do nothing

    var systemTime = new Date();
    var bgTime;
    if (glucose_data[0].display_time) {
        bgTime = new Date(glucose_data[0].display_time.replace('T', ' '));
    } else if (glucose_data[0].dateString) {
        bgTime = new Date(glucose_data[0].dateString);
    } else { console.error("Could not determine last BG time"); }
    var minAgo = (systemTime - bgTime) / 60 / 1000;

    if (minAgo > 10 || minAgo < -5) { // Dexcom data is too old, or way in the future
        var reason = "BG data is too old, or clock set incorrectly "+bgTime+" vs "+systemTime;
        console.error(reason);
        return 1;
    }
    console.error(JSON.stringify(glucose_status));
    console.error(JSON.stringify(currenttemp));
    console.error(JSON.stringify(iob_data));
    console.error(JSON.stringify(profile));

    var setTempBasal = require('oref0/lib/basal-set-temp');

    rT = determinebasal.determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, setTempBasal);

    if(typeof rT.error === 'undefined') {
        console.log(JSON.stringify(rT));
    } else {
        console.error(rT.error);
    }

}

function init() {

    var determinebasal = {
        name: 'determine-basal'
        , label: "OpenAPS Determine Basal"
    };

    determinebasal.getLastGlucose = require('oref0/lib/glucose-get-last');
    determinebasal.determine_basal = require('oref0/lib/determine-basal/determine-basal');
    return determinebasal;

}
module.exports = init;
<commit_msg>tweak older message to match<commit_after>#!/usr/bin/env node

/*
  Determine Basal

  Released under MIT license. See the accompanying LICENSE.txt file for
  full terms and conditions

  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.
*/
function usage ( ) {
  console.error('usage: ', process.argv.slice(0, 2), '<iob.json> <currenttemp.json> <glucose.json> <profile.json> [--auto-sens autosens.json] [meal.json]');

}
/* istanbul ignore next */
if (!module.parent) {
    var determinebasal = init();

    var argv = require('yargs')
      .usage("$0 iob.json currenttemp.json glucose.json profile.json [meal.json]")
      .option('auto-sens', {
        alias: 'a',
        describe: "Auto-sensitivity configuration",
        default: true

      })

      .strict(true)
      .help('help')
    ;

    var params = argv.argv;

    var iob_input = params._.slice(0, 1).pop();
    if ([null, '--help', '-h', 'help'].indexOf(iob_input) > 0) {
      usage( );
      process.exit(0)
    }
    var currenttemp_input = params._.slice(1, 2).pop();
    var glucose_input = params._.slice(2, 3).pop();
    var profile_input = params._.slice(3, 4).pop();
    var meal_input = params._.slice(4, 5).pop();
    var autosens_input = params.autoSens;

    if (!iob_input || !currenttemp_input || !glucose_input || !profile_input) {
        usage( );
        process.exit(1);
    }

    var fs = require('fs');
    try {
        var cwd = process.cwd();
        var glucose_data = require(cwd + '/' + glucose_input);
        var currenttemp = require(cwd + '/' + currenttemp_input);
        var iob_data = require(cwd + '/' + iob_input);
        var profile = require(cwd + '/' + profile_input);
        var glucose_status = determinebasal.getLastGlucose(glucose_data);
    } catch (e) {
        return console.error("Could not parse input data: ", e);
    }

    //console.log(carbratio_data);
    var meal_data = { };
    //console.error("meal_input",meal_input);
    if (typeof meal_input != 'undefined') {
        try {
            meal_data = JSON.parse(fs.readFileSync(meal_input, 'utf8'));
            console.error(JSON.stringify(meal_data));
        } catch (e) {
            var msg = {
              msg: "Optional feature Meal Assist enabled, but could not read required meal data."
            , file: meal_input
            , error: e
            };
            console.error(msg.msg);
            console.log(JSON.stringify(msg));
            process.exit(1);
        }
    }
    //if (meal_input) { meal_data = require(cwd + '/' + meal_input); }

    //console.error(autosens_input);
    var autosens_data = null;
    if (autosens_input) {
      // { "ratio":1 };
      autosens_data = { "ratio": 1 };
      if (autosens_input !== true && autosens_input.length) {
        try {
            autosens_data = JSON.parse(fs.readFileSync(autosens_input, 'utf8'));
            console.error(JSON.stringify(autosens_data));
        } catch (e) {
            var msg = {
              msg: "Optional feature Auto Sensitivity enabled.  Could not find specified auto-sens: " + autosens_input
            , error: e
            };
            console.error(msg.msg);
            console.error(e);
            console.log(JSON.stringify(msg));
            process.exit(1);
        }
      }
    }
    //if old reading from Dexcom do nothing

    var systemTime = new Date();
    var bgTime;
    if (glucose_data[0].display_time) {
        bgTime = new Date(glucose_data[0].display_time.replace('T', ' '));
    } else if (glucose_data[0].dateString) {
        bgTime = new Date(glucose_data[0].dateString);
    } else { console.error("Could not determine last BG time"); }
    var minAgo = (systemTime - bgTime) / 60 / 1000;

    if (minAgo > 10 || minAgo < -5) { // Dexcom data is too old, or way in the future
        var reason = "BG data is too old, or clock set incorrectly "+bgTime+" vs "+systemTime;
        console.error(reason);
        return 1;
    }
    console.error(JSON.stringify(glucose_status));
    console.error(JSON.stringify(currenttemp));
    console.error(JSON.stringify(iob_data));
    console.error(JSON.stringify(profile));

    var setTempBasal = require('oref0/lib/basal-set-temp');

    rT = determinebasal.determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, setTempBasal);

    if(typeof rT.error === 'undefined') {
        console.log(JSON.stringify(rT));
    } else {
        console.error(rT.error);
    }

}

function init() {

    var determinebasal = {
        name: 'determine-basal'
        , label: "OpenAPS Determine Basal"
    };

    determinebasal.getLastGlucose = require('oref0/lib/glucose-get-last');
    determinebasal.determine_basal = require('oref0/lib/determine-basal/determine-basal');
    return determinebasal;

}
module.exports = init;
<|endoftext|>


<commit_before>var net = require('net'),
    protobuf = require('protobuf.js'),
    butils = require('butils');

var messageCodes = {
    '0': 'RpbErrorResp',
    '1': 'RpbPingReq',
    '2': 'RpbPingResp',
    '3': 'RpbGetClientIdReq',
    '4': 'RpbGetClientIdResp',
    '5': 'RpbSetClientIdReq',
    '6': 'RpbSetClientIdResp',
    '7': 'RpbGetServerInfoReq',
    '8': 'RpbGetServerInfoResp',
    '9': 'RpbGetReq',
    '10': 'RpbGetResp',
    '11': 'RpbPutReq',
    '12': 'RpbPutResp',
    '13': 'RpbDelReq',
    '14': 'RpbDelResp',
    '15': 'RpbListBucketsReq',
    '16': 'RpbListBucketsResp',
    '17': 'RpbListKeysReq',
    '18': 'RpbListKeysResp',
    '19': 'RpbGetBucketReq',
    '20': 'RpbGetBucketResp',
    '21': 'RpbSetBucketReq',
    '22': 'RpbSetBucketResp',
    '23': 'RpbMapRedReq',
    '24': 'RpbMapRedResp',
    '25': 'RpbIndexReq',
    '26': 'RpbIndexResp',
    '27': 'RpbSearchQueryReq',
    '28': 'RpbSearchQueryResp'
};
Object.keys(messageCodes).forEach(function (key) {
    messageCodes[messageCodes[key]] = Number(key);
});

function RiakPBC(options) {
    var self = this;
    options = options || {};
    self.host = options.host || '127.0.0.1';
    self.port = options.port || 8087;
    self.bucket = options.bucket || undefined;
    self.translator = protobuf.loadSchema('./spec/riak_kv.proto');
    self.client = new net.Socket();
    self.connected = false;
    self.client.on('end', self.disconnect);
    self.client.on('error', self.disconnect);
    self.paused = false;
    self.queue = [];
    var mc, reply = {};

    function splitPacket(pkt) {
        var ret = [], len, pos = 0, end = pkt.length;
        while (pos < end) {
            len = butils.readInt32(pkt, pos);
            ret.push(pkt.slice(pos + 4, pos + len + 4));
            pos += len + 4;
        }
        return ret;
    }

    self.client.on('data', function (chunk) {
        splitPacket(chunk).forEach(function (packet) {
            mc = messageCodes['' + packet[0]];
            reply = _merge(reply, self.translator.decode(mc, packet.slice(1)));
            if (!self.task.expectMultiple || reply.done || mc === 'RpbErrorResp') {
                self.task.callback(reply);
                mc = undefined;
                self.task = undefined;
                reply = {};
                self.paused = false;
                self.processNext();
            }
        });
    });

    self.processNext = function () {
        if (self.queue.length && !self.paused) {
            self.paused = true;
            self.connect(function () {
                self.task = self.queue.shift();
                self.client.write(self.task.message);
            });
        }
    };
}

function _merge(obj1, obj2) {
    var obj = {};
    if (obj2.hasOwnProperty('phase')) {
        obj = obj1;
        obj[obj2.phase] = JSON.parse(obj2.response);
    } else {
        [obj1, obj2].forEach(function (old) {
            Object.keys(old).forEach(function (key) {
                if (!old.hasOwnProperty(key)) return;
                if (Array.isArray(old[key])) {
                    if (!obj[key]) obj[key] = [];
                    obj[key] = obj[key].concat(old[key]);
                } else {
                    obj[key] = old[key];
                }
            });
        });
    }
    return obj;
}

RiakPBC.prototype.makeRequest = function (type, data, callback, expectMultiple) {
    var self = this,
        reply = {},
        buffer = this.translator.encode(type, data),
        message = [];

    butils.writeInt32(message, buffer.length + 1);
    butils.writeInt(message, messageCodes[type], 4);
    message = message.concat(buffer);
    self.queue.push({ message: new Buffer(message), callback: callback, expectMultiple: expectMultiple });
    process.nextTick(self.processNext);
};

RiakPBC.prototype.getBuckets = function (callback) {
    this.makeRequest('RpbListBucketsReq', null, callback);
};

RiakPBC.prototype.getBucket = function (params, callback) {
    this.makeRequest('RpbGetBucketReq', params, callback);
};

RiakPBC.prototype.setBucket = function (params, callback) {
    this.makeRequest('RpbSetBucketReq', params, callback);
};

RiakPBC.prototype.getKeys = function (params, callback) {
    this.makeRequest('RpbListKeysReq', params, callback, true);
};

RiakPBC.prototype.put = function (params, callback) {
    this.makeRequest('RpbPutReq', params, callback);
};

RiakPBC.prototype.get = function (params, callback) {
    this.makeRequest('RpbGetReq', params, callback);
};

RiakPBC.prototype.del = function (params, callback) {
    this.makeRequest('RpbDelReq', params, callback);
};

RiakPBC.prototype.mapred = function (params, callback) {
    this.makeRequest('RpbMapRedReq', params, callback, true);
};

RiakPBC.prototype.getIndex = function (params, callback) {
    this.makeRequest('RpbIndexReq', params, callback);
};

RiakPBC.prototype.search = function (params, callback) {
    this.makeRequest('RpbSearchQueryReq', params, callback);
};

RiakPBC.prototype.getClientId = function (callback) {
    this.makeRequest('RpbGetClientIdReq', null, callback);
};

RiakPBC.prototype.setClientId = function (params, callback) {
    this.makeRequest('RpbSetClientIdReq', params, callback);
};

RiakPBC.prototype.getServerInfo = function (callback) {
    this.makeRequest('RpbGetServerInfoReq', null, callback);
};

RiakPBC.prototype.ping = function (callback) {
    this.makeRequest('RpbPingReq', null, callback);
};

RiakPBC.prototype.connect = function (callback) {
    if (this.connected) return callback();
    var self = this;
    self.client.connect(self.port, self.host, function () {
        self.connected = true;
        callback();
    });
};

RiakPBC.prototype.disconnect = function () {
    if (!this.connected) return;
    this.client.end();
    this.connected = false;
    if (this.task) {
        this.queue.unshift(this.task);
        this.task = undefined;
    }
};

exports.createClient = function (options) {
    return new RiakPBC(options);
};
<commit_msg>Fix overwrite in merge for multiple MapReduce responses.<commit_after>var net = require('net'),
    protobuf = require('protobuf.js'),
    butils = require('butils');

var messageCodes = {
    '0': 'RpbErrorResp',
    '1': 'RpbPingReq',
    '2': 'RpbPingResp',
    '3': 'RpbGetClientIdReq',
    '4': 'RpbGetClientIdResp',
    '5': 'RpbSetClientIdReq',
    '6': 'RpbSetClientIdResp',
    '7': 'RpbGetServerInfoReq',
    '8': 'RpbGetServerInfoResp',
    '9': 'RpbGetReq',
    '10': 'RpbGetResp',
    '11': 'RpbPutReq',
    '12': 'RpbPutResp',
    '13': 'RpbDelReq',
    '14': 'RpbDelResp',
    '15': 'RpbListBucketsReq',
    '16': 'RpbListBucketsResp',
    '17': 'RpbListKeysReq',
    '18': 'RpbListKeysResp',
    '19': 'RpbGetBucketReq',
    '20': 'RpbGetBucketResp',
    '21': 'RpbSetBucketReq',
    '22': 'RpbSetBucketResp',
    '23': 'RpbMapRedReq',
    '24': 'RpbMapRedResp',
    '25': 'RpbIndexReq',
    '26': 'RpbIndexResp',
    '27': 'RpbSearchQueryReq',
    '28': 'RpbSearchQueryResp'
};
Object.keys(messageCodes).forEach(function (key) {
    messageCodes[messageCodes[key]] = Number(key);
});

function RiakPBC(options) {
    var self = this;
    options = options || {};
    self.host = options.host || '127.0.0.1';
    self.port = options.port || 8087;
    self.bucket = options.bucket || undefined;
    self.translator = protobuf.loadSchema('./spec/riak_kv.proto');
    self.client = new net.Socket();
    self.connected = false;
    self.client.on('end', self.disconnect);
    self.client.on('error', self.disconnect);
    self.paused = false;
    self.queue = [];
    var mc, reply = {};

    function splitPacket(pkt) {
        var ret = [], len, pos = 0, end = pkt.length;
        while (pos < end) {
            len = butils.readInt32(pkt, pos);
            ret.push(pkt.slice(pos + 4, pos + len + 4));
            pos += len + 4;
        }
        return ret;
    }

    self.client.on('data', function (chunk) {
        splitPacket(chunk).forEach(function (packet) {
            mc = messageCodes['' + packet[0]];
            reply = _merge(reply, self.translator.decode(mc, packet.slice(1)));
            if (!self.task.expectMultiple || reply.done || mc === 'RpbErrorResp') {
                self.task.callback(reply);
                mc = undefined;
                self.task = undefined;
                reply = {};
                self.paused = false;
                self.processNext();
            }
        });
    });

    self.processNext = function () {
        if (self.queue.length && !self.paused) {
            self.paused = true;
            self.connect(function () {
                self.task = self.queue.shift();
                self.client.write(self.task.message);
            });
        }
    };
}

function _merge(obj1, obj2) {
    var obj = {};
    if (obj2.hasOwnProperty('phase')) {
        obj = obj1;
        if (obj[obj2.phase] === undefined) obj[obj2.phase] = [];
        obj[obj2.phase] = obj[obj2.phase].concat(JSON.parse(obj2.response));
    } else {
        [obj1, obj2].forEach(function (old) {
            Object.keys(old).forEach(function (key) {
                if (!old.hasOwnProperty(key)) return;
                if (Array.isArray(old[key])) {
                    if (!obj[key]) obj[key] = [];
                    obj[key] = obj[key].concat(old[key]);
                } else {
                    obj[key] = old[key];
                }
            });
        });
    }
    return obj;
}

RiakPBC.prototype.makeRequest = function (type, data, callback, expectMultiple) {
    var self = this,
        reply = {},
        buffer = this.translator.encode(type, data),
        message = [];

    butils.writeInt32(message, buffer.length + 1);
    butils.writeInt(message, messageCodes[type], 4);
    message = message.concat(buffer);
    self.queue.push({ message: new Buffer(message), callback: callback, expectMultiple: expectMultiple });
    process.nextTick(self.processNext);
};

RiakPBC.prototype.getBuckets = function (callback) {
    this.makeRequest('RpbListBucketsReq', null, callback);
};

RiakPBC.prototype.getBucket = function (params, callback) {
    this.makeRequest('RpbGetBucketReq', params, callback);
};

RiakPBC.prototype.setBucket = function (params, callback) {
    this.makeRequest('RpbSetBucketReq', params, callback);
};

RiakPBC.prototype.getKeys = function (params, callback) {
    this.makeRequest('RpbListKeysReq', params, callback, true);
};

RiakPBC.prototype.put = function (params, callback) {
    this.makeRequest('RpbPutReq', params, callback);
};

RiakPBC.prototype.get = function (params, callback) {
    this.makeRequest('RpbGetReq', params, callback);
};

RiakPBC.prototype.del = function (params, callback) {
    this.makeRequest('RpbDelReq', params, callback);
};

RiakPBC.prototype.mapred = function (params, callback) {
    this.makeRequest('RpbMapRedReq', params, callback, true);
};

RiakPBC.prototype.getIndex = function (params, callback) {
    this.makeRequest('RpbIndexReq', params, callback);
};

RiakPBC.prototype.search = function (params, callback) {
    this.makeRequest('RpbSearchQueryReq', params, callback);
};

RiakPBC.prototype.getClientId = function (callback) {
    this.makeRequest('RpbGetClientIdReq', null, callback);
};

RiakPBC.prototype.setClientId = function (params, callback) {
    this.makeRequest('RpbSetClientIdReq', params, callback);
};

RiakPBC.prototype.getServerInfo = function (callback) {
    this.makeRequest('RpbGetServerInfoReq', null, callback);
};

RiakPBC.prototype.ping = function (callback) {
    this.makeRequest('RpbPingReq', null, callback);
};

RiakPBC.prototype.connect = function (callback) {
    if (this.connected) return callback();
    var self = this;
    self.client.connect(self.port, self.host, function () {
        self.connected = true;
        callback();
    });
};

RiakPBC.prototype.disconnect = function () {
    if (!this.connected) return;
    this.client.end();
    this.connected = false;
    if (this.task) {
        this.queue.unshift(this.task);
        this.task = undefined;
    }
};

exports.createClient = function (options) {
    return new RiakPBC(options);
};
<|endoftext|>


<commit_before>/**
 * light-server
 *
 * Serve, watch, exucute commands and live-reload, all in one.
 *
 * Copyright (c) 2018 by Tianxiang Chen
 */
'use strict'

var morgan = require('morgan')
var connect = require('connect')
var serveStatic = require('serve-static')
var serveIndex = require('serve-index')
var injector = require('connect-injector')
var Gaze = require('gaze').Gaze
var LR = require('./livereload')
var spawn = require('child_process').spawn
var os = require('os').type()

function LightServer (options) {
  if (!(this instanceof LightServer)) return new LightServer(options)
  this.options = options
  if (os === 'Windows_NT') {
    this.shell = 'cmd'
    this.firstParam = '/c'
  } else {
    this.shell = 'bash'
    this.firstParam = '-c'
  }
}

LightServer.prototype.writeLog = function (logLine) {
  !this.options.quiet && console.log(logLine)
}

LightServer.prototype.start = function () {
  var _this = this
  if (!_this.options.serve && !_this.options.proxy) {
    _this.watch()
    return
  }

  var app = connect()
  if (!this.options.quiet) {
    app.use(function (req, res, next) {
      if (req.url === '/favicon.ico') {
        next()
      } else {
        morgan('dev')(req, res, next)
      }
    })
  }

  if (!_this.options.noReload) {
    _this.lr = LR({
      quiet: _this.options.quiet,
      http2: _this.options.http2
    })
    app.use(_this.lr.middleFunc)
    app.use(
      injector(
        function (req, res) {
          return (
            res.getHeader('content-type') &&
            res.getHeader('content-type').indexOf('text/html') !== -1
          )
        },
        function (data, req, res, callback) {
          callback(
            null,
            data
              .toString()
              .replace(
                '',
                ''
              )
          )
        }
      )
    )
  }

  if (_this.options.serve) {
    app.use(
      _this.options.servePrefix || '',
      serveStatic(_this.options.serve, { extensions: ['html'] })
    )
    app.use(
      _this.options.servePrefix || '',
      serveIndex(_this.options.serve, { 'icons': true })
    )
  }

  if (_this.options.proxy) {
    var proxy = require('./proxy')
    app.use(proxy(_this.options.proxy, _this.options.proxypaths).middleFunc)
  }

  if (_this.options.historyindex) {
    var history = require('connect-history-api-fallback')
    app.use(history({ index: _this.options.historyindex }))
    app.use(serveStatic(_this.options.serve))
  }

  var server
  if (_this.options.http2) {
    var fs = require('fs')
    var path = require('path')
    server = require('spdy').createServer(
      {
        key: fs.readFileSync(path.join(__dirname, '/localhost.key')),
        cert: fs.readFileSync(path.join(__dirname, '/localhost.crt'))
      },
      app
    )
  } else {
    server = require('http').createServer(app)
  }

  server
    .listen(_this.options.port, _this.options.bind, function () {
      var listeningAddr =
        (_this.options.http2 ? 'https://' : 'http://') +
        (_this.options.bind || '0.0.0.0') +
        ':' +
        _this.options.port
      console.log('light-server is listening at ' + listeningAddr)
      if (_this.options.serve) {
        _this.writeLog('  serving static dir: ' + _this.options.serve)
        if (_this.options.servePrefix) {
          _this.writeLog('  using prefix ' + _this.options.servePrefix)
        }
      }

      if (_this.options.proxy) {
        _this.writeLog(
          '  when static file not found, proxy to ' + _this.options.proxy
        )
        _this.writeLog(
          '    if url path starts with "' + _this.options.proxypaths + '"'
        )
      }

      _this.writeLog('')
      if (_this.lr) {
        _this.lr.startWS(server) // websocket shares same port with http
      }
      _this.watch()

      if (_this.options.open) {
        var opener = require('opener')
        var openAddr = listeningAddr.replace('://0.0.0.0:', '://localhost:')
        if (_this.options.servePrefix) {
          openAddr += _this.options.servePrefix
        }
        opener(openAddr)
      }
    })
    .on('error', function (err) {
      if (err.errno === 'EADDRINUSE') {
        console.log(
          '## ERROR: port ' + _this.options.port + ' is already in use'
        )
        process.exit(2)
      } else {
        console.log(err)
      }
    })
}

LightServer.prototype.watch = function () {
  var _this = this
  _this.options.watchexps.forEach(function (we) {
    var tokens = we.trim().split(/\s*#\s*/)
    var filesToWatch = tokens[0].trim().split(/\s*,\s*/)
    var commandToRun = tokens[1]
    var reloadOption = tokens[2]
    if (reloadOption !== 'reloadcss' && reloadOption !== 'no-reload') {
      reloadOption = 'reload' // default value
    }

    if (commandToRun || _this.lr) {
      _this.processWatchExp(filesToWatch, commandToRun, reloadOption)
    } else {
      console.log(
        '## WARNING: Ignoring watch expression "' +
          we +
          '", because ' +
          'it doesn\'t specify a command and live-reloading is disabled.'
      )
    }
  })
}

LightServer.prototype.processWatchExp = function (
  filesToWatch,
  commandToRun,
  reloadOption
) {
  var _this = this
  var gaze = new Gaze(filesToWatch, { interval: _this.options.interval })

  // A file has been added/changed/deleted has occurred
  gaze.on('all', function (event, filepath) {
    if (gaze.executing) {
      return
    }

    gaze.executing = true
    _this.writeLog('* file: ' + filepath + ' was ' + event)
    if (!commandToRun) {
      if (_this.lr) {
        _this.lr.trigger(reloadOption, _this.options.delay)
      }

      gaze.executing = false
      return
    }

    console.log('## executing command: ' + commandToRun)
    var start = new Date().getTime()
    var p = spawn(_this.shell, [_this.firstParam, commandToRun], {
      stdio: 'inherit'
    })
    p.on('close', function (code) {
      if (code !== 0) {
        console.log(
          '## ERROR: command ' + commandToRun + ' exited with code ' + code
        )
      } else {
        _this.writeLog(
          '## command succeeded in ' + (new Date().getTime() - start) + 'ms'
        )
        if (_this.lr) {
          _this.lr.trigger(reloadOption, _this.options.delay)
        }
      }

      gaze.executing = false
    })
  })

  if (filesToWatch.length) {
    _this.writeLog(
      'light-server is watching these files: ' + filesToWatch.join(', ')
    )
    _this.writeLog('  when file changes,')
    if (commandToRun) {
      _this.writeLog('  this command will be executed:      ' + commandToRun)
    }
    if (_this.lr) {
      _this.writeLog(
        '  this event will be sent to browser: ' + reloadOption + '\n'
      )
    }
  }
}

module.exports = LightServer
<commit_msg>set redirect to false for serve-static<commit_after>/**
 * light-server
 *
 * Serve, watch, exucute commands and live-reload, all in one.
 *
 * Copyright (c) 2018 by Tianxiang Chen
 */
'use strict'

var morgan = require('morgan')
var connect = require('connect')
var serveStatic = require('serve-static')
var serveIndex = require('serve-index')
var injector = require('connect-injector')
var Gaze = require('gaze').Gaze
var LR = require('./livereload')
var spawn = require('child_process').spawn
var os = require('os').type()

function LightServer (options) {
  if (!(this instanceof LightServer)) return new LightServer(options)
  this.options = options
  if (os === 'Windows_NT') {
    this.shell = 'cmd'
    this.firstParam = '/c'
  } else {
    this.shell = 'bash'
    this.firstParam = '-c'
  }
}

LightServer.prototype.writeLog = function (logLine) {
  !this.options.quiet && console.log(logLine)
}

LightServer.prototype.start = function () {
  var _this = this
  if (!_this.options.serve && !_this.options.proxy) {
    _this.watch()
    return
  }

  var app = connect()
  if (!this.options.quiet) {
    app.use(function (req, res, next) {
      if (req.url === '/favicon.ico') {
        next()
      } else {
        morgan('dev')(req, res, next)
      }
    })
  }

  if (!_this.options.noReload) {
    _this.lr = LR({
      quiet: _this.options.quiet,
      http2: _this.options.http2
    })
    app.use(_this.lr.middleFunc)
    app.use(
      injector(
        function (req, res) {
          return (
            res.getHeader('content-type') &&
            res.getHeader('content-type').indexOf('text/html') !== -1
          )
        },
        function (data, req, res, callback) {
          callback(
            null,
            data
              .toString()
              .replace(
                '',
                ''
              )
          )
        }
      )
    )
  }

  if (_this.options.serve) {
    app.use(
      _this.options.servePrefix || '',
      serveStatic(_this.options.serve, { extensions: ['html'], redirect: false })
    )
    app.use(
      _this.options.servePrefix || '',
      serveIndex(_this.options.serve, { icons: true })
    )
  }

  if (_this.options.proxy) {
    var proxy = require('./proxy')
    app.use(proxy(_this.options.proxy, _this.options.proxypaths).middleFunc)
  }

  if (_this.options.historyindex) {
    var history = require('connect-history-api-fallback')
    app.use(history({ index: _this.options.historyindex }))
    app.use(serveStatic(_this.options.serve))
  }

  var server
  if (_this.options.http2) {
    var fs = require('fs')
    var path = require('path')
    server = require('spdy').createServer(
      {
        key: fs.readFileSync(path.join(__dirname, '/localhost.key')),
        cert: fs.readFileSync(path.join(__dirname, '/localhost.crt'))
      },
      app
    )
  } else {
    server = require('http').createServer(app)
  }

  server
    .listen(_this.options.port, _this.options.bind, function () {
      var listeningAddr =
        (_this.options.http2 ? 'https://' : 'http://') +
        (_this.options.bind || '0.0.0.0') +
        ':' +
        _this.options.port
      console.log('light-server is listening at ' + listeningAddr)
      if (_this.options.serve) {
        _this.writeLog('  serving static dir: ' + _this.options.serve)
        if (_this.options.servePrefix) {
          _this.writeLog('  using prefix ' + _this.options.servePrefix)
        }
      }

      if (_this.options.proxy) {
        _this.writeLog(
          '  when static file not found, proxy to ' + _this.options.proxy
        )
        _this.writeLog(
          '    if url path starts with "' + _this.options.proxypaths + '"'
        )
      }

      _this.writeLog('')
      if (_this.lr) {
        _this.lr.startWS(server) // websocket shares same port with http
      }
      _this.watch()

      if (_this.options.open) {
        var opener = require('opener')
        var openAddr = listeningAddr.replace('://0.0.0.0:', '://localhost:')
        if (_this.options.servePrefix) {
          openAddr += _this.options.servePrefix
        }
        opener(openAddr)
      }
    })
    .on('error', function (err) {
      if (err.errno === 'EADDRINUSE') {
        console.log(
          '## ERROR: port ' + _this.options.port + ' is already in use'
        )
        process.exit(2)
      } else {
        console.log(err)
      }
    })
}

LightServer.prototype.watch = function () {
  var _this = this
  _this.options.watchexps.forEach(function (we) {
    var tokens = we.trim().split(/\s*#\s*/)
    var filesToWatch = tokens[0].trim().split(/\s*,\s*/)
    var commandToRun = tokens[1]
    var reloadOption = tokens[2]
    if (reloadOption !== 'reloadcss' && reloadOption !== 'no-reload') {
      reloadOption = 'reload' // default value
    }

    if (commandToRun || _this.lr) {
      _this.processWatchExp(filesToWatch, commandToRun, reloadOption)
    } else {
      console.log(
        '## WARNING: Ignoring watch expression "' +
          we +
          '", because ' +
          'it doesn\'t specify a command and live-reloading is disabled.'
      )
    }
  })
}

LightServer.prototype.processWatchExp = function (
  filesToWatch,
  commandToRun,
  reloadOption
) {
  var _this = this
  var gaze = new Gaze(filesToWatch, { interval: _this.options.interval })

  // A file has been added/changed/deleted has occurred
  gaze.on('all', function (event, filepath) {
    if (gaze.executing) {
      return
    }

    gaze.executing = true
    _this.writeLog('* file: ' + filepath + ' was ' + event)
    if (!commandToRun) {
      if (_this.lr) {
        _this.lr.trigger(reloadOption, _this.options.delay)
      }

      gaze.executing = false
      return
    }

    console.log('## executing command: ' + commandToRun)
    var start = new Date().getTime()
    var p = spawn(_this.shell, [_this.firstParam, commandToRun], {
      stdio: 'inherit'
    })
    p.on('close', function (code) {
      if (code !== 0) {
        console.log(
          '## ERROR: command ' + commandToRun + ' exited with code ' + code
        )
      } else {
        _this.writeLog(
          '## command succeeded in ' + (new Date().getTime() - start) + 'ms'
        )
        if (_this.lr) {
          _this.lr.trigger(reloadOption, _this.options.delay)
        }
      }

      gaze.executing = false
    })
  })

  if (filesToWatch.length) {
    _this.writeLog(
      'light-server is watching these files: ' + filesToWatch.join(', ')
    )
    _this.writeLog('  when file changes,')
    if (commandToRun) {
      _this.writeLog('  this command will be executed:      ' + commandToRun)
    }
    if (_this.lr) {
      _this.writeLog(
        '  this event will be sent to browser: ' + reloadOption + '\n'
      )
    }
  }
}

module.exports = LightServer
<|endoftext|>


<commit_before>const Hapi =require('hapi');
const Blipp = require('blipp');
const Inert = require('inert');
const Path = require('path');

const server = new Hapi.Server();

server.connection({
    port : 1337,
    host : '127.0.0.1'
});

server.register([Blipp, Inert], (err) => {

    //server static html and image files
    server.route({
        method: 'GET',
        path: '/{files*}',
        handler: {
            directory: {
                path: Path.join( __dirname, 'public'),
                listing: false
            }
        }
    });
    server.ext('onRequest', function (request, reply) {
        console.log('request received');
        return reply.continue();
    });
    server.ext('onPostHandler', function (request, reply) {
        const response = request.response;
        if (response.isBoom && response.output.statusCode === 404) {
            return reply.file('./404.html').code(404);
        }
        return reply.continue();
    });

    server.start((err) => {
        console.log(`Server running at: ${server.info.uri}`);
    })
});
<commit_msg>used prettier<commit_after>const Hapi = require('hapi');
const Blipp = require('blipp');
const Inert = require('inert');
const Path = require('path');

const server = new Hapi.Server();

server.connection({
    port: 1337,
    host: '127.0.0.1'
});

server.register([Blipp, Inert], (err) => {

    //server static html and image files
    server.route({
        method: 'GET',
        path: '/{files*}',
        handler: {
            directory: {
                path: Path.join(__dirname, 'public'),
                listing: false
            }
        }
    });
    server.ext('onRequest', function(request, reply) {
        console.log('request received');
        return reply.continue();
    });
    server.ext('onPostHandler', function(request, reply) {
        const response = request.response;
        if (response.isBoom && response.output.statusCode === 404) {
            return reply.file('./404.html').code(404);
        }
        return reply.continue();
    });

    server.start((err) => {
        console.log(`Server running at: ${server.info.uri}`);
    })
});
<|endoftext|>