<commit_before>'use strict';

var aws = require('aws-sdk');
var exec = require('child_process').exec;
var fs = require('fs');
var os = require('os');
var packageJson = require('./../package.json');
var path = require('path');
var async = require('async');
var zip = new require('node-zip')();
var wrench = require('wrench');
var dotenv = require('dotenv');

var Lambda = function () {
  this.version = packageJson.version;

  return this;
};

Lambda.prototype._createSampleFile = function (file, newFileName) {
  var exampleFile = process.cwd() + '/' + (file || newFileName);
  var boilerplateFile = __dirname + '/' + file + '.example';

  if (!fs.existsSync(exampleFile)) {
    fs.writeFileSync(exampleFile, fs.readFileSync(boilerplateFile));
    console.log(exampleFile + ' file successfully created');
  }
};

Lambda.prototype.setup = function () {
  console.log('Running setup.');
  this._createSampleFile('.env');
  this._createSampleFile('event.json');
  this._createSampleFile('deploy.env');
  this._createSampleFile('context.json');
  console.log('Setup done. Edit the .env, deploy.env, context.json and event.json files as needed.');
};

Lambda.prototype.run = function (program) {
  this._createSampleFile('event.json', program.eventFile);
  var splitHandler = program.handler.split('.');
  var filename = splitHandler[0] + '.js';
  var handlername = splitHandler[1];

  var handler = require(process.cwd() + '/' + filename)[handlername];
  var event = require(process.cwd() + '/' + program.eventFile);
  var context = require(process.cwd() + '/' + program.contextFile);

  this._runHandler(handler, event, program.runtime, context);
};

Lambda.prototype._runHandler = function (handler, event, runtime, context) {

  var callback = function (err, result) {
    if (err) {
      console.log('Error: ' + err);
      process.exit(-1);
    }
    else {
      console.log('Success:');
      if (result) {
        console.log(JSON.stringify(result));
      }
      process.exit(0);
    }
  };

  var isNode43 = (runtime === "nodejs4.3");
  context.succeed = function (result) {
    if (isNode43) {
      console.log('context.succeed() is deprecated with Node.js 4.3 runtime');
    }
    callback(null, result);
  };
  context.fail = function (error) {
    if (isNode43) {
      console.log('context.fail() is deprecated with Node.js 4.3 runtime');
    }
    callback(error);
  };
  context.done = function () {
    if (isNode43) {
      console.log('context.done() is deprecated with Node.js 4.3 runtime');
    }
    callback();
  };

  switch(runtime) {
    case "nodejs":
      handler(event, context);
      break;
    case "nodejs4.3":
      handler(event, context, callback);
      break;
    default:
      console.error("Runtime [" + runtime + "] is not supported.");
  }

};

Lambda.prototype._params = function (program, buffer) {
  var params = {
    FunctionName: program.functionName + (program.environment ? '-' + program.environment : ''),
    Code: {
      ZipFile: buffer
    },
    Handler: program.handler,
    Role: program.role,
    Runtime: program.runtime,
    Description: program.description,
    MemorySize: program.memorySize,
    Timeout: program.timeout,
    Publish: program.publish,
    VpcConfig: {}
  };
  if (program.version) {
    params.FunctionName += ('-' + program.version);
  }
  if (program.vpcSubnets && program.vpcSecurityGroups) {
    params.VpcConfig = {
      'SubnetIds': program.vpcSubnets.split(','),
      'SecurityGroupIds': program.vpcSecurityGroups.split(',')
    };
  }

  return params;
};

/**
 * @deprecated
 */
Lambda.prototype._zipfileTmpPath = function (program) {
  var ms_since_epoch = +new Date();
  var filename = program.functionName + '-' + ms_since_epoch + '.zip';
  var zipfile = path.join(os.tmpDir(), filename);

  return zipfile;
};

Lambda.prototype._rsync = function (program, codeDirectory, callback) {
  var excludes = ['.git*', '*.swp', '.editorconfig', 'deploy.env', '*.log', 'node_modules'],
      excludeArgs = '';
  if (program.excludeGlobs) {
    var excludeGlobs = program.excludeGlobs.split(' ');
    excludeArgs = excludeGlobs.concat(excludes).map(function(exclude) {
      return '--exclude=' + exclude;
    }).join(' ');
  }

  exec('mkdir -p ' + codeDirectory, function(err) {
    if (err) {
      return callback(err);
    }

    exec('rsync -r ' + excludeArgs + ' . ' + codeDirectory, function (err) {
      if (err) {
        return callback(err);
      }

      return callback(null, true);
    });
  });
};

Lambda.prototype._npmInstall = function (program, codeDirectory, callback) {
  exec('npm install --production --prefix ' + codeDirectory, function (err) {
    if (err) {
      return callback(err);
    }

    return callback(null, true);
  });
};

Lambda.prototype._postInstallScript = function (codeDirectory, callback) {
  var script_filename = 'post_install.sh';
  var cmd = './'+script_filename;

  var filePath = [codeDirectory, script_filename].join('/');

  fs.exists(filePath, function(exists) {
    if (exists) {
      console.log('=> Running post install script '+script_filename);
      exec(cmd, { cwd: codeDirectory,maxBuffer: 50 * 1024 * 1024 }, function(error, stdout, stderr){

        if (error) callback(error +" stdout: " + stdout + "stderr"+stderr);
        else {
          console.log("\t\t"+stdout);
          callback(null);
        }
      });

    } else {
      callback(null);
    }
  });

};

Lambda.prototype._zip = function (program, codeDirectory, callback) {

  var options = {
    type: 'nodebuffer',
    compression: 'DEFLATE'
  };

  console.log('=> Zipping repo. This might take up to 30 seconds');
  var files = wrench.readdirSyncRecursive(codeDirectory);
  files.forEach(function (file) {
    var filePath = [codeDirectory, file].join('/');
    var isFile = fs.lstatSync(filePath).isFile();
    if (isFile) {
      var content = fs.readFileSync(filePath);
      zip.file(file, content);
    }
  });

  var data = zip.generate(options);

  return callback(null, data);
};

Lambda.prototype._nativeZip = function (program, codeDirectory, callback) {
  var zipfile = this._zipfileTmpPath(program),
    cmd = 'zip -r ' + zipfile + ' .';

  exec(cmd, {
    cwd: codeDirectory,
    maxBuffer: 50 * 1024 * 1024
  }, function (err) {
    if (err !== null) {
      return callback(err, null);
    }

    var data = fs.readFileSync(zipfile);
    callback(null, data);
  });
};

Lambda.prototype._codeDirectory = function (program) {
  var epoch_time = +new Date();

  return os.tmpDir() + '/' + program.functionName + '-' + epoch_time;
};

Lambda.prototype._cleanDirectory = function (codeDirectory, callback) {
  exec('rm -rf ' + codeDirectory, function (err) {
    if (err) {
      throw err;
    }

    fs.mkdir(codeDirectory, function(err) {
      if (err) {
        throw err;
      }

      return callback(null, true);
    });
  });
};

