<commit_before>"use strict"

var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var Q = require('q');

var Promise = Q.Promise;

var algo = 'sha1';
var encoding = 'base64'; // 'base64', 'hex' or 'binary'

module.exports = {
    hashElement: createHash/** /,
    hashFolderPromise: hashFolderPromise,
    hashFilePromise: hashFilePromise/**/
}

/**
 * Create a hash over a folder or file, using either promises or error-first-callbacks.
 * The parameter directoryPath is optional. This function may be called
 *  as createHash(filename, folderpath, fn(err, hash) {}), createHash(filename, folderpath)
 *  or as createHash(path, fn(err, hash) {}), createHash(path)
 */
function createHash(name, directoryPath, callback) {
    function isString(str) {
        return (typeof str == 'string' || str instanceof String)
    }

    return Promise(function (resolve, reject, notify) {

        if (!isString(name)) {
            reject(new TypeError('First argument must be a string'));
        }
        if (!isString(directoryPath)) {
            if (typeof directoryPath === 'function') {
                callback = directoryPath;
            }

            directoryPath = path.dirname(name);
            name = path.basename(name);
        }

        resolve(hashElementPromise(name, directoryPath, callback));
    }).nodeify(callback);
}

function hashElementPromise(name, directoryPath) {
    var filepath = path.join(directoryPath, name);
    return Promise(function (resolve, reject, notify) {
        fs.stat(filepath, function (err, stats) {
            if (err) {
                return reject(err);
            }

            if (stats.isDirectory()) {
                resolve(hashFolderPromise(name, directoryPath));
            } else if (stats.isFile()) {
                resolve(hashFilePromise(name, directoryPath));
            } else {
                resolve({ name: name, hash: 'unknown element type' });
            }
        });
    });
}

function hashFolderPromise(foldername, directoryPath) {
    var TAG = 'hashFolderPromise(' + foldername + ', ' + directoryPath + '):';
    var folderPath = path.join(directoryPath, foldername);
    return Promise(function (resolve, reject, notify) {
        console.log(TAG);
        fs.readdir(folderPath, function (err, files) {
            if (err) {
                console.error(TAG, err);
                reject(err);
            }

            console.log(TAG + 'children:', files);

            var children = files.map(function (child) {
                return hashElementPromise(child, folderPath);
            });

            var allChildren = Q.all(children);

            return allChildren.then(function (children) {

                var hash = crypto.createHash(algo);
                hash.write(foldername);
                children.forEach(function (child) {
                    if (child.hash) {
                        hash.write(child.hash);
                    }
                });

                var checksum = hash.digest(encoding);

                resolve({ name: foldername, hash: checksum, children: children });
            });
        });
    });
}

function hashFilePromise(filename, directoryPath) {
    return Promise(function (resolve, reject, notify) {
        try {
            var hash = crypto.createHash(algo);
            hash.write(filename);

            var f = fs.createReadStream(path.join(directoryPath, filename));
            f.pipe(hash, { end: false });

            f.on('end', function () {
                var result = hash.digest(encoding);

                resolve({
                    name: filename,
                    hash: result
                });
            });

        } catch (ex) {
            reject(ex);
        }
    });
}<commit_msg>Remove unnecessary output from module<commit_after>"use strict"

var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var Q = require('q');

var Promise = Q.Promise;

var algo = 'sha1';
var encoding = 'base64'; // 'base64', 'hex' or 'binary'

module.exports = {
    hashElement: createHash/** /,
    hashFolderPromise: hashFolderPromise,
    hashFilePromise: hashFilePromise/**/
}

/**
 * Create a hash over a folder or file, using either promises or error-first-callbacks.
 * The parameter directoryPath is optional. This function may be called
 *  as createHash(filename, folderpath, fn(err, hash) {}), createHash(filename, folderpath)
 *  or as createHash(path, fn(err, hash) {}), createHash(path)
 */
function createHash(name, directoryPath, callback) {
    function isString(str) {
        return (typeof str == 'string' || str instanceof String)
    }

    return Promise(function (resolve, reject, notify) {

        if (!isString(name)) {
            reject(new TypeError('First argument must be a string'));
        }
        if (!isString(directoryPath)) {
            if (typeof directoryPath === 'function') {
                callback = directoryPath;
            }

            directoryPath = path.dirname(name);
            name = path.basename(name);
        }

        resolve(hashElementPromise(name, directoryPath, callback));
    }).nodeify(callback);
}

function hashElementPromise(name, directoryPath) {
    var filepath = path.join(directoryPath, name);
    return Promise(function (resolve, reject, notify) {
        fs.stat(filepath, function (err, stats) {
            if (err) {
                return reject(err);
            }

            if (stats.isDirectory()) {
                resolve(hashFolderPromise(name, directoryPath));
            } else if (stats.isFile()) {
                resolve(hashFilePromise(name, directoryPath));
            } else {
                resolve({ name: name, hash: 'unknown element type' });
            }
        });
    });
}

function hashFolderPromise(foldername, directoryPath) {
    var TAG = 'hashFolderPromise(' + foldername + ', ' + directoryPath + '):';
    var folderPath = path.join(directoryPath, foldername);
    return Promise(function (resolve, reject, notify) {
        fs.readdir(folderPath, function (err, files) {
            if (err) {
                console.error(TAG, err);
                reject(err);
            }

            var children = files.map(function (child) {
                return hashElementPromise(child, folderPath);
            });

            var allChildren = Q.all(children);

            return allChildren.then(function (children) {

                var hash = crypto.createHash(algo);
                hash.write(foldername);
                children.forEach(function (child) {
                    if (child.hash) {
                        hash.write(child.hash);
                    }
                });

                var checksum = hash.digest(encoding);

                resolve({ name: foldername, hash: checksum, children: children });
            });
        });
    });
}

function hashFilePromise(filename, directoryPath) {
    return Promise(function (resolve, reject, notify) {
        try {
            var hash = crypto.createHash(algo);
            hash.write(filename);

            var f = fs.createReadStream(path.join(directoryPath, filename));
            f.pipe(hash, { end: false });

            f.on('end', function () {
                var result = hash.digest(encoding);

                resolve({
                    name: filename,
                    hash: result
                });
            });

        } catch (ex) {
            reject(ex);
        }
    });
}<|endoftext|>


<commit_before>var spawn = require('child_process').spawn
var os = require('os')
var Through = require('audio-through')
var pump = require('pump')

module.exports = function (outputFormat) {

  var inputFormat = {
    signed: true,
    float: false,
    bitDepth: 16,
    byteOrder: os.endianness instanceof Function ? os.endianness() : 'LE',
    channels: 2,
    sampleRate: 44100,
    interleaved: false,
    samplesPerFrame: 44100,
    sampleSize: 2,
    id: 'S_16_LE_2_44100_I',
    max: 32678,
    min: -32768
  }
  this.format = inputFormat

  outputFormat = outputFormat || inputFormat

  // TODO: use web/node based on detection
  var stream = nodeMicStream()

  var through = new Through(
    inputFormat,
    outputFormat
  );

  stream.pipe(through)

  return pump(stream, through)
}

function nodeMicStream () {
  var args = [
    '-r',
    '44100',
    '-t',
    's16',
    '-c',
    '2',
    '-'
  ]
  return spawn('rec', args).stdout
}

function browserMicStream () {
  throw new Error('not implemented')
}
<commit_msg>use arecord -- much better results<commit_after>var spawn = require('child_process').spawn
var os = require('os')
var Through = require('audio-through')
var pump = require('pump')

module.exports = function (outputFormat) {

  var inputFormat = {
    signed: true,
    float: false,
    bitDepth: 16,
    byteOrder: os.endianness instanceof Function ? os.endianness() : 'LE',
    channels: 2,
    sampleRate: 44100,
    interleaved: true,
    samplesPerFrame: 1024,
    sampleSize: 2,
    id: 'S_16_LE_2_44100_I',
    max: 32678,
    min: -32768
  }
  this.format = inputFormat

  outputFormat = outputFormat || inputFormat

  // TODO: use web/node based on detection
  var stream = nodeMicStream()

  var through = new Through(
    inputFormat,
    outputFormat
  );

  stream.pipe(through)

  return pump(stream, through)
}

function nodeMicStream () {
  // var args = '-t s16 -c 1 -r 44100 -'.split(' ')
  // return spawn('rec', args).stdout
  var args = '-c 2 -r 44100 -f S16_LE --buffer-size=16384'.split(' ')
  return spawn('arecord', args).stdout
}

function browserMicStream () {
  throw new Error('not implemented')
}
<|endoftext|>


<commit_before>var MultiServer = require('multiserver')
var WS = require('multiserver/plugins/ws')
var SHS = require('multiserver/plugins/shs')
var http = require('http')
var muxrpc = require('muxrpc')
var pull = require('pull-stream')
var JSONApi = require('./json-api')
var LetsEncrypt = require('./letsencrypt')

var cap =
  new Buffer('1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s=', 'base64')

function toSodiumKeys(keys) {
  return {
    publicKey:
      new Buffer(keys.public.replace('.ed25519',''), 'base64'),
    secretKey:
      new Buffer(keys.private.replace('.ed25519',''), 'base64'),
  }
}

var READ_AND_ADD = [ //except for add, of course
  'get',
  'getLatest',
  'createLogStream',
  'createUserStream',

  'createHistoryStream',
  'getAddress',

  'links',

  'blobs.add',
  'blobs.size',
  'blobs.has',
  'blobs.get',
  'blobs.changes',
  'blobs.createWants',

  'add',

  'query.read',
  'links2.read'
]

exports.name = 'ws'
exports.version = require('./package.json').version
exports.manifest = {
  getAddress: 'sync'
}

function toId(id) {
  return '@'+id.toString('base64')+'.ed25519'
}

exports.init = function (sbot, config) {

  var port
  if(config.ws)
    port = config.ws.port
  if(!port)
    port = 1024+(~~(Math.random()*(65536-1024)))

  var server = http.createServer(JSONApi(sbot)).listen(port)

  //allow friends to
  sbot.auth.hook(function (fn, args) {
    var id = args[0]
    var cb = args[1]
    var self = this
    fn.apply(self, [id, function (err, allowed) {
      if(err) return cb(err)
      if(allowed) return cb(null, allowed)
      sbot.friends.get({source: sbot.id, dest: id}, function (err, follows) {
        if(err) return cb(err)
        else if(follows) cb(null, {allow: READ_AND_ADD, deny: null})
        else cb()
      })
    }])

  })

  var ms = MultiServer([
    [
      WS({server: server, port: port, host: config.host || 'localhost'}),
      SHS({
        keys: toSodiumKeys(config.keys),
        appKey: (config.caps && config.caps.shs) || cap,
        auth: function (id, cb) {
          sbot.auth(toId(id), cb)
        },
        timeout: config.timeout
      })
    ]
  ])

  var close = ms.server(function (stream) {
    var manifest = sbot.getManifest()
    var rpc = muxrpc({}, manifest)(sbot, stream.auth)
    rpc.id = toId(stream.remote)
    pull(stream, rpc.createStream(), stream)
  })

  //close when the server closes.
  sbot.close.hook(function (fn, args) {
    close()
    fn.apply(this, args)
  })

  return {
    getAddress: function () {
      return ms.stringify()
    }

  }
}

<commit_msg>oops, letsencrypt is removed<commit_after>var MultiServer = require('multiserver')
var WS = require('multiserver/plugins/ws')
var SHS = require('multiserver/plugins/shs')
var http = require('http')
var muxrpc = require('muxrpc')
var pull = require('pull-stream')
var JSONApi = require('./json-api')

var cap =
  new Buffer('1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s=', 'base64')

function toSodiumKeys(keys) {
  return {
    publicKey:
      new Buffer(keys.public.replace('.ed25519',''), 'base64'),
    secretKey:
      new Buffer(keys.private.replace('.ed25519',''), 'base64'),
  }
}

var READ_AND_ADD = [ //except for add, of course
  'get',
  'getLatest',
  'createLogStream',
  'createUserStream',

  'createHistoryStream',
  'getAddress',

  'links',

  'blobs.add',
  'blobs.size',
  'blobs.has',
  'blobs.get',
  'blobs.changes',
  'blobs.createWants',

  'add',

  'query.read',
  'links2.read'
]

exports.name = 'ws'
exports.version = require('./package.json').version
exports.manifest = {
  getAddress: 'sync'
}

function toId(id) {
  return '@'+id.toString('base64')+'.ed25519'
}

exports.init = function (sbot, config) {

  var port
  if(config.ws)
    port = config.ws.port
  if(!port)
    port = 1024+(~~(Math.random()*(65536-1024)))

  var server = http.createServer(JSONApi(sbot)).listen(port)

  //allow friends to
  sbot.auth.hook(function (fn, args) {
    var id = args[0]
    var cb = args[1]
    var self = this
    fn.apply(self, [id, function (err, allowed) {
      if(err) return cb(err)
      if(allowed) return cb(null, allowed)
      sbot.friends.get({source: sbot.id, dest: id}, function (err, follows) {
        if(err) return cb(err)
        else if(follows) cb(null, {allow: READ_AND_ADD, deny: null})
        else cb()
      })
    }])

  })

  var ms = MultiServer([
    [
      WS({server: server, port: port, host: config.host || 'localhost'}),
      SHS({
        keys: toSodiumKeys(config.keys),
        appKey: (config.caps && config.caps.shs) || cap,
        auth: function (id, cb) {
          sbot.auth(toId(id), cb)
        },
        timeout: config.timeout
      })
    ]
  ])

  var close = ms.server(function (stream) {
    var manifest = sbot.getManifest()
    var rpc = muxrpc({}, manifest)(sbot, stream.auth)
    rpc.id = toId(stream.remote)
    pull(stream, rpc.createStream(), stream)
  })

  //close when the server closes.
  sbot.close.hook(function (fn, args) {
    close()
    fn.apply(this, args)
  })

  return {
    getAddress: function () {
      return ms.stringify()
    }

  }
}

<|endoftext|>


<commit_before>module.exports = {
  name: 'Ember CLI Simple Auth Cookie Store',

  included: function(app) {
    this._super.included(app);

    this.app.import(app.bowerDirectory + 'ember-simple-auth/simple-auth-cookie-store.amd.js', {
      exports: {
        'simple-auth-cookie-store/stores/cookie': ['default'],
        'simple-auth-cookie-store/initializer':   ['default']
      }
    });
  }
}
<commit_msg>arrrgh...<commit_after>module.exports = {
  name: 'Ember CLI Simple Auth Cookie Store',

  included: function(app) {
    this._super.included(app);

    this.app.import(app.bowerDirectory + '/ember-simple-auth/simple-auth-cookie-store.amd.js', {
      exports: {
        'simple-auth-cookie-store/stores/cookie': ['default'],
        'simple-auth-cookie-store/initializer':   ['default']
      }
    });
  }
}
<|endoftext|>


<commit_before>var _ = require("lodash");
var e = require("estree-builder");
var parser = require("ecmaless-parser");
var compiler = require("ecmaless-compiler");
var escodegen = require("escodegen");

var toJSFile = function(estree, opts){
  opts = opts || {};

  if(!_.isArray(estree)){
    estree = [estree];
  }
  return escodegen.generate({
    "loc": _.size(estree) > 0 ? _.head(estree).loc : undefined,
    "type": "Program",
    "body": estree
  }, opts.escodegen);
};

var extractDeps = function(ast){
  var deps = {};
  var new_ast = ast;
  if(ast[0] && ast[0].type === "Dependencies"){
    _.each(ast[0].dependencies, function(d){
      deps[d.id.value] = d;
    });
    new_ast = ast.slice(1);
  }
  return {deps: deps, ast: new_ast};
};

module.exports = function(conf, callback){

  var modules = {};

  var load = function load(path, callback){
    if(_.has(modules, path)){
      return callback();
    }
    conf.loadPath(path, function(err, src){
      if(err)return callback(err);

      var p = extractDeps(parser(src, {filename: path}));
      var c = compiler(p.ast);

      modules[path] = {
        src: src,
        ast: p.ast,
        est: c.estree
      };

      if(_.isEmpty(p.deps)){
        return callback();
      }
      var done = (function(){
        var error;
        var after = _.after(_.size(p.deps), function(){
          callback(error);
        });
        return function(err){
          if(!error && err){
            error = err;
          }
          after();
        };
      }());
      _.each(p.deps, function(dep){
        load(dep.path.value, done);
      });
    });
  };

  load(conf.start_path, function(err){
    if(err)return callback(err);

    var mods = {};
    _.each(modules, function(m, path){
      mods[path] = e("array", [e("fn", [], m.est)]);
    });
    var est = e("call",
        e("fn", ["mdefs", "main"], []),
        [e("object", mods), e("string", conf.start_path)]);
    callback(void 0, toJSFile(est, conf));
  });
};
<commit_msg>proper compiling of the wrapped module functions<commit_after>var _ = require("lodash");
var e = require("estree-builder");
var parser = require("ecmaless-parser");
var compiler = require("ecmaless-compiler");
var escodegen = require("escodegen");

var toJSFile = function(estree, opts){
  opts = opts || {};

  if(!_.isArray(estree)){
    estree = [estree];
  }
  return escodegen.generate({
    "loc": _.size(estree) > 0 ? _.head(estree).loc : undefined,
    "type": "Program",
    "body": estree
  }, opts.escodegen);
};

var extractDeps = function(ast){
  var deps = {};
  var new_ast = ast;
  if(ast[0] && ast[0].type === "Dependencies"){
    _.each(ast[0].dependencies, function(d){
      deps[d.id.value] = d;
    });
    new_ast = ast.slice(1);
  }
  return {deps: deps, ast: new_ast};
};

module.exports = function(conf, callback){

  var modules = {};

  var load = function load(path, callback){
    if(_.has(modules, path)){
      return callback();
    }
    conf.loadPath(path, function(err, src){
      if(err)return callback(err);

      var ast = parser(src, {filename: path});
      var mloc;//TODO
      var mast = [
        {
          loc: mloc,
          type: "Function",
          params: [],
          block: {
            loc: mloc,
            type: "Block",
            body: []
          }
        }
      ];
      var deps = {};
      if(ast[0] && ast[0].type === "Dependencies"){
        _.each(ast[0].dependencies, function(d){
          deps[d.id.value] = d.path.value;
          mast[0].params.push(d.id)
        });
        mast[0].block.body = ast.slice(1);
      }else{
        mast[0].block.body = ast;
      }

      var c = compiler(mast);

      modules[path] = {
        src: src,
        ast: ast,
        est: c.estree[0],
        mast: mast,
        deps: deps,
      };

      if(_.isEmpty(deps)){
        return callback();
      }
      var done = (function(){
        var error;
        var after = _.after(_.size(deps), function(){
          callback(error);
        });
        return function(err){
          if(!error && err){
            error = err;
          }
          after();
        };
      }());
      _.each(deps, function(path){
        load(path, done);
      });
    });
  };

  load(conf.start_path, function(err){
    if(err)return callback(err);

    var toReqPath = function(path){
      return e("string", path);
    };

    var mods = {};
    _.each(modules, function(m, path){
      mods[path] = e("array", [m.est].concat(_.map(m.deps, toReqPath)));
    });
    var est = e("call",
        e("fn", ["mdefs", "main"], []),
        [e("object", mods), e("string", conf.start_path)]);
    callback(void 0, toJSFile(est, conf));
  });
};
<|endoftext|>


<commit_before>var async      = require('async');
var css        = require('css');
var exec       = require('child_process').exec;
var fs         = require('fs');
var glob       = require('glob');
var handlebars = require('handlebars');
var hljs       = require('highlight.js');
var jsdoc      = require('jsdoc3-parser');
var marked     = require('marked');
var path       = require('path');
var rimraf     = require('rimraf');
var sass       = require('node-sass');
var sassdoc    = require('sassdoc');

handlebars.registerHelper('toUpper', function(str) {
  return str[0].toUpperCase() + str.slice(1);
});

handlebars.registerHelper('writeMixin', function(mixin) {
  var name = mixin['context']['name'];
  var params = mixin['parameter'];

  var str = '@mixin ';
  str += name + '(';
  for (var i in params) {
    str += '$' + params[i]['name'] + ', ';
  }
  str = str.slice(0, -2);
  str += ') { }';

  return str;
});

// Creates a new instance of Supercollider, which will generate a single static site.
// options: an object of configuration settings:
//   - html: directory to scan for HTML
//   - sass: directory to scan for Sass
//   - js: directory to scan for JavaScript
//   - dest: directory to output the test JSON to
var Super = function(options) {
  this.options = options;
}