Lambda.prototype._setEnvironmentVars = function (program, codeDirectory) {
  console.log('=> Setting "environment variables" for Lambda from %s', program.configFile);
  // Which file is the handler?
  var handlerFileName = codeDirectory + '/' + program.handler.split('.').shift() + '.js';
  var contents = fs.readFileSync(handlerFileName);

  var configValues = fs.readFileSync(program.configFile);
  var prefix = '////////////////////////////////////\n// "Environment Variables"\n';
  var config = dotenv.parse(configValues);
  var contentStr = contents.toString();

  for (var k in config) {
    if (!config.hasOwnProperty(k)) {
      continue;
    }

    // Use JSON.stringify to ensure that it's valid code.
    prefix += 'process.env["' + k + '"]=' + JSON.stringify(config[k]) + ';\n';
  }
  prefix += '////////////////////////////////////\n\n';

  // If the first line of the file is 'use strict', append after
  if (contentStr.trim().indexOf('use strict') === 1) {
    contentStr = contentStr.replace(/([`'"]use strict[`'"][;]?)/, '$1\n' + prefix);
  } else {
    contentStr = prefix + contentStr;
  }

  fs.writeFileSync(handlerFileName, contentStr);
};

Lambda.prototype._uploadExisting = function(lambda, params, cb) {
  return lambda.updateFunctionCode({
    'FunctionName': params.FunctionName,
    'ZipFile': params.Code.ZipFile,
    'Publish': params.publish
  }, function(err, data) {
    if(err) {
      return cb(err, data);
    }

    return lambda.updateFunctionConfiguration({
      'FunctionName': params.FunctionName,
      'Description': params.Description,
      'Handler': params.Handler,
      'MemorySize': params.MemorySize,
      'Role': params.Role,
      'Timeout': params.Timeout,
      'VpcConfig': params.VpcConfig
    }, function(err, data) {
      return cb(err, data);
    });
  });
};

Lambda.prototype._uploadNew = function(lambda, params, cb) {
  return lambda.createFunction(params, function(err, data) {
    return cb(err, data);
  });
};

Lambda.prototype._archive = function (program, archive_callback) {
  this._createSampleFile('.env');

  // Warn if not building on 64-bit linux
  var arch = process.platform + '.' + process.arch;
  if (arch !== 'linux.x64') {
    console.warn('Warning!!! You are building on a platform that is not 64-bit Linux (%s). ' +
      'If any of your Node dependencies include C-extensions, they may not work as expected in the ' +
      'Lambda environment.\n\n', arch);
  }

  var _this = this;
  var codeDirectory = _this._codeDirectory(program);

  console.log('=> Moving files to temporary directory');
  // Move all files to tmp folder (except .git, .log, event.json and node_modules)
  _this._cleanDirectory(codeDirectory, function(err) {
    if (err) {
      return archive_callback(err);
    }
    _this._rsync(program, codeDirectory, function (err) {
      if (err) {
        return archive_callback(err);
      }
      console.log('=> Running npm install --production');
      _this._npmInstall(program, codeDirectory, function (err) {
        if (err) {
          return archive_callback(err);
        }

        _this._postInstallScript(codeDirectory, function (err) {
          if (err) {
            return archive_callback(err);
          }

          // Add custom environment variables if program.configFile is defined
          if (program.configFile) {
            _this._setEnvironmentVars(program, codeDirectory);
          }
          console.log('=> Zipping deployment package');

          var archive = process.platform !== 'win32' ? _this._nativeZip : _this._zip;
          archive = archive.bind(_this);

          archive(program, codeDirectory, archive_callback);
        });
      });
    });
  });
};

Lambda.prototype.package = function (program) {
  var _this = this;
  if (!program.packageDirectory) {
    throw 'packageDirectory not specified!';
  } else {
    try {
      var isDir = fs.lstatSync(program.packageDirectory).isDirectory();

      if (!isDir) {
        throw program.packageDirectory + ' is not a directory!';
      }
    } catch(err) {
      if (err.code === 'ENOENT') {
        console.log('=> Creating package directory');
        fs.mkdirSync(program.packageDirectory);
      } else {
        throw err;
      }
    }
  }

  _this._archive(program, function (err, buffer) {
    if (err) {
      throw err;
    }
    var basename = program.functionName + (program.environment ? '-' + program.environment : '');
    var zipfile = path.join(program.packageDirectory, basename + '.zip');
    console.log('=> Writing packaged zip');
    fs.writeFile(zipfile, buffer, function(err) {
      if (err) {
        throw err;
      }
      console.log('Packaged zip created: ' + zipfile);
    });
  });
};

Lambda.prototype.deploy = function (program) {
  var _this = this;
  var regions = program.region.split(',');
  _this._archive(program, function (err, buffer) {
    if (err) {
      throw err;
    }

    console.log('=> Reading zip file to memory');
    var params = _this._params(program, buffer);

    async.map(regions, function (region, cb) {
      console.log('=> Uploading zip file to AWS Lambda ' + region + ' with parameters:');
      console.log(params);

      var aws_security = {
        accessKeyId: program.accessKey,
        secretAccessKey: program.secretKey,
        region: region
      };

      if (program.sessionToken){
        aws_security.sessionToken = program.sessionToken;
      }

      aws.config.update(aws_security);

      var lambda = new aws.Lambda({
        apiVersion: '2015-03-31'
      });

      return lambda.getFunction({
        'FunctionName': params.FunctionName
      }, function(err) {
        if(err) {
          return _this._uploadNew(lambda, params, cb);
        }

        return _this._uploadExisting(lambda, params, cb);
      });
    }, function (err, results) {
      if (err) {
        throw err;
      } else {
        console.log('=> Zip file(s) done uploading. Results follow: ');
        console.log(results);
      }
    });
  });
};

module.exports = new Lambda();
<commit_msg>Hotfix: excludes (#91)<commit_after>'use strict';

var aws = require('aws-sdk');
var exec = require('child_process').exec;
var fs = require('fs');
var os = require('os');
var packageJson = require('./../package.json');
var path = require('path');
var async = require('async');
var zip = new require('node-zip')();
var wrench = require('wrench');
var dotenv = require('dotenv');

var Lambda = function () {
  this.version = packageJson.version;

  return this;
};

Lambda.prototype._createSampleFile = function (file, newFileName) {
  var exampleFile = process.cwd() + '/' + (file || newFileName);
  var boilerplateFile = __dirname + '/' + file + '.example';

  if (!fs.existsSync(exampleFile)) {
    fs.writeFileSync(exampleFile, fs.readFileSync(boilerplateFile));
    console.log(exampleFile + ' file successfully created');
  }
};

Lambda.prototype.setup = function () {
  console.log('Running setup.');
  this._createSampleFile('.env');
  this._createSampleFile('event.json');
  this._createSampleFile('deploy.env');
  this._createSampleFile('context.json');
  console.log('Setup done. Edit the .env, deploy.env, context.json and event.json files as needed.');
};

Lambda.prototype.run = function (program) {
  this._createSampleFile('event.json', program.eventFile);
  var splitHandler = program.handler.split('.');
  var filename = splitHandler[0] + '.js';
  var handlername = splitHandler[1];

  var handler = require(process.cwd() + '/' + filename)[handlername];
  var event = require(process.cwd() + '/' + program.eventFile);
  var context = require(process.cwd() + '/' + program.contextFile);

  this._runHandler(handler, event, program.runtime, context);
};

Lambda.prototype._runHandler = function (handler, event, runtime, context) {

  var callback = function (err, result) {
    if (err) {
      console.log('Error: ' + err);
      process.exit(-1);
    }
    else {
      console.log('Success:');
      if (result) {
        console.log(JSON.stringify(result));
      }
      process.exit(0);
    }
  };

  var isNode43 = (runtime === "nodejs4.3");
  context.succeed = function (result) {
    if (isNode43) {
      console.log('context.succeed() is deprecated with Node.js 4.3 runtime');
    }
    callback(null, result);
  };
  context.fail = function (error) {
    if (isNode43) {
      console.log('context.fail() is deprecated with Node.js 4.3 runtime');
    }
    callback(error);
  };
  context.done = function () {
    if (isNode43) {
      console.log('context.done() is deprecated with Node.js 4.3 runtime');
    }
    callback();
  };

  switch(runtime) {
    case "nodejs":
      handler(event, context);
      break;
    case "nodejs4.3":
      handler(event, context, callback);
      break;
    default:
      console.error("Runtime [" + runtime + "] is not supported.");
  }

};

Lambda.prototype._params = function (program, buffer) {
  var params = {
    FunctionName: program.functionName + (program.environment ? '-' + program.environment : ''),
    Code: {
      ZipFile: buffer
    },
    Handler: program.handler,
    Role: program.role,
    Runtime: program.runtime,
    Description: program.description,
    MemorySize: program.memorySize,
    Timeout: program.timeout,
    Publish: program.publish,
    VpcConfig: {}
  };
  if (program.version) {
    params.FunctionName += ('-' + program.version);
  }
  if (program.vpcSubnets && program.vpcSecurityGroups) {
    params.VpcConfig = {
      'SubnetIds': program.vpcSubnets.split(','),
      'SecurityGroupIds': program.vpcSecurityGroups.split(',')
    };
  }

  return params;
};

/**
 * @deprecated
 */
Lambda.prototype._zipfileTmpPath = function (program) {
  var ms_since_epoch = +new Date();
  var filename = program.functionName + '-' + ms_since_epoch + '.zip';
  var zipfile = path.join(os.tmpDir(), filename);

  return zipfile;
};

Lambda.prototype._rsync = function (program, codeDirectory, callback) {
  var excludes = ['.git*', '*.swp', '.editorconfig', 'deploy.env', '*.log', 'build/'],
      excludeGlobs = [];
  if (program.excludeGlobs) {
    excludeGlobs = program.excludeGlobs.split(' ');
  }
  var excludeArgs = excludeGlobs.concat(excludes).map(function(exclude) {
    return '--exclude=' + exclude;
  }).join(' ');

  exec('mkdir -p ' + codeDirectory, function(err) {
    if (err) {
      return callback(err);
    }

    exec('rsync -r ' + excludeArgs + ' . ' + codeDirectory, function (err) {
      if (err) {
        return callback(err);
      }

      return callback(null, true);
    });
  });
};

Lambda.prototype._npmInstall = function (program, codeDirectory, callback) {
  exec('npm install --production --prefix ' + codeDirectory, function (err) {
    if (err) {
      return callback(err);
    }

    return callback(null, true);
  });
};

Lambda.prototype._postInstallScript = function (codeDirectory, callback) {
  var script_filename = 'post_install.sh';
  var cmd = './'+script_filename;

  var filePath = [codeDirectory, script_filename].join('/');

  fs.exists(filePath, function(exists) {
    if (exists) {
      console.log('=> Running post install script '+script_filename);
      exec(cmd, { cwd: codeDirectory,maxBuffer: 50 * 1024 * 1024 }, function(error, stdout, stderr){

        if (error) callback(error +" stdout: " + stdout + "stderr"+stderr);
        else {
          console.log("\t\t"+stdout);
          callback(null);
        }
      });

    } else {
      callback(null);
    }
  });

};

Lambda.prototype._zip = function (program, codeDirectory, callback) {

  var options = {
    type: 'nodebuffer',
    compression: 'DEFLATE'
  };

  console.log('=> Zipping repo. This might take up to 30 seconds');
  var files = wrench.readdirSyncRecursive(codeDirectory);
  files.forEach(function (file) {
    var filePath = [codeDirectory, file].join('/');
    var isFile = fs.lstatSync(filePath).isFile();
    if (isFile) {
      var content = fs.readFileSync(filePath);
      zip.file(file, content);
    }
  });

  var data = zip.generate(options);

  return callback(null, data);
};

Lambda.prototype._nativeZip = function (program, codeDirectory, callback) {
  var zipfile = this._zipfileTmpPath(program),
    cmd = 'zip -r ' + zipfile + ' .';

  exec(cmd, {
    cwd: codeDirectory,
    maxBuffer: 50 * 1024 * 1024
  }, function (err) {
    if (err !== null) {
      return callback(err, null);
    }

    var data = fs.readFileSync(zipfile);
    callback(null, data);
  });
};

Lambda.prototype._codeDirectory = function (program) {
  var epoch_time = +new Date();

  return os.tmpDir() + '/' + program.functionName + '-' + epoch_time;
};

Lambda.prototype._cleanDirectory = function (codeDirectory, callback) {
  exec('rm -rf ' + codeDirectory, function (err) {
    if (err) {
      throw err;
    }

    fs.mkdir(codeDirectory, function(err) {
      if (err) {
        throw err;
      }

      return callback(null, true);
    });
  });
};

Lambda.prototype._setEnvironmentVars = function (program, codeDirectory) {
  console.log('=> Setting "environment variables" for Lambda from %s', program.configFile);
  // Which file is the handler?
  var handlerFileName = codeDirectory + '/' + program.handler.split('.').shift() + '.js';
  var contents = fs.readFileSync(handlerFileName);

  var configValues = fs.readFileSync(program.configFile);
  var prefix = '////////////////////////////////////\n// "Environment Variables"\n';
  var config = dotenv.parse(configValues);
  var contentStr = contents.toString();

  for (var k in config) {
    if (!config.hasOwnProperty(k)) {
      continue;
    }

    // Use JSON.stringify to ensure that it's valid code.
    prefix += 'process.env["' + k + '"]=' + JSON.stringify(config[k]) + ';\n';
  }
  prefix += '////////////////////////////////////\n\n';

  // If the first line of the file is 'use strict', append after
  if (contentStr.trim().indexOf('use strict') === 1) {
    contentStr = contentStr.replace(/([`'"]use strict[`'"][;]?)/, '$1\n' + prefix);
  } else {
    contentStr = prefix + contentStr;
  }

  fs.writeFileSync(handlerFileName, contentStr);
};

Lambda.prototype._uploadExisting = function(lambda, params, cb) {
  return lambda.updateFunctionCode({
    'FunctionName': params.FunctionName,
    'ZipFile': params.Code.ZipFile,
    'Publish': params.publish
  }, function(err, data) {
    if(err) {
      return cb(err, data);
    }

    return lambda.updateFunctionConfiguration({
      'FunctionName': params.FunctionName,
      'Description': params.Description,
      'Handler': params.Handler,
      'MemorySize': params.MemorySize,
      'Role': params.Role,
      'Timeout': params.Timeout,
      'VpcConfig': params.VpcConfig
    }, function(err, data) {
      return cb(err, data);
    });
  });
};

Lambda.prototype._uploadNew = function(lambda, params, cb) {
  return lambda.createFunction(params, function(err, data) {
    return cb(err, data);
  });
};

Lambda.prototype._archive = function (program, archive_callback) {
  this._createSampleFile('.env');

  // Warn if not building on 64-bit linux
  var arch = process.platform + '.' + process.arch;
  if (arch !== 'linux.x64') {
    console.warn('Warning!!! You are building on a platform that is not 64-bit Linux (%s). ' +
      'If any of your Node dependencies include C-extensions, they may not work as expected in the ' +
      'Lambda environment.\n\n', arch);
  }

  var _this = this;
  var codeDirectory = _this._codeDirectory(program);

  _this._cleanDirectory(codeDirectory, function(err) {
    if (err) {
      return archive_callback(err);
    }
    console.log('=> Moving files to temporary directory');
    // Move files to tmp folder
    _this._rsync(program, codeDirectory, function (err) {
      if (err) {
        return archive_callback(err);
      }
      console.log('=> Running npm install --production');
      _this._npmInstall(program, codeDirectory, function (err) {
        if (err) {
          return archive_callback(err);
        }

        _this._postInstallScript(codeDirectory, function (err) {
          if (err) {
            return archive_callback(err);
          }

          // Add custom environment variables if program.configFile is defined
          if (program.configFile) {
            _this._setEnvironmentVars(program, codeDirectory);
          }
          console.log('=> Zipping deployment package');

          var archive = process.platform !== 'win32' ? _this._nativeZip : _this._zip;
          archive = archive.bind(_this);

          archive(program, codeDirectory, archive_callback);
        });
      });
    });
  });
};

Lambda.prototype.package = function (program) {
  var _this = this;
  if (!program.packageDirectory) {
    throw 'packageDirectory not specified!';
  } else {
    try {
      var isDir = fs.lstatSync(program.packageDirectory).isDirectory();

      if (!isDir) {
        throw program.packageDirectory + ' is not a directory!';
      }
    } catch(err) {
      if (err.code === 'ENOENT') {
        console.log('=> Creating package directory');
        fs.mkdirSync(program.packageDirectory);
      } else {
        throw err;
      }
    }
  }

  _this._archive(program, function (err, buffer) {
    if (err) {
      throw err;
    }
    var basename = program.functionName + (program.environment ? '-' + program.environment : '');
    var zipfile = path.join(program.packageDirectory, basename + '.zip');
    console.log('=> Writing packaged zip');
    fs.writeFile(zipfile, buffer, function(err) {
      if (err) {
        throw err;
      }
      console.log('Packaged zip created: ' + zipfile);
    });
  });
};

Lambda.prototype.deploy = function (program) {
  var _this = this;
  var regions = program.region.split(',');
  _this._archive(program, function (err, buffer) {
    if (err) {
      throw err;
    }

    console.log('=> Reading zip file to memory');
    var params = _this._params(program, buffer);

    async.map(regions, function (region, cb) {
      console.log('=> Uploading zip file to AWS Lambda ' + region + ' with parameters:');
      console.log(params);

      var aws_security = {
        accessKeyId: program.accessKey,
        secretAccessKey: program.secretKey,
        region: region
      };

      if (program.sessionToken){
        aws_security.sessionToken = program.sessionToken;
      }

      aws.config.update(aws_security);

      var lambda = new aws.Lambda({
        apiVersion: '2015-03-31'
      });

      return lambda.getFunction({
        'FunctionName': params.FunctionName
      }, function(err) {
        if(err) {
          return _this._uploadNew(lambda, params, cb);
        }

        return _this._uploadExisting(lambda, params, cb);
      });
    }, function (err, results) {
      if (err) {
        throw err;
      } else {
        console.log('=> Zip file(s) done uploading. Results follow: ');
        console.log(results);
      }
    });
  });
};

module.exports = new Lambda();
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 * Copyright (c) 2016 GochoMugo <mugo@forfuture.co.ke>
 * Copyright (c) 2016 Forfuture, LLC < we@forfuture.co.ke>
 *
 * Program's main entry point
 */

exports = module.exports = main;

// built-in modules
const EventEmitter = require('events');
const fs = require('fs');
const path = require('path');

// npm-installed modules
const _ = require('lodash');
const walker = require('walker');
const out = require('cli-output');

// own modules
const defaults = require('./defaults');
const stages = require('./stages');
const parallel = require('./parallel');

function main(options) {
    // our global variables
    var globals = {
        emitter: new EventEmitter(),
        pendingRuns: 0,
        doneWalking: false,
        options: {},
    };

    // if a reporter has been provided, pass the emitter to it
    if (_.isFunction(options.reporter)) options.reporter(globals.emitter);

    // load configuration from the respective '.ftpush.toml'
    var configPath = options.configPath || path.join(process.cwd(), defaults.configfileName);
    var profile = options.profile || defaults.profile;
    var allConfig = {};
    try {
        allConfig = require(configPath);
        globals.emitter.emit('Info', `using configuration file at '${configPath}'`);
    } catch(requireErr) {
        // continue if config file is missing. Just log that.
        if (requireErr.message.indexOf('Cannot find module') !== -1) {
            globals.emitter.emit('Info', 'Configuration file is missing. Continuing...');
            requireErr = null;
        }
        if (requireErr) {
            debug(`error loading configuration file: ${requireErr}`);
            process.nextTick(function() {
                globals.emitter.emit('ConfigError', requireErr);
            });
            return globals.emitter;
        }
    }
    const config = allConfig[profile] || {};

    // Load all options, in order of increasing precedence:
    // defaults, options from config file, options from command-line args
    globals.options = _.defaultsDeep({}, options, config, defaults);

    // ensure sourceDir is absolute
    globals.options.sourceDir = path.isAbsolute(globals.options.sourceDir) ?
        globals.options.sourceDir :
        path.join(process.cwd(), globals.options.sourceDir);

    // printing the configurations
    globals.emitter.emit('Info', 'Printing configuration values being used:');
    const pass = globals.options.ftp.pass;
    globals.emitter.emit('Config', _.defaultsDeep({
        ftp: {
            // we do NOT display the password, as it may leak through logs
            pass: pass ? Array(pass.length + 1).join('*') : null,
        },
    }, globals.options));

    // we require a FTP host
    if (!globals.options.ftp.host) {
        debug(`FTP host missing`);
        globals.emitter.emit('ConfigError', new Error('FTP host missing'));
        return globals.emitter;
    }

    // create a new handler for parallel runs
    globals.parallel = new parallel.Handler(globals, function(ftp, dirpath, next) {
        return stages.run(globals, { ftp, dirpath }, function(err) {
            globals.pendingRuns--;
            globals.emitter.emit('DirDone', err, dirpath);

            // if we are stop on error, we forcibly exit
            if (globals.options.stopOnError && err) {
                finish(true);
                return;
            }

            return next();
        });
    }, finish);

    // walking through the source directory
    walker(globals.options.sourceDir)
        .filterDir(function(dirpath) {
            var basename = path.basename(dirpath);
            // return false, to skip
            return globals.options.ignoreDirs.indexOf(basename) === -1;
        })
        .on('dir', function(dirpath) {
            globals.pendingRuns++;
            dirpath = path.relative(globals.options.sourceDir, dirpath) || ".";
            globals.emitter.emit('DirInfo', dirpath);
            globals.parallel.enqueue(dirpath);
        }).on('error', function(err) {
            return globals.emitter.emit('WalkerError', err);
        }).on('end', function() {
            globals.doneWalking = true;
            return finish();
        });

    // check to see if we are done
    function finish(force) {
        if (!force && (globals.doneWalking === false || globals.pendingRuns !== 0)) {
            return;
        }
        // workaround: See issue #6
        return globals.parallel.destroyFtps(function(destroyErr) {
            return globals.emitter.emit('Exit', destroyErr);
        });
    }

    // return the emitter
    return globals.emitter;
}
<commit_msg>[main] Remove old, unnecessary LOC<commit_after>/**
 * The MIT License (MIT)
 * Copyright (c) 2016 GochoMugo <mugo@forfuture.co.ke>
 * Copyright (c) 2016 Forfuture, LLC < we@forfuture.co.ke>
 *
 * Program's main entry point
 */

exports = module.exports = main;

// built-in modules
const EventEmitter = require('events');
const fs = require('fs');
const path = require('path');

// npm-installed modules
const _ = require('lodash');
const walker = require('walker');
const out = require('cli-output');

// own modules
const defaults = require('./defaults');
const stages = require('./stages');
const parallel = require('./parallel');

function main(options) {
    // our global variables
    var globals = {
        emitter: new EventEmitter(),
        pendingRuns: 0,
        doneWalking: false,
        options: {},
    };

    // if a reporter has been provided, pass the emitter to it
    if (_.isFunction(options.reporter)) options.reporter(globals.emitter);

    // load configuration from the respective '.ftpush.toml'
    var configPath = options.configPath || path.join(process.cwd(), defaults.configfileName);
    var profile = options.profile || defaults.profile;
    var allConfig = {};
    try {
        allConfig = require(configPath);
        globals.emitter.emit('Info', `using configuration file at '${configPath}'`);
    } catch(requireErr) {
        // continue if config file is missing. Just log that.
        if (requireErr.message.indexOf('Cannot find module') !== -1) {
            globals.emitter.emit('Info', 'Configuration file is missing. Continuing...');
            requireErr = null;
        }
        if (requireErr) {
            process.nextTick(function() {
                globals.emitter.emit('ConfigError', requireErr);
            });
            return globals.emitter;
        }
    }
    const config = allConfig[profile] || {};

    // Load all options, in order of increasing precedence:
    // defaults, options from config file, options from command-line args
    globals.options = _.defaultsDeep({}, options, config, defaults);

    // ensure sourceDir is absolute
    globals.options.sourceDir = path.isAbsolute(globals.options.sourceDir) ?
        globals.options.sourceDir :
        path.join(process.cwd(), globals.options.sourceDir);

    // printing the configurations
    globals.emitter.emit('Info', 'Printing configuration values being used:');
    const pass = globals.options.ftp.pass;
    globals.emitter.emit('Config', _.defaultsDeep({
        ftp: {
            // we do NOT display the password, as it may leak through logs
            pass: pass ? Array(pass.length + 1).join('*') : null,
        },
    }, globals.options));

    // we require a FTP host
    if (!globals.options.ftp.host) {
        globals.emitter.emit('ConfigError', new Error('FTP host missing'));
        return globals.emitter;
    }

    // create a new handler for parallel runs
    globals.parallel = new parallel.Handler(globals, function(ftp, dirpath, next) {
        return stages.run(globals, { ftp, dirpath }, function(err) {
            globals.pendingRuns--;
            globals.emitter.emit('DirDone', err, dirpath);

            // if we are stop on error, we forcibly exit
            if (globals.options.stopOnError && err) {
                finish(true);
                return;
            }

            return next();
        });
    }, finish);

    // walking through the source directory
    walker(globals.options.sourceDir)
        .filterDir(function(dirpath) {
            var basename = path.basename(dirpath);
            // return false, to skip
            return globals.options.ignoreDirs.indexOf(basename) === -1;
        })
        .on('dir', function(dirpath) {
            globals.pendingRuns++;
            dirpath = path.relative(globals.options.sourceDir, dirpath) || ".";
            globals.emitter.emit('DirInfo', dirpath);
            globals.parallel.enqueue(dirpath);
        }).on('error', function(err) {
            return globals.emitter.emit('WalkerError', err);
        }).on('end', function() {
            globals.doneWalking = true;
            return finish();
        });

    // check to see if we are done
    function finish(force) {
        if (!force && (globals.doneWalking === false || globals.pendingRuns !== 0)) {
            return;
        }
        // workaround: See issue #6
        return globals.parallel.destroyFtps(function(destroyErr) {
            return globals.emitter.emit('Exit', destroyErr);
        });
    }

    // return the emitter
    return globals.emitter;
}
<|endoftext|>


<commit_before>var data    = require("sdk/self").data;
var pageMod = require("sdk/page-mod");

pageMod.PageMod({
  include: "*",
  contentScriptWhen: 'end',
  contentScriptFile: [data.url('jquery-1.10.2.min.js'),
                      data.url('simp-trad.js'),
                      data.url('content_script.js')],
  contentStyleFile: [data.url('styles.css')]
});
<commit_msg>lib/main.js, add exclude moedict sites<commit_after>var data    = require("sdk/self").data;
var pageMod = require("sdk/page-mod");

pageMod.PageMod({
  include: "*",
  contentScriptWhen: 'end',
  contentScriptFile: [data.url('jquery-1.10.2.min.js'),
                      data.url('simp-trad.js'),
                      data.url('content_script.js')],
  contentStyleFile: [data.url('styles.css')],
  include: {
      test: function (url) {
        result = true; //include

        // exclude
        if (url.match(/moedict\.org/)) {
          result = false;
        }
        if (url.match(/moedict\.tw/)) {
          result = false;
        }

        return result;
      },
      exec: function (url) {
        return this.test(url) ? [url] : null;
      }
    }
});
<|endoftext|>


<commit_before>
var http = require('http');
var angularcontext = require('angularcontext');
var ngoverrides = require('./ngoverrides.js');

function sendError(error, response) {
    console.error(error.stack);
    response.writeHead(
        500,
        {
            'Content-Type': 'text/plain'
        }
    );
    response.end(
        error.stack
    );
}

function makeRequestListener(template, scripts, modules) {
    return function (request, response) {
        var context = angularcontext.Context();
        context.runFiles(
            scripts,
            function (success, error) {
                if (error) {
                    sendError(error, response);
                    context.dispose();
                    return;
                }

                ngoverrides.registerModule(context);

                handleRequest(template, context, modules, request, response);
            }
        );
    };
}

function handleRequest(template, context, modules, request, response) {

    try {
        var modules = context.getAngular().copy(modules);
        var element = context.element(template);
        modules.push(
            function ($provide) {
                $provide.value('$rootElement', element);
            }
        );
        modules.push('angularjs-server');

        var injector = context.injector(modules);
        var reqContext = injector.get('serverRequestContext');
        reqContext.setRequest(request);

        var $compile = injector.get('$compile');
        var $rootScope = injector.get('$rootScope');
        var $httpBackend = injector.get('$httpBackend');

        var link = $compile(element);
        link($rootScope);

        var onceRouteKnown = function (route) {

            if (reqContext.getRedirectTo()) {
                // The path changed while we were rendering, so emit a redirect.
                // FIXME: Find some way to do this without actually doing the work to render
                // the route. Probably will need to do route resolution manually, then.
                response.writeHead(
                    302,
                    {
                        Location: reqContext.getRedirectTo()
                    }
                );
                response.end(reqContext.getRedirectTo());
                // still need to clean up the context once everything's settled.
                $httpBackend.notifyWhenNoOpenRequests(
                    function () {
                        context.dispose();
                    }
                );
                return;
            }

            // Stash any controller locals we pre-resolved so we can return them
            // to the client as a sort of cache so the browser can avoid additional round-trips.
            var preResolved = {};
            if (route.$$route && route.$$route.resolve) {
                for (var k in route.$$route.resolve) {
                    if (route.locals[k] !== undefined) {
                        preResolved[k] = route.locals[k];
                    }
                }
            }

            $httpBackend.notifyWhenNoOpenRequests(
                function () {
                    $rootScope.$digest();

                    response.writeHead(200);
                    response.end(element[0].outerHTML);
                    context.dispose();
                }
            );
        };

        $rootScope.$on(
            '$routeChangeSuccess',
            function (evt, newRoute, oldRoute) {
                onceRouteKnown(newRoute);
            }
        );

        // return a real 404 if we fail to change routes
        $rootScope.$on(
            '$routeChangeError',
            function (evt, newRoute, oldRoute, rejection) {
                // TODO: Come up with a way to let the app customize the 404 page.
                response.writeHead(404);
                response.end('Not Found');
            }
        );

        // Kick off the route system by broadcasting our URL.
        $rootScope.$broadcast(
            '$locationChangeSuccess',
            reqContext.location.absUrl(),
            undefined
        );
        $rootScope.$digest();

    }
    catch (err) {
        context.dispose();
        sendError(err, response);
    }
}

function createServer(template, scripts, modules) {
    var listener = makeRequestListener(template, scripts, modules);
    return http.createServer(listener);
}

exports.makeRequestListener = makeRequestListener;
exports.createServer = createServer;

<commit_msg>Allow the response to be more than one element.<commit_after>
var http = require('http');
var angularcontext = require('angularcontext');
var ngoverrides = require('./ngoverrides.js');

function sendError(error, response) {
    console.error(error.stack);
    response.writeHead(
        500,
        {
            'Content-Type': 'text/plain'
        }
    );
    response.end(
        error.stack
    );
}

function makeRequestListener(template, scripts, modules) {
    return function (request, response) {
        var context = angularcontext.Context();
        context.runFiles(
            scripts,
            function (success, error) {
                if (error) {
                    sendError(error, response);
                    context.dispose();
                    return;
                }

                ngoverrides.registerModule(context);

                handleRequest(template, context, modules, request, response);
            }
        );
    };
}

function handleRequest(template, context, modules, request, response) {

    try {
        var modules = context.getAngular().copy(modules);
        var element = context.element(template);
        modules.push(
            function ($provide) {
                $provide.value('$rootElement', element);
            }
        );
        modules.push('angularjs-server');

        var injector = context.injector(modules);
        var reqContext = injector.get('serverRequestContext');
        reqContext.setRequest(request);

        var $compile = injector.get('$compile');
        var $rootScope = injector.get('$rootScope');
        var $httpBackend = injector.get('$httpBackend');

        var link = $compile(element);
        link($rootScope);

        var onceRouteKnown = function (route) {

            if (reqContext.getRedirectTo()) {
                // The path changed while we were rendering, so emit a redirect.
                // FIXME: Find some way to do this without actually doing the work to render
                // the route. Probably will need to do route resolution manually, then.
                response.writeHead(
                    302,
                    {
                        Location: reqContext.getRedirectTo()
                    }
                );
                response.end(reqContext.getRedirectTo());
                // still need to clean up the context once everything's settled.
                $httpBackend.notifyWhenNoOpenRequests(
                    function () {
                        context.dispose();
                    }
                );
                return;
            }

            // Stash any controller locals we pre-resolved so we can return them
            // to the client as a sort of cache so the browser can avoid additional round-trips.
            var preResolved = {};
            if (route.$$route && route.$$route.resolve) {
                for (var k in route.$$route.resolve) {
                    if (route.locals[k] !== undefined) {
                        preResolved[k] = route.locals[k];
                    }
                }
            }

            $httpBackend.notifyWhenNoOpenRequests(
                function () {
                    $rootScope.$digest();

                    var container = context.element('

');
                    container.append(element);

                    response.writeHead(200);
                    response.end(container.html());
                    context.dispose();
                }
            );
        };

        $rootScope.$on(
            '$routeChangeSuccess',
            function (evt, newRoute, oldRoute) {
                onceRouteKnown(newRoute);
            }
        );

        // return a real 404 if we fail to change routes
        $rootScope.$on(
            '$routeChangeError',
            function (evt, newRoute, oldRoute, rejection) {
                // TODO: Come up with a way to let the app customize the 404 page.
                response.writeHead(404);
                response.end('Not Found');
            }
        );

        // Kick off the route system by broadcasting our URL.
        $rootScope.$broadcast(
            '$locationChangeSuccess',
            reqContext.location.absUrl(),
            undefined
        );
        $rootScope.$digest();

    }
    catch (err) {
        context.dispose();
        sendError(err, response);
    }
}

function createServer(template, scripts, modules) {
    var listener = makeRequestListener(template, scripts, modules);
    return http.createServer(listener);
}

exports.makeRequestListener = makeRequestListener;
exports.createServer = createServer;

<|endoftext|>


<commit_before>
/*

  Server.js

*/

module.exports = function() {

  var PORT     = 27182,
      path     = require("path"),
      express  = require("express"),
      server   = express(),
      cookies  = require("cookie-parser"),
      sessions = require("express-session"),
      config   = require("./config")(),
      compiled = require("./compiled"),
      database = require("./database"),
      statics  = require("./statics"),
      views    = require("./views");

  // Set up sensible logging defaults, etc.
  server.use(cookies());
  server.use(sessions({ secret : "password123", resave : false, saveUninitialized : true }));

  // Get JSON data (for database and view-rendering)
  global.db = database();

  // Middleware helper
  function iterateMiddleware(arr, middleware) {
    arr.forEach(function(options) { server.use(middleware(options)); });
  }

  // Add routers
  server.use(require("./views.js")());

  // Add compiled
  iterateMiddleware(config.styles, compiled);
  iterateMiddleware(config.scripts, compiled);

  // Add statics
  iterateMiddleware(config.fonts, statics);
  iterateMiddleware(config.images, statics);
  iterateMiddleware(config.statics, statics);

  // We must add the data last or it overwrites other paths
  server.use(require("./api")());

  // Listen (we will proxy with browser sync)
  server.listen(PORT);

}
<commit_msg>Main: switches set up to globals<commit_after>
/*

  Server.js

*/

module.exports = function() {

  var PORT     = 27182,
      path     = require("path"),
      express  = require("express"),
      server   = express(),
      cookies  = require("cookie-parser"),
      sessions = require("express-session"),
      compiled = require("./compiled"),
      statics  = require("./statics"),
      views    = require("./views");

  // Set up sensible logging defaults, etc.
  server.use(cookies());
  server.use(sessions({ secret : "password123", resave : false, saveUninitialized : true }));

  // Middleware helper
  function iterateMiddleware(arr, middleware) {
    arr.forEach(function(options) { server.use(middleware(options)); });
  }

  // Add routers
  server.use(require("./views.js")());

  // Add compiled
  iterateMiddleware(global.config.styles, compiled);
  iterateMiddleware(global.config.scripts, compiled);

  // Add statics
  iterateMiddleware(global.config.fonts, statics);
  iterateMiddleware(global.config.images, statics);
  iterateMiddleware(global.config.statics, statics);

  // We must add the data last or it overwrites other paths
  server.use(require("./api")());

  // Listen (we will proxy with browser sync)
  server.listen(PORT);

}
<|endoftext|>


<commit_before>/**
 * @file
 * @copyright (c) 2013 Stephan Brenner
 * @license   This project is released under the MIT License.
 *
 * This file implements a Node.js module for initiating socket.io connections
 * through a proxy server.
 */

(function(){
    var http = require('http');
    var https = require('https');
    var url = require('url');
    var io = require('socket.io-client');

    var tunnelPort = 61423;
    var tunnelServer;
    var initialized = false;

    exports.connect = function(destinationUrl, options) {
        var destination = url.parse(destinationUrl);
        if (!destination.port) {
            destination.port = destination.protocol === 'https:' ? 443 : 80;
        }

        if (!initialized) exports.init();

        if (typeof tunnelServer === 'undefined') return io.connect(destinationUrl, options);   // Direct connection

        options = options || {};
        options['force new connection'] = true;   // Allows one tunnel server to handle multiple destinations

        return io.connect('http://localhost:' + tunnelPort + '/' +
            '?protocol=' + destination.protocol.replace(':', '')  +
            '&hostname=' + destination.hostname +
            '&port=' + destination.port, options);
    };

    exports.init = function(proxyUrl) {
        initialized = true;

        if (typeof tunnelServer !== 'undefined') {
            tunnelServer.close();
            tunnelServer = undefined;
        }

        if (typeof proxyUrl === 'undefined') {
            if (process.env.http_proxy) {
                proxyUrl = process.env.http_proxy;
            } else {
                console.log('Direct connection (no proxy defined)');
                return;
            }
        }

        var proxy = url.parse(proxyUrl, true);

        tunnelServer = http.createServer(function (request, response) {
            var requestUrl = url.parse(request.url, true);
            var hostname = requestUrl.query.hostname;
            var port = requestUrl.query.port;

            var options = {
                hostname: typeof proxy !== 'undefined' ? proxy.hostname : hostname,
                port: typeof proxy !== 'undefined' ? proxy.port : port,
                path: requestUrl.pathname + '?t=' + requestUrl.query.t,
                method: request.method,
                headers: request.headers
            };
            options['headers']['Host'] = hostname + ':' + port；

            var proxy_request = requestUrl.query.protocol === 'http'
                ? http.request(options)
                : https.request(options);

            proxy_request.addListener('response', function (proxy_response) {
                proxy_response.addListener('data', function (chunk) { response.write(chunk, 'binary'); });
                proxy_response.addListener('end', function () { response.end(); });
                response.writeHead(proxy_response.statusCode, proxy_response.headers);
            });

            request.addListener('data', function (chunk) { proxy_request.write(chunk, 'binary'); });
            request.addListener('end', function () { proxy_request.end(); });
        });

        tunnelServer.listen(tunnelPort);
        console.log('Proxy: ' + proxyUrl);
    };
})();
<commit_msg>Corrected line ending<commit_after>/**
 * @file
 * @copyright (c) 2013 Stephan Brenner
 * @license   This project is released under the MIT License.
 *
 * This file implements a Node.js module for initiating socket.io connections
 * through a proxy server.
 */

(function(){
    var http = require('http');
    var https = require('https');
    var url = require('url');
    var io = require('socket.io-client');

    var tunnelPort = 61423;
    var tunnelServer;
    var initialized = false;

    exports.connect = function(destinationUrl, options) {
        var destination = url.parse(destinationUrl);
        if (!destination.port) {
            destination.port = destination.protocol === 'https:' ? 443 : 80;
        }

        if (!initialized) exports.init();

        if (typeof tunnelServer === 'undefined') return io.connect(destinationUrl, options);   // Direct connection

        options = options || {};
        options['force new connection'] = true;   // Allows one tunnel server to handle multiple destinations

        return io.connect('http://localhost:' + tunnelPort + '/' +
            '?protocol=' + destination.protocol.replace(':', '')  +
            '&hostname=' + destination.hostname +
            '&port=' + destination.port, options);
    };

    exports.init = function(proxyUrl) {
        initialized = true;

        if (typeof tunnelServer !== 'undefined') {
            tunnelServer.close();
            tunnelServer = undefined;
        }

        if (typeof proxyUrl === 'undefined') {
            if (process.env.http_proxy) {
                proxyUrl = process.env.http_proxy;
            } else {
                console.log('Direct connection (no proxy defined)');
                return;
            }
        }

        var proxy = url.parse(proxyUrl, true);

        tunnelServer = http.createServer(function (request, response) {
            var requestUrl = url.parse(request.url, true);
            var hostname = requestUrl.query.hostname;
            var port = requestUrl.query.port;

            var options = {
                hostname: typeof proxy !== 'undefined' ? proxy.hostname : hostname,
                port: typeof proxy !== 'undefined' ? proxy.port : port,
                path: requestUrl.pathname + '?t=' + requestUrl.query.t,
                method: request.method,
                headers: request.headers
            };
            options['headers']['Host'] = hostname + ':' + port;

            var proxy_request = requestUrl.query.protocol === 'http'
                ? http.request(options)
                : https.request(options);

            proxy_request.addListener('response', function (proxy_response) {
                proxy_response.addListener('data', function (chunk) { response.write(chunk, 'binary'); });
                proxy_response.addListener('end', function () { response.end(); });
                response.writeHead(proxy_response.statusCode, proxy_response.headers);
            });

            request.addListener('data', function (chunk) { proxy_request.write(chunk, 'binary'); });
            request.addListener('end', function () { proxy_request.end(); });
        });

        tunnelServer.listen(tunnelPort);
        console.log('Proxy: ' + proxyUrl);
    };
})();
<|endoftext|>


<commit_before>

function Router($stateProvider, $httpProvider, $locationProvider){
    "ngInject";

    var states = [
        {
            name : 'app',
            url : '/',
            views : {
                'app' : {
                    templateUrl : 'views/app/home/home.html'
                }
            }
        },
        {
            name : 'app.login',
            url : 'login',
            views : {
                'app@' : {
                    templateUrl : 'views/app/login/login.html',
                    controller: 'LoginCtrl',
                    controllerAs: 'login'
                }
            }
        },
        {
            name : 'app.account',
            url : 'account',
            views : {
                'mainContent@app' : {
                    templateUrl : 'views/app/account/account.html',
                    controller : 'AccountCtrl',
                    controllerAs : 'account'
                }
            }
        },
        {
            name : 'app.courses',
            url : 'courses',
            views : {
                'mainContent@app' : {
                    templateUrl: 'views/student/home/home.html',
                    controller: 'Student.HomeCtrl',
                    controllerAs: 'studentHome'
                }
            }
        },
        {
            name : 'app.course',
            url  : 'courses/{courseId}',
            views : {
                'mainContent@app' : {
                    templateUrl : 'views/student/course/home.html',
                    controller : 'Student.Course',
                    controllerAs : 'course'
                }
            },
            resolve : {
                course : ['CourseService','SessionService','$stateParams', function(CourseService, SessionService, $stateParams){
                    return CourseService.getCourse($stateParams.courseId)
                        .then(function(course){
                        SessionService.setCourseUserId(course.courseUserId);
                        return course;
                    }, function(err){
                        return err;
                    });
                }]
            }
        },
        {
            name : 'app.course.assignments',
            url : '/assignments',
            views : {
                'childContent' : {
                    templateUrl : 'views/student/assignments/home.html',
                    controller : 'Student.AssignmentsCtrl',
                    controllerAs : 'courseAssignments'
                }
            }
        },
        {
            name : 'app.course.grades',
            url : '/grades',
            views : {
                'childContent' : {
                    templateUrl : 'views/student/grades/home.html',
                    controller : 'Student.GradesCtrl',
                    controllerAs : 'courseGrades'
                }
            }
        },
        {
            name : 'app.course.assignment',
            url : '/assignments/{moduleId}',
            views : {
                'childContent' : {
                    templateUrl : 'views/student/assignment/home.html',
                    controller : 'Student.AssignmentDetailsCtrl',
                    controllerAs : 'assignmentDetails'
                },
                'assignmentContent@app.course.assignment' : {
                    templateUrl : 'views/student/assignment_details/home.html'
                }
            }
        },
        {
            name : 'app.course.assignment.group',
            url : '/group',
            views : {
                'assignmentContent' : {
                    templateUrl : 'views/student/assignment_create_group/home.html',
                    controller : 'Student.AssignmentGroupCtrl',
                    controllerAs : 'assignmentGroup'

                }
            }
        },
        {
            name :  'app.course.assignment.login',
            url : '/login',
            views : {
                'assignmentContent' : {
                    templateUrl : 'views/student/assignment_group_login/home.html',
                    controller : 'Student.AssignmentLoginCtrl',
                    controllerAs : 'assignmentLogin'
                }
            }
        }

    ]

    states.forEach(function(state) {
        $stateProvider.state(state);
    });

    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';

//    Removing # from the urls
}

module.exports = Router;
<commit_msg>ADD: groupId parameter<commit_after>

function Router($stateProvider, $httpProvider, $locationProvider){
    "ngInject";

    var states = [
        {
            name : 'app',
            url : '/',
            views : {
                'app' : {
                    templateUrl : 'views/app/home/home.html'
                }
            }
        },
        {
            name : 'app.login',
            url : 'login',
            views : {
                'app@' : {
                    templateUrl : 'views/app/login/login.html',
                    controller: 'LoginCtrl',
                    controllerAs: 'login'
                }
            }
        },
        {
            name : 'app.account',
            url : 'account',
            views : {
                'mainContent@app' : {
                    templateUrl : 'views/app/account/account.html',
                    controller : 'AccountCtrl',
                    controllerAs : 'account'
                }
            }
        },
        {
            name : 'app.courses',
            url : 'courses',
            views : {
                'mainContent@app' : {
                    templateUrl: 'views/student/home/home.html',
                    controller: 'Student.HomeCtrl',
                    controllerAs: 'studentHome'
                }
            }
        },
        {
            name : 'app.course',
            url  : 'courses/{courseId}',
            views : {
                'mainContent@app' : {
                    templateUrl : 'views/student/course/home.html',
                    controller : 'Student.Course',
                    controllerAs : 'course'
                }
            },
            resolve : {
                course : ['CourseService','SessionService','$stateParams', function(CourseService, SessionService, $stateParams){
                    return CourseService.getCourse($stateParams.courseId)
                        .then(function(course){
                        SessionService.setCourseUserId(course.courseUserId);
                        return course;
                    }, function(err){
                        return err;
                    });
                }]
            }
        },
        {
            name : 'app.course.assignments',
            url : '/assignments',
            views : {
                'childContent' : {
                    templateUrl : 'views/student/assignments/home.html',
                    controller : 'Student.AssignmentsCtrl',
                    controllerAs : 'courseAssignments'
                }
            }
        },
        {
            name : 'app.course.grades',
            url : '/grades',
            views : {
                'childContent' : {
                    templateUrl : 'views/student/grades/home.html',
                    controller : 'Student.GradesCtrl',
                    controllerAs : 'courseGrades'
                }
            }
        },
        {
            name : 'app.course.assignment',
            url : '/assignments/{moduleId}',
            views : {
                'childContent' : {
                    templateUrl : 'views/student/assignment/home.html',
                    controller : 'Student.AssignmentDetailsCtrl',
                    controllerAs : 'assignmentDetails'
                },
                'assignmentContent@app.course.assignment' : {
                    templateUrl : 'views/student/assignment_details/home.html'
                }
            }
        },
        {
            name : 'app.course.assignment.group',
            url : '/group/{groupId}',
            views : {
                'assignmentContent' : {
                    templateUrl : 'views/student/assignment_create_group/home.html',
                    controller : 'Student.AssignmentGroupCtrl',
                    controllerAs : 'assignmentGroup'

                }
            }
        },
        {
            name :  'app.course.assignment.login',
            url : '/login',
            views : {
                'assignmentContent' : {
                    templateUrl : 'views/student/assignment_group_login/home.html',
                    controller : 'Student.AssignmentLoginCtrl',
                    controllerAs : 'assignmentLogin'
                }
            }
        }

    ]

    states.forEach(function(state) {
        $stateProvider.state(state);
    });

    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';

//    Removing # from the urls
}

module.exports = Router;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2013 André Bargull
 * Alle Rechte vorbehalten / All Rights Reserved.  Use is subject to license terms.
 *
 * <https://github.com/anba/es6draft>
 */

(function OldProxyAPI(global) {
"use strict";

const Object = global.Object,
      Function = global.Function,
      Array = global.Array,
      Proxy = global.Proxy,
      TypeError = global.TypeError;

const Object_create = Object.create,
      Object_assign = Object.assign;

const Function_call = Function.prototype.call.bind(Function.prototype.call);

const iteratorSym = getSym("@@iterator");

function toProxyHandler(handler) {
  var TypeErrorThrower = () => { throw TypeError() };
  /* fundamental traps mapping:
   * getOwnPropertyDescriptor -> getOwnPropertyDescriptor
   * getPropertyDescriptor -> -
   * getOwnPropertyNames -> ownKeys
   * getPropertyNames -> -
   * defineProperty -> defineProperty
   * delete -> deleteProperty
   * fix -> -
   */
  var proxyHandler = {
    getOwnPropertyDescriptor: TypeErrorThrower,
    defineProperty: TypeErrorThrower,
    deleteProperty: TypeErrorThrower,
    ownKeys: TypeErrorThrower,
  };

  // fundamental traps
  if ('getOwnPropertyDescriptor' in handler) {
    proxyHandler['getOwnPropertyDescriptor'] = (_, pk) => handler['getOwnPropertyDescriptor'](pk);
  } else if ('getPropertyDescriptor' in handler) {
    proxyHandler['getOwnPropertyDescriptor'] = (_, pk) => handler['getPropertyDescriptor'](pk);
  }
  if ('getOwnPropertyNames' in handler) {
    proxyHandler['ownKeys'] = () => [...handler['getOwnPropertyNames']()].values()[iteratorSym]();
  }
  if ('defineProperty' in handler) {
    proxyHandler['defineProperty'] = (_, pk, desc) => (handler['defineProperty'](pk, desc), true);
  }
  if ('delete' in handler) {
    proxyHandler['deleteProperty'] = (_, pk) => handler['delete'](pk);
  }

  // derived traps
  if ('has' in handler) {
    proxyHandler['has'] = (_, pk) => handler['has'](pk);
  } else {
    proxyHandler['has'] = (_, pk) => !!handler['getPropertyDescriptor'](pk);
  }
  if ('hasOwn' in handler) {
    proxyHandler['hasOwn'] = (_, pk) => handler['hasOwn'](pk);
  } else {
    proxyHandler['hasOwn'] = (_, pk) => !!handler['getOwnPropertyDescriptor'](pk);
  }
  if ('get' in handler && typeof handler['get'] == 'function') {
    proxyHandler['get'] = (_, pk, receiver) => handler['get'](receiver, pk);
  } else {
    proxyHandler['get'] = (_, pk, receiver) => {
      // XXX: special case for iteration tests
      if (pk === iteratorSym) {
        var desc = handler['getPropertyDescriptor']("iterator");
        if (desc !== undefined && 'value' in desc) {
          // call @@iterator() so we don't end up with a StopIteration based Iterator
          return function() { return desc.value.call(this)[iteratorSym]() };
        }
      }
      var desc = handler['getPropertyDescriptor'](pk);
      if (desc !== undefined && 'value' in desc) {
        return desc.value;
      }
      if (desc !== undefined && desc.get !== undefined) {
        return desc.get.call(receiver);
      }
    };
  }
  if ('set' in handler) {
    proxyHandler['set'] = (_, pk, value, receiver) => handler['set'](receiver, pk, value);
  } else {
    proxyHandler['set'] = (_, pk, value, receiver) => {
      var desc = handler['getOwnPropertyDescriptor'](pk);
      if (!desc) {
        desc = handler['getPropertyDescriptor'](pk);
        if (!desc) {
          desc = {
            writable: true, enumerable: true, configurable: true
          };
        }
      }
      if (('writable' in desc) && desc.writable) {
        handler['defineProperty'](pk, (desc.value = value, desc));
        return true;
      }
      if (!('writable' in desc) && desc.set) {
        desc.set.call(receiver, value);
        return true;
      }
      return false;
    };
  }
  if ('enumerate' in handler) {
    proxyHandler['enumerate'] = () => [...handler['enumerate']()].values()[iteratorSym]();
  } else if ('iterate' in handler) {
    proxyHandler['enumerate'] = () => handler['iterate']()[iteratorSym]();
  } else {
    proxyHandler['enumerate'] = () => handler['getPropertyNames'].filter(
      pk => handler['getPropertyDescriptor'](pk).enumerable
    ).values()[iteratorSym]();
  }
  if ('keys' in handler) {
    proxyHandler['ownKeys'] = () => [...handler['keys']()].values()[iteratorSym]();
  }
  proxyHandler['invoke'] = (_, pk, args, receiver) => Function_call(proxyHandler['get'](_, pk, receiver), receiver, ...args);
  return proxyHandler;
}

Object.defineProperties(Object_assign(Proxy, {
  create(handler, proto = null) {
    if (Object(handler) !== handler) throw TypeError();
    var proxyTarget = Object_create(proto);
    var proxyHandler = Object_assign({
      setPrototypeOf() { throw TypeError() }
    }, toProxyHandler(handler));
    return new Proxy(proxyTarget, proxyHandler);
  },
  createFunction(handler, callTrap, constructTrap = callTrap) {
    if (Object(handler) !== handler) throw TypeError();
    if (typeof callTrap != 'function') throw TypeError();
    if (typeof constructTrap != 'function') throw TypeError();
    var proxyTarget = function(){};
    var proxyHandler = Object_assign({
      setPrototypeOf() { throw TypeError() },
      apply(_, thisValue, args) { return callTrap.apply(thisValue, args) },
      construct(_, args) { return new constructTrap(...args) }
    }, toProxyHandler(handler));
    return new Proxy(proxyTarget, proxyHandler);
  }
}), {
  create: {enumerable: false},
  createFunction: {enumerable: false},
});

})(this);
<commit_msg>Remove use of Array.prototype.values() because it's currently disabled in SpiderMonkey<commit_after>/*
 * Copyright (c) 2012-2013 André Bargull
 * Alle Rechte vorbehalten / All Rights Reserved.  Use is subject to license terms.
 *
 * <https://github.com/anba/es6draft>
 */

(function OldProxyAPI(global) {
"use strict";

const Object = global.Object,
      Function = global.Function,
      Array = global.Array,
      Proxy = global.Proxy,
      TypeError = global.TypeError;

const Object_create = Object.create,
      Object_assign = Object.assign;

const Function_call = Function.prototype.call.bind(Function.prototype.call);

const iteratorSym = getSym("@@iterator");

function toProxyHandler(handler) {
  var TypeErrorThrower = () => { throw TypeError() };
  /* fundamental traps mapping:
   * getOwnPropertyDescriptor -> getOwnPropertyDescriptor
   * getPropertyDescriptor -> -
   * getOwnPropertyNames -> ownKeys
   * getPropertyNames -> -
   * defineProperty -> defineProperty
   * delete -> deleteProperty
   * fix -> -
   */
  var proxyHandler = {
    getOwnPropertyDescriptor: TypeErrorThrower,
    defineProperty: TypeErrorThrower,
    deleteProperty: TypeErrorThrower,
    ownKeys: TypeErrorThrower,
  };

  // fundamental traps
  if ('getOwnPropertyDescriptor' in handler) {
    proxyHandler['getOwnPropertyDescriptor'] = (_, pk) => handler['getOwnPropertyDescriptor'](pk);
  } else if ('getPropertyDescriptor' in handler) {
    proxyHandler['getOwnPropertyDescriptor'] = (_, pk) => handler['getPropertyDescriptor'](pk);
  }
  if ('getOwnPropertyNames' in handler) {
    proxyHandler['ownKeys'] = () => [...handler['getOwnPropertyNames']()][iteratorSym]();
  }
  if ('defineProperty' in handler) {
    proxyHandler['defineProperty'] = (_, pk, desc) => (handler['defineProperty'](pk, desc), true);
  }
  if ('delete' in handler) {
    proxyHandler['deleteProperty'] = (_, pk) => handler['delete'](pk);
  }

  // derived traps
  if ('has' in handler) {
    proxyHandler['has'] = (_, pk) => handler['has'](pk);
  } else {
    proxyHandler['has'] = (_, pk) => !!handler['getPropertyDescriptor'](pk);
  }
  if ('hasOwn' in handler) {
    proxyHandler['hasOwn'] = (_, pk) => handler['hasOwn'](pk);
  } else {
    proxyHandler['hasOwn'] = (_, pk) => !!handler['getOwnPropertyDescriptor'](pk);
  }
  if ('get' in handler && typeof handler['get'] == 'function') {
    proxyHandler['get'] = (_, pk, receiver) => handler['get'](receiver, pk);
  } else {
    proxyHandler['get'] = (_, pk, receiver) => {
      // XXX: special case for iteration tests
      if (pk === iteratorSym) {
        var desc = handler['getPropertyDescriptor']("iterator");
        if (desc !== undefined && 'value' in desc) {
          // call @@iterator() so we don't end up with a StopIteration based Iterator
          return function() { return desc.value.call(this)[iteratorSym]() };
        }
      }
      var desc = handler['getPropertyDescriptor'](pk);
      if (desc !== undefined && 'value' in desc) {
        return desc.value;
      }
      if (desc !== undefined && desc.get !== undefined) {
        return desc.get.call(receiver);
      }
    };
  }
  if ('set' in handler) {
    proxyHandler['set'] = (_, pk, value, receiver) => handler['set'](receiver, pk, value);
  } else {
    proxyHandler['set'] = (_, pk, value, receiver) => {
      var desc = handler['getOwnPropertyDescriptor'](pk);
      if (!desc) {
        desc = handler['getPropertyDescriptor'](pk);
        if (!desc) {
          desc = {
            writable: true, enumerable: true, configurable: true
          };
        }
      }
      if (('writable' in desc) && desc.writable) {
        handler['defineProperty'](pk, (desc.value = value, desc));
        return true;
      }
      if (!('writable' in desc) && desc.set) {
        desc.set.call(receiver, value);
        return true;
      }
      return false;
    };
  }
  if ('enumerate' in handler) {
    proxyHandler['enumerate'] = () => [...handler['enumerate']()][iteratorSym]();
  } else if ('iterate' in handler) {
    proxyHandler['enumerate'] = () => handler['iterate']()[iteratorSym]();
  } else {
    proxyHandler['enumerate'] = () => handler['getPropertyNames'].filter(
      pk => handler['getPropertyDescriptor'](pk).enumerable
    )[iteratorSym]();
  }
  if ('keys' in handler) {
    proxyHandler['ownKeys'] = () => [...handler['keys']()][iteratorSym]();
  }
  proxyHandler['invoke'] = (_, pk, args, receiver) => Function_call(proxyHandler['get'](_, pk, receiver), receiver, ...args);
  return proxyHandler;
}

Object.defineProperties(Object_assign(Proxy, {
  create(handler, proto = null) {
    if (Object(handler) !== handler) throw TypeError();
    var proxyTarget = Object_create(proto);
    var proxyHandler = Object_assign({
      setPrototypeOf() { throw TypeError() }
    }, toProxyHandler(handler));
    return new Proxy(proxyTarget, proxyHandler);
  },
  createFunction(handler, callTrap, constructTrap = callTrap) {
    if (Object(handler) !== handler) throw TypeError();
    if (typeof callTrap != 'function') throw TypeError();
    if (typeof constructTrap != 'function') throw TypeError();
    var proxyTarget = function(){};
    var proxyHandler = Object_assign({
      setPrototypeOf() { throw TypeError() },
      apply(_, thisValue, args) { return callTrap.apply(thisValue, args) },
      construct(_, args) { return new constructTrap(...args) }
    }, toProxyHandler(handler));
    return new Proxy(proxyTarget, proxyHandler);
  }
}), {
  create: {enumerable: false},
  createFunction: {enumerable: false},
});

})(this);
<|endoftext|>