Super.prototype = {
  // Parses files according to the options passed to the constructor.
  parseFiles: function() {
    var _this = this;
    var tasks = [
      // Hologram
      function(callback) {
        var holo = path.join(__dirname, 'lib', 'hologram.rb');
        exec('bundle exec ruby '+holo+' '+_this.options.html, function(error, stdout, stderr) {
          callback(error, JSON.parse(stdout));
        });
      },
      // SassDoc
      function(callback) {
        sassdoc.parse(_this.options.sass, {verbose: true}).then(function(data) {
          callback(null, data);
        });
      },
      // JSDoc
      function(callback) {
        glob(_this.options.js, function(er, files) {
          var data = [];
          for (var file in files) {
            jsdoc(files[file], function(error, ast) {
              for (var item in ast) data.push(ast[item]);
            });
          }
          callback(null, data);
        });
      },
      // CSS classes
      function(callback) {
        // glob('scss/**/*.scss', function(err, files) {
        //   var data = {};
        //   for (var file in files) {
        //     sass.render({
        //       file: files[file],
        //       includePaths: ['./scss'],
        //       outputStyle: 'nested',
        //       success: function(data, map, status) {
        //         var name = files[file].split('/');
        //         name = name[name.length -1].split
        //         data[]
        //       },
        //       error: function() {
        //         callback(new Error('Error with node-sass.'), {});
        //       }
        //     });
        //   }
        //   callback(null, data);
        // });
        callback(null, {});
      }
    ];

    async.parallel(tasks, function(err, results) {
      _this.process(results);
    });
  },

  // Combines the data from multiple parsing trees into one object.
  // data: an array containing data from different parsers, generated by the async library. Each item in the array is an object containing the output of a single parser.
  process: function(data) {
    var hologram = data[0][0];
    var sassdoc  = data[1];
    var jsdoc    = data[2];
    // var cssobj   = data[3];
    var tree = {};

    // Process Hologram components
    // The Hologram parser forms the "canonical" list of components
    for (var item in hologram) {
      var comp = hologram[item];
      var componentName = comp['blocks'][0]['name'];
      var html = marked(comp['md'], {
        highlight: function(code, lang) {
          return hljs.highlight(lang, code).value;
        }
      });

      tree[componentName] = {
        'html': html,
        'variable': [],
        'mixin': [],
        'function': [],
        'javascript': []
      }
    }

    // Process SassDoc components
    // The @group tag is used to connect items to the main object
    for (var item in sassdoc) {
      var comp   = sassdoc[item];
      var group  = comp['group'][0];
      var type   = comp['context']['type'];

      // Only parse public items
      if (comp['access'] === 'private') continue;

      // Check if the item was assigned to a group
      if (group !== 'undefined') {
        // Check if the group is also an HTML component name
        if (typeof tree[group] === 'object') {
          // Type will be "function", "mixin", or "variable"
          tree[group][type].push(comp);
        }
        else {
          console.warn("Found a Sass component missing HTML documentation: " + group);
        }
      }
      else {
        console.warn("Found a Sass component missing a group: " + comp['context']['name']);
      }
    }

    // Process JSDoc components
    // The @component tag is used to connect items to the main object
    for (var item in jsdoc) {
      var comp = jsdoc[item];

      // Find the component name
      var group = (function() {
        for (var tag in comp['tags']) {
          if (comp['tags'][tag]['title'] === 'component') return comp['tags'][tag]['value'];
        }
        return null;
      })();

      if (group === null) {
        console.warn("Found a JavaScript doclet missing a component name: " + comp['kind'] + " " + comp['name']);
      }
      else {
        if (typeof tree[group] === 'object') {
          tree[group]['javascript'].push(comp);
        }
        else {
          console.warn("Found a JavaScript component missing HTML documentation: " + group);
        }
      }
    }

    if (typeof this.options.destJSON === 'string') {
      var outputPath = path.join(process.cwd(), this.options.destJSON, name+'.html');
      fs.writeFile(outputPath, JSON.stringify(tree));
    }

    this.buildPages(tree);
  },

  // Creates HTML pages out of an object of components, and writes them to disk.
  // tree: an object of components generated by Super.process().
  buildPages: function(tree) {
    // Fetch template code
    var layoutSrc = fs.readFileSync('templates/layout.html');
    var componentSrc = fs.readFileSync('templates/component.html')

    // Compile it into Handlebars templates
    var layoutTemplate = handlebars.compile(layoutSrc.toString(), {noEscape: true});
    var componentTemplate = handlebars.compile(componentSrc.toString(), {noEscape: true});

    // Erase an existing build folder and recreate it
    if (fs.existsSync(this.options.dest)) {
      rimraf.sync(this.options.dest)
    }
    fs.mkdirSync(this.options.dest);

    var components = Object.keys(tree);

    // For each component in the list, render a template with that component's data and write it to disk
    for (var name in tree) {
      var data = tree[name];

      // Compile the page
      var componentPage = componentTemplate(data);
      var layoutPage    = layoutTemplate({body: componentPage, components: components});

      // Write to disk
      var outputPath = path.join(process.cwd(), this.options.dest, name+'.html');
      fs.writeFileSync(outputPath, layoutPage);
    }
  }
}

module.exports = function(options) {
  var s = new Super(options);
  s.parseFiles();
}<commit_msg>Add markdown helper to handlebars<commit_after>var async      = require('async');
var css        = require('css');
var exec       = require('child_process').exec;
var fs         = require('fs');
var glob       = require('glob');
var handlebars = require('handlebars');
var hljs       = require('highlight.js');
var jsdoc      = require('jsdoc3-parser');
var marked     = require('marked');
var path       = require('path');
var rimraf     = require('rimraf');
var sass       = require('node-sass');
var sassdoc    = require('sassdoc');

handlebars.registerHelper('toUpper', function(str) {
  return str[0].toUpperCase() + str.slice(1);
});

handlebars.registerHelper('writeMixin', function(mixin) {
  var name = mixin['context']['name'];
  var params = mixin['parameter'];

  var str = '@mixin ';
  str += name + '(';
  for (var i in params) {
    str += '$' + params[i]['name'] + ', ';
  }
  str = str.slice(0, -2);
  str += ') { }';

  return str;
});

handlebars.registerHelper('md', function(text) {
  return marked(text);
});

// Creates a new instance of Supercollider, which will generate a single static site.
// options: an object of configuration settings:
//   - html: directory to scan for HTML
//   - sass: directory to scan for Sass
//   - js: directory to scan for JavaScript
//   - dest: directory to output the test JSON to
var Super = function(options) {
  this.options = options;
}

Super.prototype = {
  // Parses files according to the options passed to the constructor.
  parseFiles: function() {
    var _this = this;
    var tasks = [
      // Hologram
      function(callback) {
        var holo = path.join(__dirname, 'lib', 'hologram.rb');
        exec('bundle exec ruby '+holo+' '+_this.options.html, function(error, stdout, stderr) {
          callback(error, JSON.parse(stdout));
        });
      },
      // SassDoc
      function(callback) {
        sassdoc.parse(_this.options.sass, {verbose: true}).then(function(data) {
          callback(null, data);
        });
      },
      // JSDoc
      function(callback) {
        glob(_this.options.js, function(er, files) {
          var data = [];
          for (var file in files) {
            jsdoc(files[file], function(error, ast) {
              for (var item in ast) data.push(ast[item]);
            });
          }
          callback(null, data);
        });
      },
      // CSS classes
      function(callback) {
        // glob('scss/**/*.scss', function(err, files) {
        //   var data = {};
        //   for (var file in files) {
        //     sass.render({
        //       file: files[file],
        //       includePaths: ['./scss'],
        //       outputStyle: 'nested',
        //       success: function(data, map, status) {
        //         var name = files[file].split('/');
        //         name = name[name.length -1].split
        //         data[]
        //       },
        //       error: function() {
        //         callback(new Error('Error with node-sass.'), {});
        //       }
        //     });
        //   }
        //   callback(null, data);
        // });
        callback(null, {});
      }
    ];

    async.parallel(tasks, function(err, results) {
      _this.process(results);
    });
  },

  // Combines the data from multiple parsing trees into one object.
  // data: an array containing data from different parsers, generated by the async library. Each item in the array is an object containing the output of a single parser.
  process: function(data) {
    var hologram = data[0][0];
    var sassdoc  = data[1];
    var jsdoc    = data[2];
    // var cssobj   = data[3];
    var tree = {};

    // Process Hologram components
    // The Hologram parser forms the "canonical" list of components
    for (var item in hologram) {
      var comp = hologram[item];
      var componentName = comp['blocks'][0]['name'];
      var html = marked(comp['md'], {
        highlight: function(code, lang) {
          return hljs.highlight(lang, code).value;
        }
      });

      tree[componentName] = {
        'html': html,
        'variable': [],
        'mixin': [],
        'function': [],
        'javascript': []
      }
    }

    // Process SassDoc components
    // The @group tag is used to connect items to the main object
    for (var item in sassdoc) {
      var comp   = sassdoc[item];
      var group  = comp['group'][0];
      var type   = comp['context']['type'];

      // Only parse public items
      if (comp['access'] === 'private') continue;

      // Check if the item was assigned to a group
      if (group !== 'undefined') {
        // Check if the group is also an HTML component name
        if (typeof tree[group] === 'object') {
          // Type will be "function", "mixin", or "variable"
          tree[group][type].push(comp);
        }
        else {
          console.warn("Found a Sass component missing HTML documentation: " + group);
        }
      }
      else {
        console.warn("Found a Sass component missing a group: " + comp['context']['name']);
      }
    }

    // Process JSDoc components
    // The @component tag is used to connect items to the main object
    for (var item in jsdoc) {
      var comp = jsdoc[item];

      // Find the component name
      var group = (function() {
        for (var tag in comp['tags']) {
          if (comp['tags'][tag]['title'] === 'component') return comp['tags'][tag]['value'];
        }
        return null;
      })();

      if (group === null) {
        console.warn("Found a JavaScript doclet missing a component name: " + comp['kind'] + " " + comp['name']);
      }
      else {
        if (typeof tree[group] === 'object') {
          tree[group]['javascript'].push(comp);
        }
        else {
          console.warn("Found a JavaScript component missing HTML documentation: " + group);
        }
      }
    }

    if (typeof this.options.destJSON === 'string') {
      var outputPath = path.join(process.cwd(), this.options.destJSON, name+'.html');
      fs.writeFile(outputPath, JSON.stringify(tree));
    }

    this.buildPages(tree);
  },

  // Creates HTML pages out of an object of components, and writes them to disk.
  // tree: an object of components generated by Super.process().
  buildPages: function(tree) {
    // Fetch template code
    var layoutSrc = fs.readFileSync('templates/layout.html');
    var componentSrc = fs.readFileSync('templates/component.html')

    // Compile it into Handlebars templates
    var layoutTemplate = handlebars.compile(layoutSrc.toString(), {noEscape: true});
    var componentTemplate = handlebars.compile(componentSrc.toString(), {noEscape: true});

    // Erase an existing build folder and recreate it
    if (fs.existsSync(this.options.dest)) {
      rimraf.sync(this.options.dest)
    }
    fs.mkdirSync(this.options.dest);

    var components = Object.keys(tree);

    // For each component in the list, render a template with that component's data and write it to disk
    for (var name in tree) {
      var data = tree[name];

      // Compile the page
      var componentPage = componentTemplate(data);
      var layoutPage    = layoutTemplate({body: componentPage, components: components});

      // Write to disk
      var outputPath = path.join(process.cwd(), this.options.dest, name+'.html');
      fs.writeFileSync(outputPath, layoutPage);
    }
  }
}

module.exports = function(options) {
  var s = new Super(options);
  s.parseFiles();
}<|endoftext|>


<commit_before>var badArgumentsError = new Error('hpkp must be called with a maxAge and at least two SHA-256s (one actually used and another kept as a backup).');

module.exports = function hpkp(passedOptions) {
  var options = parseOptions(passedOptions);
  var headerKey = getHeaderKey(options);
  var headerValue = getHeaderValue(options);

  return function hpkp(req, res, next) {
    res.setHeader(headerKey, headerValue);
    next();
  };
};

function parseOptions(options) {
  if (!options) { throw badArgumentsError; }

  if (options.maxage && options.maxAge) { throw badArgumentsError; }

  var maxAge = options.maxAge || options.maxage;
  var sha256s = options.sha256s;

  if (!maxAge || (maxAge <= 0)) { throw badArgumentsError; }
  if (!sha256s || (sha256s.length < 2)) { throw badArgumentsError; }

  return {
    maxAge: maxAge,
    sha256s: sha256s,
    includeSubdomains: options.includeSubdomains,
    reportUri: options.reportUri
  };
}

function getHeaderKey(options) {
  var header = 'Public-Key-Pins';
  if (options.reportUri) {
    header += '-Report-Only';
  }
  return header;
}

function getHeaderValue(options) {
  var result = options.sha256s.map(function (sha) {
    return 'pin-sha256="' + sha + '"';
  });
  result.push('max-age=' + Math.round(options.maxAge / 1000));
  if (options.includeSubdomains) {
    result.push('includeSubdomains');
  }
  if (options.reportUri) {
    result.push('report-uri="' + options.reportUri + '"');
  }
  return result.join('; ');
}
<commit_msg>Minor: remove some gratuitous parens<commit_after>var badArgumentsError = new Error('hpkp must be called with a maxAge and at least two SHA-256s (one actually used and another kept as a backup).');

module.exports = function hpkp(passedOptions) {
  var options = parseOptions(passedOptions);
  var headerKey = getHeaderKey(options);
  var headerValue = getHeaderValue(options);

  return function hpkp(req, res, next) {
    res.setHeader(headerKey, headerValue);
    next();
  };
};

function parseOptions(options) {
  if (!options) { throw badArgumentsError; }

  if (options.maxage && options.maxAge) { throw badArgumentsError; }

  var maxAge = options.maxAge || options.maxage;
  var sha256s = options.sha256s;

  if (!maxAge || maxAge <= 0) { throw badArgumentsError; }
  if (!sha256s || sha256s.length < 2) { throw badArgumentsError; }

  return {
    maxAge: maxAge,
    sha256s: sha256s,
    includeSubdomains: options.includeSubdomains,
    reportUri: options.reportUri
  };
}

function getHeaderKey(options) {
  var header = 'Public-Key-Pins';
  if (options.reportUri) {
    header += '-Report-Only';
  }
  return header;
}

function getHeaderValue(options) {
  var result = options.sha256s.map(function (sha) {
    return 'pin-sha256="' + sha + '"';
  });
  result.push('max-age=' + Math.round(options.maxAge / 1000));
  if (options.includeSubdomains) {
    result.push('includeSubdomains');
  }
  if (options.reportUri) {
    result.push('report-uri="' + options.reportUri + '"');
  }
  return result.join('; ');
}
<|endoftext|>


<commit_before>/**
 * UI Modal component for A-Frame.
 */

if (typeof AFRAME === 'undefined') {
  throw new Error('Component attempted to register before AFRAME was available.');
}

AFRAME.registerComponent('ui-modal', {

    schema: {
        src: {
            type: 'selector',
            default: ''
        },
        show: {
            default: 'click'
        },
        hide: {
            default: 'click'
        },
        zpos: {
            default: -4
        }
    },

    init: function() {

        document.querySelector(data.src).addEventListener(this.data.show, this.show.bind(this));
        document.querySelector(data.src).addEventListener(this.data.hide, this.hide.bind(this));

        this.cameraEl = document.querySelector('a-entity[camera]');

        this.yaxis = new THREE.Vector3(0, 1, 0);
        this.zaxis = new THREE.Vector3(0, 0, 1);

        this.pivot = new THREE.Object3D();
        this.el.object3D.position.set(0, this.cameraEl.object3D.getWorldPosition().y, this.data.zpos);

        this.el.sceneEl.object3D.add(this.pivot);
        this.pivot.add(this.el.object3D);

    },

    show: function(evt) {

        if (this.el.getAttribute('visible') === false) {

            var direction = this.zaxis.clone();
            direction.applyQuaternion(this.cameraEl.object3D.quaternion);
            var ycomponent = this.yaxis.clone().multiplyScalar(direction.dot(this.yaxis));
            direction.sub(ycomponent);
            direction.normalize();

            this.pivot.quaternion.setFromUnitVectors(this.zaxis, direction);
            this.pivot.position.copy(this.cameraEl.object3D.getWorldPosition());

            this.el.setAttribute('visible', true);

        }

    },

    hide: function(evt) {

        if (this.el.getAttribute('visible') === true) {

            this.el.setAttribute('visible', false);

        }

    },

    update: function (oldData) {},

    remove: function() {}

});

<commit_msg>fixed this.data<commit_after>/**
 * UI Modal component for A-Frame.
 */

if (typeof AFRAME === 'undefined') {
  throw new Error('Component attempted to register before AFRAME was available.');
}

AFRAME.registerComponent('ui-modal', {

    schema: {
        src: {
            type: 'selector',
            default: ''
        },
        show: {
            default: 'click'
        },
        hide: {
            default: 'click'
        },
        zpos: {
            default: -4
        }
    },

    init: function() {

        document.querySelector(this.data.src).addEventListener(this.data.show, this.show.bind(this));
        document.querySelector(this.data.src).addEventListener(this.data.hide, this.hide.bind(this));

        this.cameraEl = document.querySelector('a-entity[camera]');

        this.yaxis = new THREE.Vector3(0, 1, 0);
        this.zaxis = new THREE.Vector3(0, 0, 1);

        this.pivot = new THREE.Object3D();
        this.el.object3D.position.set(0, this.cameraEl.object3D.getWorldPosition().y, this.data.zpos);

        this.el.sceneEl.object3D.add(this.pivot);
        this.pivot.add(this.el.object3D);

    },

    show: function(evt) {

        if (this.el.getAttribute('visible') === false) {

            var direction = this.zaxis.clone();
            direction.applyQuaternion(this.cameraEl.object3D.quaternion);
            var ycomponent = this.yaxis.clone().multiplyScalar(direction.dot(this.yaxis));
            direction.sub(ycomponent);
            direction.normalize();

            this.pivot.quaternion.setFromUnitVectors(this.zaxis, direction);
            this.pivot.position.copy(this.cameraEl.object3D.getWorldPosition());

            this.el.setAttribute('visible', true);

        }

    },

    hide: function(evt) {

        if (this.el.getAttribute('visible') === true) {

            this.el.setAttribute('visible', false);

        }

    },

    update: function (oldData) {},

    remove: function() {}

});

<|endoftext|>


<commit_before>var Botkit = require("botkit");

// Expect a SLACK_TOKEN environment variable
var slackToken = process.env.SLACK_TOKEN;
if (!slackToken) {
    console.error("SLACK_TOKEN is required!");
    process.exit(1);
}

var controller = Botkit.slackbot();
var bot = controller.spawn({
    "token": slackToken
});

bot.startRTM(function(err, bot, payload) {
    if (err) {
        throw new Error("Could not connect to Slack");
    }
});

// Join message
controller.on("bot_channel_join", function(bot, message) {
    bot.reply(message, "I'm here!");
});

// Mention listener
controller.hears(["hello", "hi", "sup", "howdy", "yo"], ["direct_mention"], function(bot, message) {
    bot.reply(message, "sup");
});

// DM listener
controller.hears(["hello", "hi", "sup", "howdy", "yo"], ["direct_message"], function(bot, message) {
    bot.reply(message, "Wuddup.");
    bot.reply(message, "It\'s nice to talk to you directly.");
});

// Help message
controller.hears("help", ["direct_message", "direct_mention"], function(bot, message) {
    var help = "I will respond to the following messages: \n" +
        "`bot hi` for a simple message.\n" +
        "`bot convert [number]` to convert DKK to USD.\n" +
        "`bot convert from [number] [currency1] to [currency2]` to convert a currency.\n" +
        "`bot translate [words]` to translate anything into English.\n" +
        "`bot help` to see this again.";
    bot.reply(message, help);
});

// Custom scripts
// ==============

//=> Interpreter: translates Danish to English

// Expect a GOOGLE_TOKEN environment variable
var googleToken = process.env.GOOGLE_TOKEN;
if (!googleToken) {
    console.error("GOOGLE_TOKEN is required!");
    process.exit(1);
}

var googleTranslate = require("google-translate")(googleToken);

controller.hears(["^translate (.*)$"], ["direct_message", "direct_mention"], function(bot, message) {
    googleTranslate.translate(message.match[1], "da", "en", function(err, translation) {
        try {
            bot.reply(message, ":flag-dk: => " + translation.translatedText);
        }
        catch (err) {
            bot.reply(message, err);
        }
    });
});
// <=

//=> Converter: converts currencies

// Use openexchangerates.com for up-to-date rates
// Expect an OXR_TOKEN environment variable
var oxrToken = process.env.OXR_TOKEN;
if (!oxrToken) {
    console.error("OXR_TOKEN is required!");
    process.exit(1);
}

var oxr = require("open-exchange-rates"),
    fx = require("money"),
    d3Format = require("d3-format");

fx.settings = {"from": "DKK", "to": "USD"}; //! Broken
var fxSettingsIsBroken = true;

oxr.set({"app_id": oxrToken});

var format = d3Format.format(",.3s"),
    currencyPattern = /([+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?) (\w{3}) to (\w{3})/g;

// Takes a value, an input currency, and returns an output currency
controller.hears(["^convert from (.*)"], ["direct_message", "direct_mention"], function(bot, message) {
    oxr.latest(function() {
        try {
            fx.rates = oxr.rates,
            fx.base = oxr.base;

            match = currencyPattern.exec(message.match[1]);

            // Uppercase currencies are required---apparently
            num = match[1],
            fromCur = match[2].toUpperCase(),
            toCur = match[3].toUpperCase();

            result = format(fx(num).from(fromCur).to(toCur));

            bot.reply(message, result + " " + toCur);
        }
        catch (err) {
            bot.reply(message, err);
        }
    });
});

// Converts a number from USD to DKK
controller.hears(["^convert (.*)$"], ["direct_message", "direct_mention"], function(bot, message) {
    oxr.latest(function() {
        try {
            fx.rates = oxr.rates,
            fx.base = oxr.base;

            // fromCur = "",
            // toCur = "",
            num = message.match[1];

            if (fxSettingsIsBroken) { // Long conversion with explicit currencies
                fromCur = fx.settings.from, //  message.from || fx.settings.from
                toCur = fx.settings.to; // message.to || fx.settings.to;

                result = format(fx(num).from(fromCur).to(toCur));

                bot.reply(message, result + " " + toCur);
            }
            else { // Shorthand conversion with implied currencies
                bot.reply(message, (fx(num)));
            }
        }
        catch (err) {
            bot.reply(message, err);
        }
    });
});
// <=

// This goes by the end of the file; it works as an "else" function for listener events.
controller.hears(".*", ["direct_message", "direct_mention"], function(bot, message) {
    bot.reply(message, "Sorry <@" + message.user + ">, I don\'t understand. \n");
});
<commit_msg>Add missing dollar character<commit_after>var Botkit = require("botkit");

// Expect a SLACK_TOKEN environment variable
var slackToken = process.env.SLACK_TOKEN;
if (!slackToken) {
    console.error("SLACK_TOKEN is required!");
    process.exit(1);
}

var controller = Botkit.slackbot();
var bot = controller.spawn({
    "token": slackToken
});

bot.startRTM(function(err, bot, payload) {
    if (err) {
        throw new Error("Could not connect to Slack");
    }
});

// Join message
controller.on("bot_channel_join", function(bot, message) {
    bot.reply(message, "I'm here!");
});

// Mention listener
controller.hears(["hello", "hi", "sup", "howdy", "yo"], ["direct_mention"], function(bot, message) {
    bot.reply(message, "sup");
});

// DM listener
controller.hears(["hello", "hi", "sup", "howdy", "yo"], ["direct_message"], function(bot, message) {
    bot.reply(message, "Wuddup.");
    bot.reply(message, "It\'s nice to talk to you directly.");
});

// Help message
controller.hears("help", ["direct_message", "direct_mention"], function(bot, message) {
    var help = "I will respond to the following messages: \n" +
        "`bot hi` for a simple message.\n" +
        "`bot convert [number]` to convert DKK to USD.\n" +
        "`bot convert from [number] [currency1] to [currency2]` to convert a currency.\n" +
        "`bot translate [words]` to translate anything into English.\n" +
        "`bot help` to see this again.";
    bot.reply(message, help);
});

// Custom scripts
// ==============

//=> Interpreter: translates Danish to English

// Expect a GOOGLE_TOKEN environment variable
var googleToken = process.env.GOOGLE_TOKEN;
if (!googleToken) {
    console.error("GOOGLE_TOKEN is required!");
    process.exit(1);
}

var googleTranslate = require("google-translate")(googleToken);

controller.hears(["^translate (.*)$"], ["direct_message", "direct_mention"], function(bot, message) {
    googleTranslate.translate(message.match[1], "da", "en", function(err, translation) {
        try {
            bot.reply(message, ":flag-dk: => " + translation.translatedText);
        }
        catch (err) {
            bot.reply(message, err);
        }
    });
});
// <=

//=> Converter: converts currencies

// Use openexchangerates.com for up-to-date rates
// Expect an OXR_TOKEN environment variable
var oxrToken = process.env.OXR_TOKEN;
if (!oxrToken) {
    console.error("OXR_TOKEN is required!");
    process.exit(1);
}

var oxr = require("open-exchange-rates"),
    fx = require("money"),
    d3Format = require("d3-format");

fx.settings = {"from": "DKK", "to": "USD"}; //! Broken
var fxSettingsIsBroken = true;

oxr.set({"app_id": oxrToken});

var format = d3Format.format(",.3s"),
    currencyPattern = /([+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?) (\w{3}) to (\w{3})/g;

// Takes a value, an input currency, and returns an output currency
controller.hears(["^convert from (.*)$"], ["direct_message", "direct_mention"], function(bot, message) {
    oxr.latest(function() {
        try {
            fx.rates = oxr.rates,
            fx.base = oxr.base;

            match = currencyPattern.exec(message.match[1]);

            // Uppercase currencies are required---apparently
            num = match[1],
            fromCur = match[2].toUpperCase(),
            toCur = match[3].toUpperCase();

            result = format(fx(num).from(fromCur).to(toCur));

            bot.reply(message, result + " " + toCur);
        }
        catch (err) {
            bot.reply(message, err);
        }
    });
});

// Converts a number from USD to DKK
controller.hears(["^convert (.*)$"], ["direct_message", "direct_mention"], function(bot, message) {
    oxr.latest(function() {
        try {
            fx.rates = oxr.rates,
            fx.base = oxr.base;

            // fromCur = "",
            // toCur = "",
            num = message.match[1];

            if (fxSettingsIsBroken) { // Long conversion with explicit currencies
                fromCur = fx.settings.from, //  message.from || fx.settings.from
                toCur = fx.settings.to; // message.to || fx.settings.to;

                result = format(fx(num).from(fromCur).to(toCur));

                bot.reply(message, result + " " + toCur);
            }
            else { // Shorthand conversion with implied currencies
                bot.reply(message, (fx(num)));
            }
        }
        catch (err) {
            bot.reply(message, err);
        }
    });
});
// <=

// This goes by the end of the file; it works as an "else" function for listener events.
controller.hears(".*", ["direct_message", "direct_mention"], function(bot, message) {
    bot.reply(message, "Sorry <@" + message.user + ">, I don\'t understand. \n");
});
<|endoftext|>


<commit_before>var util = require("./lib/utils");
var knox = require("knox");
var s3;

function S3Context(options) {
  this.readOnly = options.isReadOnly;
  this.keyPrefix = options.keyPrefix;
}

function prefixKey(prefix, key) {
  return prefix + "/" + key;
}

S3Context.prototype.put = function (key, value, callback) {
  if(this.readOnly) {
    return callback("Error: Write operation on readOnly context.");
  }
  key = prefixKey(this.keyPrefix, key);
  // We do extra work to make sure typed arrays survive
  // being stored in S3 and still get the right prototype later.
  if (Object.prototype.toString.call(value) === "[object Uint8Array]") {
    value = {
      __isUint8Array: true,
      __array: util.u8toArray(value)
    };
  }
  value = JSON.stringify(value);
  var headers = {
    'x-amz-acl': 'public-read',
    'Content-Length': Buffer.byteLength(value),
    'application/type': 'application/json'
  };

  function onError() {
    callback("Error " + res.statusCode);
  }

  s3.put(key, headers)
    .on("error", onError)
    .on("response", function (res) {
      if (res.statusCode !== 200) {
        onError();
      }
      callback(null);
    })
    .end(value);
};

S3Context.prototype.delete = function (key, callback) {
  if(this.readOnly) {
    return callback("Error: Write operation on readOnly context.");
  }
  key = prefixKey(this.keyPrefix, key);
  s3.del(key).on('response', function (res) {
    if(res.statusCode === 403) {
      return callback("Error: 403. Permission denied");
    }
    callback(null);
  }).end();
};

S3Context.prototype.clear = function (callback) {
  if(this.readOnly) {
    return callback("Error: Write operation on readOnly context.");
  }
  var options = {
    prefix: this.keyPrefix
  };
  getAllObjects(options, callback, []);

  function getAllObjects(options, callback, aggregate) {
    s3.list(options, function (err, data) {
      aggregate = aggregate.concat(data.Contents.map(function (content) {
        return content.Key;
      }));
      if (data.IsTruncated) {
        options.marker = data.Contents[data.Contents.length - 1].Key;
        getAllObjects(options, callback, aggregate);
      }
      s3.deleteMultiple(aggregate, function (err, res) {
        if(res.statusCode === 403) {
          return callback("Error 403: Permission deined." + err);
        }
        return callback(null);
      });
    });
  }

};

S3Context.prototype.get = function (key, callback) {
  key = prefixKey(this.keyPrefix, key);
  s3.get(key).on('response', function (res) {
    if (res.statusCode === 404) {
      return callback("Error " + res.statusCode);
    }
    var chunks = [];
    res.on('data', function (chunk) {
      chunks.push(chunk);
    }).on('end', function () {
      var value = chunks.join('');
      try {
        if(value) {
          value = JSON.parse(value);
          // Deal with special-cased flattened typed arrays in WebSQL (see put() below)
          if(value.__isUint8Array) {
            value = new Uint8Array(value.__array);
          }
        }
        callback(null, value);
      } catch(e) {
        return callback(e);
      }
    });
  }).end();
};

function S3Provider(options) {
  this.name = options.name;
  this.keyPrefix = options.keyPrefix;
}

S3Provider.isSupported = function() {
  return (typeof module !== 'undefined' && module.exports);
};

S3Provider.prototype.open = function(options, callback) {
  if(!this.keyPrefix) {
    callback("Error: Missing keyPrefix");
    return;
  }
  try {
    s3 = knox.createClient({
      bucket: options.bucket,
      key: options.key,
      secret: options.secret
    });
    s3.list({ prefix: this.keyPrefix, maxKeys: 1 }, function(err, data) {
      if(err) {
        callback(err);
        return;
      }
      // Check to see if this is the first access or not"
      callback(null, data.Contents.length === 0);
    });
  } catch(e) {
    callback("Error: Unable to connect to s3. " + e);
  }
};

S3Provider.prototype.getReadOnlyContext = function() {
  return new S3Context({isReadOnly: true, keyPrefix: this.keyPrefix});
};

S3Provider.prototype.getReadWriteContext = function() {
  return new S3Context({isReadOnly: false, keyPrefix: this.keyPrefix});
};

module.exports = S3Provider;
<commit_msg>Add missing 'res' in onError<commit_after>var util = require("./lib/utils");
var knox = require("knox");
var s3;

function S3Context(options) {
  this.readOnly = options.isReadOnly;
  this.keyPrefix = options.keyPrefix;
}

function prefixKey(prefix, key) {
  return prefix + "/" + key;
}

S3Context.prototype.put = function (key, value, callback) {
  if(this.readOnly) {
    return callback("Error: Write operation on readOnly context.");
  }
  key = prefixKey(this.keyPrefix, key);
  // We do extra work to make sure typed arrays survive
  // being stored in S3 and still get the right prototype later.
  if (Object.prototype.toString.call(value) === "[object Uint8Array]") {
    value = {
      __isUint8Array: true,
      __array: util.u8toArray(value)
    };
  }
  value = JSON.stringify(value);
  var headers = {
    'x-amz-acl': 'public-read',
    'Content-Length': Buffer.byteLength(value),
    'application/type': 'application/json'
  };

  function onError(res) {
    callback("Error " + res.statusCode);
  }

  s3.put(key, headers)
    .on("error", onError)
    .on("response", function (res) {
      if (res.statusCode !== 200) {
        onError(res);
      }
      callback(null);
    })
    .end(value);
};

S3Context.prototype.delete = function (key, callback) {
  if(this.readOnly) {
    return callback("Error: Write operation on readOnly context.");
  }
  key = prefixKey(this.keyPrefix, key);
  s3.del(key).on('response', function (res) {
    if(res.statusCode === 403) {
      return callback("Error: 403. Permission denied");
    }
    callback(null);
  }).end();
};

S3Context.prototype.clear = function (callback) {
  if(this.readOnly) {
    return callback("Error: Write operation on readOnly context.");
  }
  var options = {
    prefix: this.keyPrefix
  };
  getAllObjects(options, callback, []);

  function getAllObjects(options, callback, aggregate) {
    s3.list(options, function (err, data) {
      aggregate = aggregate.concat(data.Contents.map(function (content) {
        return content.Key;
      }));
      if (data.IsTruncated) {
        options.marker = data.Contents[data.Contents.length - 1].Key;
        getAllObjects(options, callback, aggregate);
      }
      s3.deleteMultiple(aggregate, function (err, res) {
        if(res.statusCode === 403) {
          return callback("Error 403: Permission deined." + err);
        }
        return callback(null);
      });
    });
  }

};

S3Context.prototype.get = function (key, callback) {
  key = prefixKey(this.keyPrefix, key);
  s3.get(key).on('response', function (res) {
    if (res.statusCode === 404) {
      return callback("Error " + res.statusCode);
    }
    var chunks = [];
    res.on('data', function (chunk) {
      chunks.push(chunk);
    }).on('end', function () {
      var value = chunks.join('');
      try {
        if(value) {
          value = JSON.parse(value);
          // Deal with special-cased flattened typed arrays in WebSQL (see put() below)
          if(value.__isUint8Array) {
            value = new Uint8Array(value.__array);
          }
        }
        callback(null, value);
      } catch(e) {
        return callback(e);
      }
    });
  }).end();
};

function S3Provider(options) {
  this.name = options.name;
  this.keyPrefix = options.keyPrefix;
}

S3Provider.isSupported = function() {
  return (typeof module !== 'undefined' && module.exports);
};

S3Provider.prototype.open = function(options, callback) {
  if(!this.keyPrefix) {
    callback("Error: Missing keyPrefix");
    return;
  }
  try {
    s3 = knox.createClient({
      bucket: options.bucket,
      key: options.key,
      secret: options.secret
    });
    s3.list({ prefix: this.keyPrefix, maxKeys: 1 }, function(err, data) {
      if(err) {
        callback(err);
        return;
      }
      // Check to see if this is the first access or not"
      callback(null, data.Contents.length === 0);
    });
  } catch(e) {
    callback("Error: Unable to connect to s3. " + e);
  }
};

S3Provider.prototype.getReadOnlyContext = function() {
  return new S3Context({isReadOnly: true, keyPrefix: this.keyPrefix});
};

S3Provider.prototype.getReadWriteContext = function() {
  return new S3Context({isReadOnly: false, keyPrefix: this.keyPrefix});
};

module.exports = S3Provider;
<|endoftext|>


<commit_before>/* eslint-env node */

const SilentError = require('silent-error');

let TsPreprocessor;
try {
  TsPreprocessor = require('./lib/typescript-preprocessor');
} catch (ex) {
  // Do nothing; we just won't have the plugin available. This means that if you
  // somehow end up in a state where it doesn't load, the preprocessor *will*
  // fail, but this is necessary because the preprocessor depends on packages
  // which aren't installed until the
}

module.exports = {
  name: 'ember-cli-typescript',

  setupPreprocessorRegistry(type, registry) {
    if (!TsPreprocessor) {
      this.ui.write(
        'Note: TypeScript preprocessor not available -- some dependencies not installed. ' +
          '(If this is during installation of the add-on, this is as expected. If it is ' +
          'while building, serving, or testing the application, this is an error.)'
      );
      return;
    }

    try {
      registry.add('js', new TsPreprocessor({
        ui: this.ui
      }));
    } catch (ex) {
      throw new SilentError(`Missing or invalid tsconfig.json, please fix or run \`ember generate ember-cli-typescript\`.\n${ex}`);
    }
  },
};
<commit_msg>Fixed preprocessor setup. No correctly detects missing tsconfig.json and skips.<commit_after>/* eslint-env node */

const fs = require('fs');
const path = require('path');
const SilentError = require('silent-error');
const TsPreprocessor = require('./lib/typescript-preprocessor');

module.exports = {
  name: 'ember-cli-typescript',

  setupPreprocessorRegistry(type, registry) {
    if (!fs.existsSync(path.join(this.project.root, 'tsconfig.json'))) {
      // Do nothing; we just won't have the plugin available. This means that if you
      // somehow end up in a state where it doesn't load, the preprocessor *will*
      // fail, but this is necessary because the preprocessor depends on packages
      // which aren't installed until the default blueprint is run

      this.ui.writeInfoLine(
        'Skipping TypeScript preprocessing as there is no tsconfig.json. ' +
        '(If this is during installation of the add-on, this is as expected. If it is ' +
        'while building, serving, or testing the application, this is an error.)'
      );
      return;
    }

    try {
      registry.add('js', new TsPreprocessor({
        ui: this.ui
      }));
    } catch (ex) {
      throw new SilentError(`Failed to instantiate TypeScript preprocessor, probably due to an invalid tsconfig.json. Please fix or run \`ember generate ember-cli-typescript\`.\n${ex}`);
    }
  },
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Provider } from 'react-redux';
import Login from './Login';
import configureStore from '../store/configureStore';
import { Router, Route } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';

const store = configureStore();
const history = createBrowserHistory();

export default class Root extends Component {
    render() {
      return (
          <Provider store={store}>
                              <Router history={history}>
                                  <Route path='/'>
                                      <Route path='/login' component={Login} />
                                  </Route>
                              </Router>
                      </Provider>
      );
    }
}
<commit_msg>Changed client's routes ... now the weird error in the JS console about wrong mime type is gone.<commit_after>import React, { Component } from 'react';
import { Provider } from 'react-redux';
import Login from './Login';
import configureStore from '../store/configureStore';
import { Router, Route } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';

const store = configureStore();
const history = createBrowserHistory();

export default class Root extends Component {
    render() {
      return (
          <Provider store={store}>
                              <Router history={history}>
                                  <Route path='/'>
                                  </Route>
                                  <Route path='/login' component={Login} />
                              </Router>
                      </Provider>
      );
    }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the Clear BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/Handler/Keyboard.js
 */

/**
 * Class: OpenLayers.Control.KeyboardDefaults
 * The KeyboardDefaults control adds panning and zooming functions, controlled
 * with the keyboard. By default arrow keys pan, +/- keys zoom & Page Up/Page
 * Down/Home/End scroll by three quarters of a page.
 *
 * This control has no visible appearance.
 *
 * Inherits from:
 *  - <OpenLayers.Control>
 */
OpenLayers.Control.KeyboardDefaults = OpenLayers.Class(OpenLayers.Control, {

    /**
     * APIProperty: autoActivate
     * {Boolean} Activate the control when it is added to a map.  Default is
     *     true.
     */
    autoActivate: true,

    /**
     * APIProperty: slideFactor
     * Pixels to slide by.
     */
    slideFactor: 75,

    /**
     * Constructor: OpenLayers.Control.KeyboardDefaults
     */

    /**
     * Method: draw
     * Create handler.
     */
    draw: function() {
        this.handler = new OpenLayers.Handler.Keyboard( this, {
                                "keydown": this.defaultKeyPress });
    },

    /**
     * Method: defaultKeyPress
     * When handling the key event, we only use evt.keyCode. This holds
     * some drawbacks, though we get around them below. When interpretting
     * the keycodes below (including the comments associated with them),
     * consult the URL below. For instance, the Safari browser returns
     * "IE keycodes", and so is supported by any keycode labeled "IE".
     *
     * Very informative URL:
     *    http://unixpapa.com/js/key.html
     *
     * Parameters:
     * evt - {Event}
     */
    defaultKeyPress: function (evt) {
        switch(evt.keyCode) {
            case OpenLayers.Event.KEY_LEFT:
                this.map.pan(-this.slideFactor, 0);
                break;
            case OpenLayers.Event.KEY_RIGHT:
                this.map.pan(this.slideFactor, 0);
                break;
            case OpenLayers.Event.KEY_UP:
                this.map.pan(0, -this.slideFactor);
                break;
            case OpenLayers.Event.KEY_DOWN:
                this.map.pan(0, this.slideFactor);
                break;

            case 33: // Page Up. Same in all browsers.
                var size = this.map.getSize();
                this.map.pan(0, -0.75*size.h);
                break;
            case 34: // Page Down. Same in all browsers.
                var size = this.map.getSize();
                this.map.pan(0, 0.75*size.h);
                break;
            case 35: // End. Same in all browsers.
                var size = this.map.getSize();
                this.map.pan(0.75*size.w, 0);
                break;
            case 36: // Home. Same in all browsers.
                var size = this.map.getSize();
                this.map.pan(-0.75*size.w, 0);
                break;

            case 43:  // +/= (ASCII), keypad + (ASCII, Opera)
            case 61:  // +/= (Mozilla, Opera, some ASCII)
            case 187: // +/= (IE)
            case 107: // keypad + (IE, Mozilla)
                this.map.zoomIn();
                break;
            case 45:  // -/_ (ASCII, Opera), keypad - (ASCII, Opera)
            case 109: // -/_ (Mozilla), keypad - (Mozilla, IE)
            case 189: // -/_ (IE)
            case 95:  // -/_ (some ASCII)
                this.map.zoomOut();
                break;
        }
    },

    CLASS_NAME: "OpenLayers.Control.KeyboardDefaults"
});
<commit_msg>remove multiple variable declarations in Control/KeyboardDefaults.js, non functional change<commit_after>/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the Clear BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/Handler/Keyboard.js
 */

/**
 * Class: OpenLayers.Control.KeyboardDefaults
 * The KeyboardDefaults control adds panning and zooming functions, controlled
 * with the keyboard. By default arrow keys pan, +/- keys zoom & Page Up/Page
 * Down/Home/End scroll by three quarters of a page.
 *
 * This control has no visible appearance.
 *
 * Inherits from:
 *  - <OpenLayers.Control>
 */
OpenLayers.Control.KeyboardDefaults = OpenLayers.Class(OpenLayers.Control, {

    /**
     * APIProperty: autoActivate
     * {Boolean} Activate the control when it is added to a map.  Default is
     *     true.
     */
    autoActivate: true,

    /**
     * APIProperty: slideFactor
     * Pixels to slide by.
     */
    slideFactor: 75,

    /**
     * Constructor: OpenLayers.Control.KeyboardDefaults
     */

    /**
     * Method: draw
     * Create handler.
     */
    draw: function() {
        this.handler = new OpenLayers.Handler.Keyboard( this, {
                                "keydown": this.defaultKeyPress });
    },

    /**
     * Method: defaultKeyPress
     * When handling the key event, we only use evt.keyCode. This holds
     * some drawbacks, though we get around them below. When interpretting
     * the keycodes below (including the comments associated with them),
     * consult the URL below. For instance, the Safari browser returns
     * "IE keycodes", and so is supported by any keycode labeled "IE".
     *
     * Very informative URL:
     *    http://unixpapa.com/js/key.html
     *
     * Parameters:
     * evt - {Event}
     */
    defaultKeyPress: function (evt) {
        var size;
        switch(evt.keyCode) {
            case OpenLayers.Event.KEY_LEFT:
                this.map.pan(-this.slideFactor, 0);
                break;
            case OpenLayers.Event.KEY_RIGHT:
                this.map.pan(this.slideFactor, 0);
                break;
            case OpenLayers.Event.KEY_UP:
                this.map.pan(0, -this.slideFactor);
                break;
            case OpenLayers.Event.KEY_DOWN:
                this.map.pan(0, this.slideFactor);
                break;

            case 33: // Page Up. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(0, -0.75*size.h);
                break;
            case 34: // Page Down. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(0, 0.75*size.h);
                break;
            case 35: // End. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(0.75*size.w, 0);
                break;
            case 36: // Home. Same in all browsers.
                size = this.map.getSize();
                this.map.pan(-0.75*size.w, 0);
                break;

            case 43:  // +/= (ASCII), keypad + (ASCII, Opera)
            case 61:  // +/= (Mozilla, Opera, some ASCII)
            case 187: // +/= (IE)
            case 107: // keypad + (IE, Mozilla)
                this.map.zoomIn();
                break;
            case 45:  // -/_ (ASCII, Opera), keypad - (ASCII, Opera)
            case 109: // -/_ (Mozilla), keypad - (Mozilla, IE)
            case 189: // -/_ (IE)
            case 95:  // -/_ (some ASCII)
                this.map.zoomOut();
                break;
        }
    },

    CLASS_NAME: "OpenLayers.Control.KeyboardDefaults"
});
<|endoftext|>


<commit_before>// require('dotenv').load();
var debug = require('debug')('Express4');
var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var cors = require('cors');
var path = require('path');

require('./app_api/models/db');
require('./app_api/config/passport');

// (commented out because routes in the server are not used)
// var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');

var app = express();

//app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json({limit: '5mb', extended: true}));
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());

if(process.env.NODE_ENV === 'production') {
  app.get('*', function(req, res, next) {
    if(req.headers['x-forwarded-proto'] != 'https') {
        res.redirect('https://apila.care' + req.url);
      } else {
        next();
      }
  });
}

app.use('/api', routesApi);
app.use('/files', express.static(__dirname + 'upload_storage'));

app.use(express.static(path.join(__dirname, 'app_client')));

app.get('*', function(req, res) {
  res.sendfile((path.join(__dirname, 'app_client/index.html')));
});

app.set('port', process.env.PORT || 3300);

var server = app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + server.address().port);
});

module.exports = app;
<commit_msg>adding the production/staging different url paths<commit_after>// require('dotenv').load();
var debug = require('debug')('Express4');
var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var cors = require('cors');
var path = require('path');

require('./app_api/models/db');
require('./app_api/config/passport');

// (commented out because routes in the server are not used)
// var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');

var app = express();

//app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json({limit: '5mb', extended: true}));
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());

var url = "";

if(process.env.NODE_ENV === 'production') {
  url = "https://apila.care";
} else if(process.env.NODE_ENV === 'staging') {
  url = "https://apila.us";
}

if(process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
  app.get('*', function(req, res, next) {
    if(req.headers['x-forwarded-proto'] != 'https') {
        res.redirect(url + req.url);
      } else {
        next();
      }
  });
}

app.use('/api', routesApi);
app.use('/files', express.static(__dirname + 'upload_storage'));

app.use(express.static(path.join(__dirname, 'app_client')));

app.get('*', function(req, res) {
  res.sendfile((path.join(__dirname, 'app_client/index.html')));
});

app.set('port', process.env.PORT || 3300);

var server = app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + server.address().port);
});

module.exports = app;
<|endoftext|>


<commit_before>angular.module('tg.dynamicDirective', [])
    .directive('tgDynamicDirective', ['$compile',
        function($compile) {
            'use strict';
            return {
                restrict: 'E',
                require: '^ngModel',
                scope: true,
                template: '

',
                link: function(scope, element, attrs, ngModel) {
                    var ngModelItem = scope.$eval(attrs.ngModel);
                    scope.ngModelItem = ngModelItem;
                    scope.templateUrl = '';

                    var getView = scope.$eval(attrs.tgDynamicDirectiveView);
                    if (getView && typeof getView === 'function') {
                        var templateUrl = getView(ngModelItem);
                        if (templateUrl) {
                            scope.templateUrl = templateUrl;
                        }
                    }
                }
            };
        }
    ]);
<commit_msg>feat: watch the template provider function for changes<commit_after>angular.module('tg.dynamicDirective', [])
    .directive('tgDynamicDirective', ['$compile',
        function($compile) {
            'use strict';

            function templateUrlProvider(getView, ngModelItem) {
                if (getView) {
                    if (typeof getView === 'function') {
                        var templateUrl = getView(ngModelItem) || '';
                        if (templateUrl) {
                            return templateUrl;
                        }
                    } else if (typeof getView === 'string' && getView.length) {
                        return getView;
                    }
                }
                return '';
            }

            return {
                restrict: 'E',
                require: '^ngModel',
                scope: true,
                template: '

',
                link: function(scope, element, attrs, ngModel) {
                    var ngModelItem = scope.$eval(attrs.ngModel);
                    var getView = scope.$eval(attrs.tgDynamicDirectiveView);
                    scope.ngModelItem = ngModelItem;

                    scope.$watch(function() {
                        return templateUrlProvider(getView, ngModelItem);
                    }, function(newValue, oldValue) {
                        scope.templateUrl = newValue;
                    });
                }
            };
        }
    ]);
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Transitional utilities to unsafely trust random strings as
 * goog.html types. Intended for temporary use when upgrading a library that
 * used to accept plain strings to use safe types, but where it's not
 * practical to transitively update callers.
 *
 * IMPORTANT: No new code should use the conversion functions in this file,
 * they are intended for refactoring old code to use goog.html types. New code
 * should construct goog.html types via their APIs, template systems or
 * sanitizers. If that’s not possible it should use
 * goog.html.uncheckedconversions and undergo security review.

 *
 * The semantics of the conversions in goog.html.legacyconversions are very
 * different from the ones provided by goog.html.uncheckedconversions. The
 * latter are for use in code where it has been established through manual
 * security review that the value produced by a piece of code will always
 * satisfy the SafeHtml contract (e.g., the output of a secure HTML sanitizer).
 * In uses of goog.html.legacyconversions, this guarantee is not given -- the
 * value in question originates in unreviewed legacy code and there is no
 * guarantee that it satisfies the SafeHtml contract.
 *
 * There are only three valid uses of legacyconversions:
 *
 * 1. Introducing a goog.html version of a function which currently consumes
 * string and passes that string to a DOM API which can execute script - and
 * hence cause XSS - like innerHTML. For example, Dialog might expose a
 * setContent method which takes a string and sets the innerHTML property of
 * an element with it. In this case a setSafeHtmlContent function could be
 * added, consuming goog.html.SafeHtml instead of string, and using
 * goog.dom.safe.setInnerHtml instead of directly setting innerHTML.
 * setContent could then internally use legacyconversions to create a SafeHtml
 * from string and pass the SafeHtml to setSafeHtmlContent. In this scenario
 * remember to document the use of legacyconversions in the modified setContent
 * and consider deprecating it as well.
 *
 * 2. Automated refactoring of application code which handles HTML as string
 * but needs to call a function which only takes goog.html types. For example,
 * in the Dialog scenario from (1) an alternative option would be to refactor
 * setContent to accept goog.html.SafeHtml instead of string and then refactor
 * all current callers to use legacyconversions to pass SafeHtml. This is
 * generally preferable to (1) because it keeps the library clean of
 * legacyconversions, and makes code sites in application code that are
 * potentially vulnerable to XSS more apparent.
 *
 * 3. Old code which needs to call APIs which consume goog.html types and for
 * which it is prohibitively expensive to refactor to use goog.html types.
 * Generally, this is code where safety from XSS is either hopeless or
 * unimportant.
 */

goog.provide('goog.html.legacyconversions');

goog.require('goog.html.SafeHtml');
goog.require('goog.html.SafeScript');
goog.require('goog.html.SafeStyle');
goog.require('goog.html.SafeStyleSheet');
goog.require('goog.html.SafeUrl');
goog.require('goog.html.TrustedResourceUrl');

/**
 * Performs an "unchecked conversion" from string to SafeHtml for legacy API
 * purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} html A string to be converted to SafeHtml.
 * @return {!goog.html.SafeHtml} The value of html, wrapped in a SafeHtml
 *     object.
 */
goog.html.legacyconversions.safeHtmlFromString = function(html) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
      html, null /* dir */);
};

/**
 * Performs an "unchecked conversion" from string to SafeScript for legacy API
 * purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} script A string to be converted to SafeScript.
 * @return {!goog.html.SafeScript} The value of script, wrapped in a SafeScript
 *     object.
 */
goog.html.legacyconversions.safeScriptFromString = function(script) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(
      script);
};

/**
 * Performs an "unchecked conversion" from string to SafeStyle for legacy API
 * purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} style A string to be converted to SafeStyle.
 * @return {!goog.html.SafeStyle} The value of style, wrapped in a SafeStyle
 *     object.
 */
goog.html.legacyconversions.safeStyleFromString = function(style) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
      style);
};

/**
 * Performs an "unchecked conversion" from string to SafeStyleSheet for legacy
 * API purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} styleSheet A string to be converted to SafeStyleSheet.
 * @return {!goog.html.SafeStyleSheet} The value of style sheet, wrapped in
 *     a SafeStyleSheet object.
 */
goog.html.legacyconversions.safeStyleSheetFromString = function(styleSheet) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeStyleSheet
      .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet);
};

/**
 * Performs an "unchecked conversion" from string to SafeUrl for legacy API
 * purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} url A string to be converted to SafeUrl.
 * @return {!goog.html.SafeUrl} The value of url, wrapped in a SafeUrl
 *     object.
 */
goog.html.legacyconversions.safeUrlFromString = function(url) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
};

/**
 * Performs an "unchecked conversion" from string to TrustedResourceUrl for
 * legacy API purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} url A string to be converted to TrustedResourceUrl.
 * @return {!goog.html.TrustedResourceUrl} The value of url, wrapped in a
 *     TrustedResourceUrl object.
 */
goog.html.legacyconversions.trustedResourceUrlFromString = function(url) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.TrustedResourceUrl
      .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);
};

/**
 * @private {function(): undefined}
 */
goog.html.legacyconversions.reportCallback_ = goog.nullFunction;

/**
 * Sets a function that will be called every time a legacy conversion is
 * performed. The function is called with no parameters but it can use
 * goog.debug.getStacktrace to get a stacktrace.
 *
 * @param {function(): undefined} callback Error callback as defined above.
 */
goog.html.legacyconversions.setReportCallback = function(callback) {
  'use strict';
  goog.html.legacyconversions.reportCallback_ = callback;
};
<commit_msg>Remove a redundant blank line. RELNOTES: n/a<commit_after>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Transitional utilities to unsafely trust random strings as
 * goog.html types. Intended for temporary use when upgrading a library that
 * used to accept plain strings to use safe types, but where it's not
 * practical to transitively update callers.
 *
 * IMPORTANT: No new code should use the conversion functions in this file,
 * they are intended for refactoring old code to use goog.html types. New code
 * should construct goog.html types via their APIs, template systems or
 * sanitizers. If that’s not possible it should use
 * goog.html.uncheckedconversions and undergo security review.
 *
 * The semantics of the conversions in goog.html.legacyconversions are very
 * different from the ones provided by goog.html.uncheckedconversions. The
 * latter are for use in code where it has been established through manual
 * security review that the value produced by a piece of code will always
 * satisfy the SafeHtml contract (e.g., the output of a secure HTML sanitizer).
 * In uses of goog.html.legacyconversions, this guarantee is not given -- the
 * value in question originates in unreviewed legacy code and there is no
 * guarantee that it satisfies the SafeHtml contract.
 *
 * There are only three valid uses of legacyconversions:
 *
 * 1. Introducing a goog.html version of a function which currently consumes
 * string and passes that string to a DOM API which can execute script - and
 * hence cause XSS - like innerHTML. For example, Dialog might expose a
 * setContent method which takes a string and sets the innerHTML property of
 * an element with it. In this case a setSafeHtmlContent function could be
 * added, consuming goog.html.SafeHtml instead of string, and using
 * goog.dom.safe.setInnerHtml instead of directly setting innerHTML.
 * setContent could then internally use legacyconversions to create a SafeHtml
 * from string and pass the SafeHtml to setSafeHtmlContent. In this scenario
 * remember to document the use of legacyconversions in the modified setContent
 * and consider deprecating it as well.
 *
 * 2. Automated refactoring of application code which handles HTML as string
 * but needs to call a function which only takes goog.html types. For example,
 * in the Dialog scenario from (1) an alternative option would be to refactor
 * setContent to accept goog.html.SafeHtml instead of string and then refactor
 * all current callers to use legacyconversions to pass SafeHtml. This is
 * generally preferable to (1) because it keeps the library clean of
 * legacyconversions, and makes code sites in application code that are
 * potentially vulnerable to XSS more apparent.
 *
 * 3. Old code which needs to call APIs which consume goog.html types and for
 * which it is prohibitively expensive to refactor to use goog.html types.
 * Generally, this is code where safety from XSS is either hopeless or
 * unimportant.
 */

goog.provide('goog.html.legacyconversions');

goog.require('goog.html.SafeHtml');
goog.require('goog.html.SafeScript');
goog.require('goog.html.SafeStyle');
goog.require('goog.html.SafeStyleSheet');
goog.require('goog.html.SafeUrl');
goog.require('goog.html.TrustedResourceUrl');

/**
 * Performs an "unchecked conversion" from string to SafeHtml for legacy API
 * purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} html A string to be converted to SafeHtml.
 * @return {!goog.html.SafeHtml} The value of html, wrapped in a SafeHtml
 *     object.
 */
goog.html.legacyconversions.safeHtmlFromString = function(html) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
      html, null /* dir */);
};

/**
 * Performs an "unchecked conversion" from string to SafeScript for legacy API
 * purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} script A string to be converted to SafeScript.
 * @return {!goog.html.SafeScript} The value of script, wrapped in a SafeScript
 *     object.
 */
goog.html.legacyconversions.safeScriptFromString = function(script) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(
      script);
};

/**
 * Performs an "unchecked conversion" from string to SafeStyle for legacy API
 * purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} style A string to be converted to SafeStyle.
 * @return {!goog.html.SafeStyle} The value of style, wrapped in a SafeStyle
 *     object.
 */
goog.html.legacyconversions.safeStyleFromString = function(style) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
      style);
};

/**
 * Performs an "unchecked conversion" from string to SafeStyleSheet for legacy
 * API purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} styleSheet A string to be converted to SafeStyleSheet.
 * @return {!goog.html.SafeStyleSheet} The value of style sheet, wrapped in
 *     a SafeStyleSheet object.
 */
goog.html.legacyconversions.safeStyleSheetFromString = function(styleSheet) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeStyleSheet
      .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet);
};

/**
 * Performs an "unchecked conversion" from string to SafeUrl for legacy API
 * purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} url A string to be converted to SafeUrl.
 * @return {!goog.html.SafeUrl} The value of url, wrapped in a SafeUrl
 *     object.
 */
goog.html.legacyconversions.safeUrlFromString = function(url) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);
};

/**
 * Performs an "unchecked conversion" from string to TrustedResourceUrl for
 * legacy API purposes.
 *
 * Please read fileoverview documentation before using.
 *
 * @param {string} url A string to be converted to TrustedResourceUrl.
 * @return {!goog.html.TrustedResourceUrl} The value of url, wrapped in a
 *     TrustedResourceUrl object.
 */
goog.html.legacyconversions.trustedResourceUrlFromString = function(url) {
  'use strict';
  goog.html.legacyconversions.reportCallback_();
  return goog.html.TrustedResourceUrl
      .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);
};

/**
 * @private {function(): undefined}
 */
goog.html.legacyconversions.reportCallback_ = goog.nullFunction;

/**
 * Sets a function that will be called every time a legacy conversion is
 * performed. The function is called with no parameters but it can use
 * goog.debug.getStacktrace to get a stacktrace.
 *
 * @param {function(): undefined} callback Error callback as defined above.
 */
goog.html.legacyconversions.setReportCallback = function(callback) {
  'use strict';
  goog.html.legacyconversions.reportCallback_ = callback;
};
<|endoftext|>


<commit_before>const discord = require('discord.js');

module.exports = {
	name: 'guide',
	description: 'Provides a set of guides for Puyo players to better themselves at playing Puyo.',
	aliases: ['g'],
	category: ['Help'],
	usage: [''],
	execute(message) {
		const em = new discord.RichEmbed();

		em.setColor(0x59AFEF);
		em.setTitle('Guides:');
		em.addField('Puyo Nexus: How to play Puyo Puyo!', 'https://puyonexus.com/wiki/How_to_Play_Puyo_Puyo',false);
		em.addField('Puyo Puyo lesson plan', 'https://puyo.guide',false);
		em.setFooter('Guides will be added when they are released.');

		// TODO: mini-guides.

		message.channel.send(em);
	},
};<commit_msg>Some (outdated) guides as well as restoring qb/mq functionality.<commit_after>const discord = require('discord.js');

module.exports = {
	name: 'guide',
	description: 'Provides a set of guides for Puyo players to better themselves at playing Puyo.',
	aliases: ['g'],
	category: ['Help'],
	usage: [''],
	execute(message, args) {

		const postfix = args[0];

		const em = new discord.RichEmbed();

		if (!postfix) {

			em.setColor(0x59AFEF);
			em.setTitle('Guides:');
			em.addField('Puyo Nexus: How to play Puyo Puyo!', 'https://puyonexus.com/wiki/How_to_Play_Puyo_Puyo',false);
			em.addField('Puyo Puyo lesson plan', 'https://puyo.guide',false);
			em.addField('**outdated** How to think', 'https://puyonexus.com/forum/viewtopic.php?f=3&t=26');
			em.addField('**outdated** Guide to losing battles', 'https://puyonexus.com/forum/viewtopic.php?f=3&t=3445');
			em.addField('**outdated** Observational Skillsets', 'https://puyonexus.com/forum/viewtopic.php?f=3&t=2921')
			em.addField('Multiquest Guide', `.guide mq`);
			em.addField('Questbattle Guide', '.guide qb')
			em.setFooter('Guides will be added when they are released.');

		}
		// TODO: mini-guides. - partly done

		if (postfix == 'qb') {

			em.setTitle("HELP: Multiplayer Battle help.  Syntax:")
			.setColor(0x00FF00)
			.setDescription("questBattle (Battle Code) (Battle Type) (Battle Title - Optional)")
			.addField("Battle Code", "get the quest code from your Everybody Battle!! game", false)
			.addField("Battle Type", "1: **Standard PvP**" +
						"\n2: **Death Match** (1 row vs. 1 row)",false)
			.addField("For EXP:","3: **Fight Club** (visitor brings close to nothing, lets host kill as quickly as possible)" +
			"\n4: **Target Practice** (host lets visitor kill as quickly as possible)")
			.addField("Battle Title", "A description for your battle, optional.",false)
			.setFooter("Battles will come with a TAPI PPQ link for members to join.  Please use responsibly!");

		}

		else if (postfix == 'mq') {

			em.setTitle("HELP: Multiplayer Quest help.  Syntax:")
			.setColor(0x00FF00)
			.setDescription("multiQuest (Quest Code) (Quest Access) (Quest title - optional)")
			.addField("Quest Code", "Get the quest code from your Everybody Quest!! game",false)
			.addField("Quest Access","1: **Open to Public**\n2: **Open to Guild**\n3: **Code Only**",false)
			.addField("Quest Title","A description for your quest, optional.",false)
			.setFooter("Quests will come with a TAPI PPQ link for members to join.  Please use responsibly!");

		}

		message.channel.send(em);
	},
};<|endoftext|>