<commit_before>/*jslint sloppy:true indent:2 plusplus:true regexp:true*/

var contentPattern = '&&<>&&';

function contentFor(contentName) {
  return contentPattern + contentName + contentPattern;
}

function parseContents(locals) {
  var name, i = 1, str = locals.body,
    regex = new RegExp('\n?' + contentPattern + '.+?' + contentPattern + '\n?', 'g'),
    split = str.split(regex),
    matches = str.match(regex);

  locals.body = split[0];

  if (matches !== null) {
    matches.forEach(function (match) {
      name = match.split(contentPattern)[1];
      locals[name] = split[i];
      i++;
    });
  }
}

function parseScripts(locals) {
  var str = locals.body, regex = /\<script[\s\S]*?\>[\s\S]*?\<\/script\>/g;

  if (regex.test(str)) {
    locals.body = str.replace(regex, '');
    locals.script = str.match(regex).join('\n');
  }
}

function parseStyles(locals) {
  var str = locals.body, regex = /(?:\<style[\s\S]*?\>[\s\S]*?\<\/style\>)|(?:\<link[\s\S]*?\>(?:\<\/link\>)?)/g;

  if (regex.test(str)) {
    locals.body = str.replace(regex, '');
    locals.style = str.match(regex).join('\n');
  }
}

function parseMetas(locals) {
  var str = locals.body, regex = /\<meta[\s\S]*?\>/g;

  if (regex.test(str)) {
    locals.body = str.replace(regex, '');
    locals.meta = str.match(regex).join('\n');
  }
}

module.exports = function (req, res, next) {
  var render = res.render;

  res.render = function (view, options, fn) {
    var layout, self = this, app = req.app,
      defaultLayout = app.get('layout');

    options = options || {};
    if (typeof options === 'function') {
      fn = options;
      options = {};
    }

    if (options.layout === false || ((options.layout || defaultLayout) === false)) {
      render.call(res, view, options, fn);
      return;
    }

    layout = options.layout || res.locals.layout || defaultLayout;
    if (layout === true || layout === undefined) {
      layout = 'layout';
    }

    options.contentFor = contentFor;
    render.call(res, view, options, function (err, str) {
      var l, locals;

      if (err) { return fn ? fn(err) : next(err); }

      locals = {
        body: str,
        defineContent: function(contentName) { return locals[contentName] || ''; }
      };
      for (l in options) {
        if (options.hasOwnProperty(l) && l !== 'layout' && l !== 'contentFor') {
          locals[l] = options[l];
        }
      }

      if (options.extractScripts === true || (options.extractScripts === undefined && app.get('layout extractScripts') === true)) {
        locals.script = '';
        parseScripts(locals);
      }

      if (options.extractStyles === true || (options.extractStyles === undefined && app.get('layout extractStyles') === true)) {
        locals.style = '';
        parseStyles(locals);
      }

      if (options.extractMetas === true || (options.extractMetas === undefined && app.get('layout extractMetas') === true)) {
        locals.meta = '';
        parseMetas(locals);
      }

      parseContents(locals);
      render.call(self, layout, locals, fn);
    });
  };
  next();
};
<commit_msg>Fix original render assignment, ensure we dont override the render method multiple times<commit_after>/*jslint sloppy:true indent:2 plusplus:true regexp:true*/

var contentPattern = '&&<>&&';

function contentFor(contentName) {
  return contentPattern + contentName + contentPattern;
}

function parseContents(locals) {
  var name, i = 1, str = locals.body,
    regex = new RegExp('\n?' + contentPattern + '.+?' + contentPattern + '\n?', 'g'),
    split = str.split(regex),
    matches = str.match(regex);

  locals.body = split[0];

  if (matches !== null) {
    matches.forEach(function (match) {
      name = match.split(contentPattern)[1];
      locals[name] = split[i];
      i++;
    });
  }
}

function parseScripts(locals) {
  var str = locals.body, regex = /\<script[\s\S]*?\>[\s\S]*?\<\/script\>/g;

  if (regex.test(str)) {
    locals.body = str.replace(regex, '');
    locals.script = str.match(regex).join('\n');
  }
}

function parseStyles(locals) {
  var str = locals.body, regex = /(?:\<style[\s\S]*?\>[\s\S]*?\<\/style\>)|(?:\<link[\s\S]*?\>(?:\<\/link\>)?)/g;

  if (regex.test(str)) {
    locals.body = str.replace(regex, '');
    locals.style = str.match(regex).join('\n');
  }
}

function parseMetas(locals) {
  var str = locals.body, regex = /\<meta[\s\S]*?\>/g;

  if (regex.test(str)) {
    locals.body = str.replace(regex, '');
    locals.meta = str.match(regex).join('\n');
  }
}

module.exports = function (req, res, next) {
  if(!res.__render) res.__render = res.render;

  res.render = function (view, options, fn) {
    var layout, self = this, app = req.app,
      defaultLayout = app.get('layout');

    options = options || {};
    if (typeof options === 'function') {
      fn = options;
      options = {};
    }

    if (options.layout === false || ((options.layout || defaultLayout) === false)) {
      res.__render.call(res, view, options, fn);
      return;
    }

    layout = options.layout || res.locals.layout || defaultLayout;
    if (layout === true || layout === undefined) {
      layout = 'layout';
    }

    options.contentFor = contentFor;
    res.__render.call(res, view, options, function (err, str) {
      var l, locals;

      if (err) { return fn ? fn(err) : next(err); }

      locals = {
        body: str,
        defineContent: function(contentName) { return locals[contentName] || ''; }
      };
      for (l in options) {
        if (options.hasOwnProperty(l) && l !== 'layout' && l !== 'contentFor') {
          locals[l] = options[l];
        }
      }

      if (options.extractScripts === true || (options.extractScripts === undefined && app.get('layout extractScripts') === true)) {
        locals.script = '';
        parseScripts(locals);
      }

      if (options.extractStyles === true || (options.extractStyles === undefined && app.get('layout extractStyles') === true)) {
        locals.style = '';
        parseStyles(locals);
      }

      if (options.extractMetas === true || (options.extractMetas === undefined && app.get('layout extractMetas') === true)) {
        locals.meta = '';
        parseMetas(locals);
      }

      parseContents(locals);
      res.__render.call(self, layout, locals, fn);
    });
  };
  next();
};
<|endoftext|>


<commit_before>
// Express - Request - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)

/**
 * StaticFile for Request#sendfile()
 */

var StaticFile = require('express/static').File

/**
 * Default response code bodies.
 */

var statusBodies = require('http').STATUS_CODES

// --- InvalidStatusCode

InvalidStatusCode = ExpressError.extend({
  name: 'InvalidStatusCode',
  init: function(status) {
    this.message = status + ' is an invalid HTTP response code'
  }
})

// --- InvalidResponseBody

InvalidResponseBody = ExpressError.extend({
  name: 'InvalidResponseBody',
  init: function(request) {
    this.message = request.method + ' ' + JSON.encode(request.uri.path) + ' did not respond with a body string'
  }
})

// --- Helpers

/**
 * Normalize the given _path_.
 * Strips trailing slashes and whitespace.
 *
 * @param  {string} path
 * @return {string}
 * @api public
 */

exports.normalizePath = function(path) {
  return path.replace(/[\s\/]*$/g, '')
}

// --- Request

exports.Request = Class({

  /**
   * Initialize with node's _request_ and _response_ objects.
   *
   * @param  {object} request
   * @param  {object} response
   * @api private
   */

  init: function(request, response) {
    process.mixin(true, this, request)
    response.headers = {}
    this.response = response
    this.uri.path = exports.normalizePath(this.uri.path)
    this.params = {
      get: parseNestedParams(this.uri.params),
      post: {},
      path: {}
    }
    this.plugins = $(Express.plugins).map(function(plugin){
      return new plugin.klass(plugin.options)
    })
  },

  /**
   * Set response header _key_ and _val_ or get
   * request header value by _key_.
   *
   * @param  {string} key
   * @param  {string} val
   * @return {string}
   * @api public
   */

  header: function(key, val) {
    return val === undefined ?
      this.headers[key.toLowerCase()] :
        this.response.headers[key.toLowerCase()] = val
  },

  /**
   * Return a param _key_ value or null.
   *
   *  - Checks route populated path parameters
   *  - Checks POST parameters
   *  - Checks GET parameters
   *
   * @param  {string} key
   * @return {string}
   * @api public
   */

  param: function(key) {
    return this.params.get[key] ||
           this.params.post[key] ||
           this.params.path[key]
  },

  /**
   * Check if Accept header includes the mime type
   * for the given _path_, which calls mime().
   *
   * When no Accept header is present true will be
   * returned as stated in the HTTP specification.
   *
   * @param  {string} path
   * @return {bool}
   * @see mime()
   * @api public
   */

  accepts: function(path) {
    return this.header('accept') ?
      this.header('accept').indexOf(mime(path)) !== -1 :
        true
  },

  /**
   * Set response status to _code_.
   *
   * @param  {int} code
   * @return {int}
   * @api public
   */

  status: function(code) {
    return this.response.status = code
  },

  /**
   * Immediately respond with response _code_, _body_ and optional _encoding_.
   * The status _code_ defaults to to 404, and _body_ will
   * default to the default body associated with the response
   * _code_.
   *
   * When an invalid status _code_ is passed, InvalidStatusCode
   * will be thrown.
   *
   * @param  {int} code
   * @param  {string} body
   * @param  {string} encoding
   * @see statusBodies
   * @api public
   */

  halt: function(code, body, encoding) {
    this.status(code = code || 404)
    if (body = body || statusBodies[code])
      return this.respond(body, encoding)
    throw new InvalidStatusCode(code)
  },

  /**
   * Respond with _body_ and optional _encoding_.
   *
   * @param  {string} body
   * @param  {string} encoding
   * @see Request#halt()
   * @api private
   */

  respond: function(body, encoding) {
    this.response.body = body
    this.trigger('response')
    if (typeof this.response.body != 'string') throw new InvalidResponseBody(this)
    if (typeof this.response.status != 'number') throw new InvalidStatusCode(this.response.status)
    this.response.sendHeader(this.response.status, this.response.headers)
    this.response.sendBody(this.response.body, encoding)
    this.response.finish()
  },

  /**
   * Set Content-Type header to the mime type
   * for the given _path_, which calls mime().
   *
   * @param  {string} path
   * @see mime()
   * @api public
   */

  contentType: function(path) {
    this.header('content-type', mime(path))
  },

  /**
   * Trigger even _name_ with optional _data_.
   *
   * @param  {string} name
   * @param  {hash} data
   * @api public
   */

  trigger: function(name, data) {
    data = process.mixin(data || {}, {
      request: this,
      response: this.response
    })
    this.plugins.each(function(plugin){
      plugin.trigger(new Event(name, data))
    })
  },

  /**
   * Set Content-Disposition header to 'attachment',
   * with optional _filename_.
   *
   * @param  {string} filename
   * @api public
   */

  attachment: function(filename) {
    this.header('content-disposition', filename ?
       'attachment; filename="' + filename + '"' :
         'attachment')
  },

  /**
   * Transfer static file at the given _path_.
   *
   * @param  {string} path
   * @api public
   */

  sendfile: function(path) {
    (new StaticFile(path)).send(this)
  }
})<commit_msg>Added Request#download()<commit_after>
// Express - Request - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)

/**
 * StaticFile for Request#sendfile()
 */

var StaticFile = require('express/static').File

/**
 * Default response code bodies.
 */

var statusBodies = require('http').STATUS_CODES

// --- InvalidStatusCode

InvalidStatusCode = ExpressError.extend({
  name: 'InvalidStatusCode',
  init: function(status) {
    this.message = status + ' is an invalid HTTP response code'
  }
})

// --- InvalidResponseBody

InvalidResponseBody = ExpressError.extend({
  name: 'InvalidResponseBody',
  init: function(request) {
    this.message = request.method + ' ' + JSON.encode(request.uri.path) + ' did not respond with a body string'
  }
})

// --- Helpers

/**
 * Normalize the given _path_.
 * Strips trailing slashes and whitespace.
 *
 * @param  {string} path
 * @return {string}
 * @api public
 */

exports.normalizePath = function(path) {
  return path.replace(/[\s\/]*$/g, '')
}

// --- Request

exports.Request = Class({

  /**
   * Initialize with node's _request_ and _response_ objects.
   *
   * @param  {object} request
   * @param  {object} response
   * @api private
   */

  init: function(request, response) {
    process.mixin(true, this, request)
    response.headers = {}
    this.response = response
    this.uri.path = exports.normalizePath(this.uri.path)
    this.params = {
      get: parseNestedParams(this.uri.params),
      post: {},
      path: {}
    }
    this.plugins = $(Express.plugins).map(function(plugin){
      return new plugin.klass(plugin.options)
    })
  },

  /**
   * Set response header _key_ and _val_ or get
   * request header value by _key_.
   *
   * @param  {string} key
   * @param  {string} val
   * @return {string}
   * @api public
   */

  header: function(key, val) {
    return val === undefined ?
      this.headers[key.toLowerCase()] :
        this.response.headers[key.toLowerCase()] = val
  },

  /**
   * Return a param _key_ value or null.
   *
   *  - Checks route populated path parameters
   *  - Checks POST parameters
   *  - Checks GET parameters
   *
   * @param  {string} key
   * @return {string}
   * @api public
   */

  param: function(key) {
    return this.params.get[key] ||
           this.params.post[key] ||
           this.params.path[key]
  },

  /**
   * Check if Accept header includes the mime type
   * for the given _path_, which calls mime().
   *
   * When no Accept header is present true will be
   * returned as stated in the HTTP specification.
   *
   * @param  {string} path
   * @return {bool}
   * @see mime()
   * @api public
   */

  accepts: function(path) {
    return this.header('accept') ?
      this.header('accept').indexOf(mime(path)) !== -1 :
        true
  },

  /**
   * Set response status to _code_.
   *
   * @param  {int} code
   * @return {int}
   * @api public
   */

  status: function(code) {
    return this.response.status = code
  },

  /**
   * Immediately respond with response _code_, _body_ and optional _encoding_.
   * The status _code_ defaults to to 404, and _body_ will
   * default to the default body associated with the response
   * _code_.
   *
   * When an invalid status _code_ is passed, InvalidStatusCode
   * will be thrown.
   *
   * @param  {int} code
   * @param  {string} body
   * @param  {string} encoding
   * @see statusBodies
   * @api public
   */

  halt: function(code, body, encoding) {
    this.status(code = code || 404)
    if (body = body || statusBodies[code])
      return this.respond(body, encoding)
    throw new InvalidStatusCode(code)
  },

  /**
   * Respond with _body_ and optional _encoding_.
   *
   * @param  {string} body
   * @param  {string} encoding
   * @see Request#halt()
   * @api private
   */

  respond: function(body, encoding) {
    this.response.body = body
    this.trigger('response')
    if (typeof this.response.body != 'string') throw new InvalidResponseBody(this)
    if (typeof this.response.status != 'number') throw new InvalidStatusCode(this.response.status)
    this.response.sendHeader(this.response.status, this.response.headers)
    this.response.sendBody(this.response.body, encoding)
    this.response.finish()
  },

  /**
   * Set Content-Type header to the mime type
   * for the given _path_, which calls mime().
   *
   * @param  {string} path
   * @see mime()
   * @api public
   */

  contentType: function(path) {
    this.header('content-type', mime(path))
  },

  /**
   * Trigger even _name_ with optional _data_.
   *
   * @param  {string} name
   * @param  {hash} data
   * @api public
   */

  trigger: function(name, data) {
    data = process.mixin(data || {}, {
      request: this,
      response: this.response
    })
    this.plugins.each(function(plugin){
      plugin.trigger(new Event(name, data))
    })
  },

  /**
   * Transfer static file at the given _path_ as an attachment.
   *
   * @param  {string} path
   * @api public
   */

  download: function(path) {
    this.attachment(path)
    this.sendfile(path)
  },

  /**
   * Set Content-Disposition header to 'attachment',
   * with optional file _path_.
   *
   * @param  {string} path
   * @api public
   */

  attachment: function(path) {
    this.header('content-disposition', path ?
       'attachment; filename="' + path + '"' :
         'attachment')
  },

  /**
   * Transfer static file at the given _path_.
   *
   * @param  {string} path
   * @api public
   */

  sendfile: function(path) {
    (new StaticFile(path)).send(this)
  }
})<|endoftext|>


<commit_before>
const R        = require('ramda');
const Bluebird = require('bluebird');
const uuid     = require('uuid');
const Err      = require('../error.js');

const throwInvalidBucket = (bucket) => {
  throw new Error(`Invalid Bucket: ${bucket}`);
};

const throwItemNotFound  = (bucket, id) => {
  throw new Error(`Item ID#${id} Not Found in bucket: ${bucket}`);
};

const missingBucket = R.curryN(2, R.compose(R.not, R.flip(R.has)));

const assertBucket = R.curry((store, bucket) =>
    R.when(missingBucket(store), throwInvalidBucket)(bucket)
);

module.exports = function MemoryStore(data_set) {

  const store = R.defaultTo({}, data_set);

  const getBucket = (bucket) => {
    assertBucket(store, bucket);

    return R.prop(bucket, store);
  };

  const getById = R.curry((bucket, id) => {
    assertBucket(store, bucket);

    return Bluebird.resolve(store[bucket][id]);
  });

  const insert = R.curry((bucket, data) => {
    data.id = uuid.v4();

    if (!R.has(bucket, store)) store[bucket] = {};

    store[bucket][data.id] = data;

    return Bluebird.resolve(data.id);
  });

  const update = R.curry((bucket, id, data) =>

      getById(bucket, id)

    .tap(R.when(R.isNil, () => throwItemNotFound(bucket, id)))

    .then(() => { store[bucket][id] = data })

    .return(id)

  );

  const findWhere = R.curry((bucket, predicates) => R.composeP(
    R.unless(R.isNil, R.compose(
      R.find(R.whereEq(predicates))
      , R.values
    ))
    , R.compose(Bluebird.resolve, R.prop(R.__, store))
  )(bucket));

  const upsert = R.curry((bucket, keys, data) =>

      findWhere(bucket, R.pick(keys,  data))

    .then((found) => found ?
      update(bucket, found.id, R.merge(found, data)) :
      insert(bucket, data)
    )

  );

  const getAll = R.compose(Bluebird.resolve, R.values, getBucket);

  /** @TODO Query Routing
   * const query = R.curry((bucket, query, params) =>
   *   QueryRouter(table, query).then((fn) => fn(store, params))
   * );
   */

  const projectAll = R.curry((bucket, projection) =>
      getAll(bucket).map(R.pick(projection)));

  const findBy = R.curry((bucket, projection, prop, value) =>
      projectAll(bucket, projection).filter(R.propEq(prop, value)));

  const findOneBy = R.curry((bucket, projection, prop, value) =>
      findBy(bucket, projection, prop, value)

    .tap((results) => {
      if (results.length > 1)
        throw new Err.TooManyRecords(
          bucket, prop, value, results.length
        );
    })

    .then(R.head));

  const findById = R.curry((bucket, projection, id) => {

    return getById(bucket, id)
      .then(R.pick(projection))

  });

  return {
    insert
    , upsert
    , getById
    , getAll
    , projectAll
    , findBy
    , findOneBy
    , findById
    , findWhere
  };

}

<commit_msg>Fix custom signature.<commit_after>
const R        = require('ramda');
const Bluebird = require('bluebird');
const uuid     = require('uuid');
const Err      = require('../error.js');

const throwInvalidBucket = (bucket) => {
  throw new Error(`Invalid Bucket: ${bucket}`);
};

const throwItemNotFound  = (bucket, id) => {
  throw new Error(`Item ID#${id} Not Found in bucket: ${bucket}`);
};

const missingBucket = R.curryN(2, R.compose(R.not, R.flip(R.has)));

const assertBucket = R.curry((store, bucket) =>
    R.when(missingBucket(store), throwInvalidBucket)(bucket)
);

module.exports = function MemoryStore(data_set) {

  const store = R.defaultTo({}, data_set);

  const getBucket = (bucket) => {
    assertBucket(store, bucket);

    return R.prop(bucket, store);
  };

  const getById = R.curry((bucket, id) => {
    assertBucket(store, bucket);

    return Bluebird.resolve(store[bucket][id]);
  });

  const insert = R.curry((bucket, data) => {
    data.id = uuid.v4();

    if (!R.has(bucket, store)) store[bucket] = {};

    store[bucket][data.id] = data;

    return Bluebird.resolve(data.id);
  });

  const update = R.curry((bucket, id, data) =>

      getById(bucket, id)

    .tap(R.when(R.isNil, () => throwItemNotFound(bucket, id)))

    .then(() => { store[bucket][id] = data })

    .return(id)

  );

  const findWhere = R.curry((bucket, predicates) => R.composeP(
    R.unless(R.isNil, R.compose(
      R.find(R.whereEq(predicates))
      , R.values
    ))
    , R.compose(Bluebird.resolve, R.prop(R.__, store))
  )(bucket));

  const upsert = R.curry((bucket, keys, data) =>

      findWhere(bucket, R.pick(keys,  data))

    .then((found) => found ?
      update(bucket, found.id, R.merge(found, data)) :
      insert(bucket, data)
    )

  );

  const getAll = R.compose(Bluebird.resolve, R.values, getBucket);

  /** @TODO Query Routing
   * const query = R.curry((bucket, query, params) =>
   *   QueryRouter(query).then((fn) => fn(bucket, store, params))
   * );
   */

  const projectAll = R.curry((bucket, projection) =>
      getAll(bucket).map(R.pick(projection)));

  const findBy = R.curry((bucket, projection, prop, value) =>
      projectAll(bucket, projection).filter(R.propEq(prop, value)));

  const findOneBy = R.curry((bucket, projection, prop, value) =>
      findBy(bucket, projection, prop, value)

    .tap((results) => {
      if (results.length > 1)
        throw new Err.TooManyRecords(
          bucket, prop, value, results.length
        );
    })

    .then(R.head));

  const findById = R.curry((bucket, projection, id) => {

    return getById(bucket, id)
      .then(R.pick(projection))

  });

  return {
    insert
    , upsert
    , getById
    , getAll
    , projectAll
    , findBy
    , findOneBy
    , findById
    , findWhere
  };

}

<|endoftext|>


<commit_before>if(!Draw.textSize) {
  Draw.textSize = function(size) {
    if(!Canvas.configured) {
      console.warn("KAPhy Warning - You must use Canvas.configure(); before you can draw!");
      return;
    }

    var currentFont = Canvas.context.font.split(" ");

    Canvas.context.font = (currentFont.length === 3 ? (currentFont[0] + " ") : "") + Math.round(size) + "px " + currentFont[currentFont.length - 1];
  };
}
<commit_msg>Update textsize.js<commit_after>if(!Draw.textSize) {
  Draw.textSize = function(size) {
    if(!Canvas.configured) {
      console.warn("KAPhy Warning - You must use Canvas.configure(); before you can draw!");
      return;
    }

    var currentFont = Canvas.context.font.split(" ");

    Canvas.context.font = (currentFont.length === 3 ? (currentFont[0] + " ") : "") + Canvas.toPixels(Math.round(size)) + "px " + currentFont[currentFont.length - 1];
  };
}
<|endoftext|>


<commit_before>'use strict';

var fs          = require('fs');
var path        = require('path');
var deprecate   = require('../utilities/deprecate');
var assign      = require('lodash-node/modern/objects/assign');
var glob        = require('glob');
var pickFiles   = require('../broccoli/custom-static-compiler');
var compileES6  = require('broccoli-es6-concatenator');
var mergeTrees  = require('broccoli-merge-trees');
var jshintTrees = require('broccoli-jshint');
var concatFiles = require('broccoli-concat');
var fileMover   = require('broccoli-file-mover');
var SilentError = require('../errors/silent');

var p                   = require('../preprocessors');
var preprocessJs        = p.preprocessJs;
var preprocessCss       = p.preprocessCss;
var preprocessTemplates = p.preprocessTemplates;

var CoreObject = require('core-object');

function Addon(project) {
  this.project = project;
  this.registry = p.setupRegistry(this);

  if (!this.name) {
    throw new SilentError('An addon must define a `name` property.');
  }
}

Addon.__proto__ = CoreObject;
Addon.prototype.constructor = Addon;

Addon.prototype._unwatchedTreeGenerator = function unwatchedTree(dir) {
  return {
    read:    function() { return dir; },
    cleanup: function() { }
  };
};

Addon.prototype.isDevelopingAddon = function() {
  return process.env.EMBER_ADDON_ENV === 'development';
};

Addon.prototype.treeGenerator = function(dir) {
  var tree;
  if (this.isDevelopingAddon()) {
    tree = dir;
  } else {
    tree = this._unwatchedTreeGenerator(dir);
  }

  return tree;
};

Addon.prototype.treePaths = {
  app:               'app',
  styles:            'app/styles',
  templates:         'app/templates',
  addon:             'addon',
  'addon-styles':    'addon/styles',
  'addon-templates': 'addon/templates',
  vendor:            'vendor',
  'test-support':    'test-support'
};

Addon.prototype.treeFor = function treeFor(name) {
  var tree;
  var trees = [];

  if (tree = this._treeFor(name)) {
    trees.push(tree);
  }

  if (this.isDevelopingAddon() && this.app.hinting && name === 'app') {
    trees.push(this.jshinting());
  }

  return mergeTrees(trees);
};

Addon.prototype._treeFor = function _treeFor(name) {
  var treePath = path.join(this.root, this.treePaths[name]);
  var tree;

  if (fs.existsSync(treePath)) {
    tree = this.treeGenerator(treePath);

    if (name === 'addon') {
      tree = this.treeForAddon(tree);
    }
  }

  return tree;
};

Addon.prototype.included = function(app) {
  this.app = app;
};

Addon.prototype.includedModules = function() {
  if (this._includedModules) {
    return this._includedModules;
  }

  var moduleName = this.moduleName();
  var treePath   = path.join(this.root, this.treePaths['addon']);

  this._includedModules = glob.sync(path.join(treePath, '**/*.js')).reduce(function(ignoredModules, filePath) {
    ignoredModules[filePath.replace(treePath, moduleName).slice(0, -3)] = ['default'];
    return ignoredModules;
  }, {});

  return this._includedModules;
};

Addon.prototype.treeForAddon = function(tree) {
  var addonTree = this.compileAddon(tree);
  var stylesTree = this.compileStyles(this._treeFor('addon-styles'));
  var templatesTree = this.compileTemplates(this._treeFor('addon-templates'));

  var jsTree = concatFiles(mergeTrees([addonTree, templatesTree].filter(Boolean)), {
    inputFiles: ['*.js', '**/*.js'],
    outputFile: '/' + this.name + '.js',
    allowNone: true
  });

  return mergeTrees([jsTree, stylesTree].filter(Boolean));
};

Addon.prototype.compileStyles = function(tree) {
  if (tree) {
    var styleFiles = pickFiles(tree, {
      srcDir: '/styles',
      destDir: '/'
    });
    var processedStyles = preprocessCss(styleFiles, '/', '/', {
      registry: this.registry
    });
    return fileMover(processedStyles, {
      srcFile: '/' + this.app.name + '.css',
      destFile: '/' + this.name + '.css'
    });
  }
};

Addon.prototype.compileTemplates = function(tree) {
  if (tree) {
    var standardTemplates = pickFiles(tree, {
      srcDir: '/',
      destDir: this.name + '/templates'
    });

    var podTemplates = pickFiles(tree, {
      srcDir: '/',
      files: ['**/template.*'],
      destDir: this.name + '/',
      allowEmpty: true
    });

    return preprocessTemplates(mergeTrees([standardTemplates, podTemplates]), {
      registry: this.registry
    });
  }
};

Addon.prototype.compileAddon = function(tree) {
  if (Object.keys(this.includedModules()).length === 0) {
    return;
  }

  var addonJs = this.addonJsFiles(tree);

  var es6Tree = compileES6(addonJs, {
    ignoredModules: Object.keys(this.app.importWhitelist),
    inputFiles: [this.name + '/**/*.js'],
    wrapInEval: this.app.options.wrapInEval,
    outputFile: '/' + this.name + '.js'
  });

  this.app.importWhitelist = assign(this.app.importWhitelist, this.includedModules());

  return es6Tree;
};

Addon.prototype.jshinting = function() {
  var addonJs = this.addonJsFiles('addon');
  var jshintedAddon = jshintTrees(addonJs, {
    jshintrcPath: this.app.options.jshintrc.app,
    description: 'JSHint - Addon'
  });
  return pickFiles(jshintedAddon, {
    srcDir: '/',
    destDir: this.name + '/tests/'
  });
};

Addon.prototype.addonJsFiles = function(tree) {
  var files = pickFiles(tree, {
    srcDir: '/',
    files: ['**/*.js'],
    destDir: this.name,
    allowEmpty: true
  });

  return preprocessJs(files, '/', this.name, {
    registry: this.registry
  });
};

Addon.prototype.moduleName = function() {
  return this.name.toLowerCase().replace(/\s/g, '-');
};

Addon.prototype.blueprintsPath = function() {
  var blueprintPath = path.join(this.root, 'blueprints');

  if (fs.existsSync(blueprintPath)) {
    return blueprintPath;
  }
};

Addon.resolvePath = function(addon) {
  var addonMain;

  deprecate(addon.pkg.name + ' is using the deprecated ember-addon-main definition. It should be updated to {\'ember-addon\': {\'main\': \'' + addon.pkg['ember-addon-main'] + '\'}}', addon.pkg['ember-addon-main']);

  addonMain = addon.pkg['ember-addon-main'] || addon.pkg['ember-addon'].main || 'index.js';

  // Resolve will fail unless it has an extension
  if(!path.extname(addonMain)) {
    addonMain += '.js';
  }

  return path.resolve(addon.path, addonMain);
};

Addon.lookup = function(addon) {
  var Constructor, addonModule, modulePath, moduleDir;

  modulePath = Addon.resolvePath(addon);
  moduleDir  = path.dirname(modulePath);

  if (fs.existsSync(modulePath)) {
    addonModule = require(modulePath);

    if (typeof addonModule === 'function') {
      Constructor = addonModule;
      Constructor.prototype.root = Constructor.prototype.root || moduleDir;
    } else {
      Constructor = Addon.extend(assign({root: moduleDir}, addonModule));
    }
  } else {
    Constructor = Addon.extend({
      name: '(generated ' + addon.pkg.name + ' addon)',
      root: moduleDir
    });
  }

  return Constructor;
};

module.exports = Addon;

<commit_msg>Do not require build related packages for every boot.<commit_after>'use strict';

var fs          = require('fs');
var path        = require('path');
var deprecate   = require('../utilities/deprecate');
var assign      = require('lodash-node/modern/objects/assign');
var glob        = require('glob');
var pickFiles   = require('../broccoli/custom-static-compiler');
var SilentError = require('../errors/silent');

var p                   = require('../preprocessors');
var preprocessJs        = p.preprocessJs;
var preprocessCss       = p.preprocessCss;
var preprocessTemplates = p.preprocessTemplates;

var CoreObject = require('core-object');

function Addon(project) {
  this.project = project;
  this.registry = p.setupRegistry(this);

  if (!this.name) {
    throw new SilentError('An addon must define a `name` property.');
  }
}

Addon.__proto__ = CoreObject;
Addon.prototype.constructor = Addon;

Addon.prototype._requireBuildPackages = function() {
  this.compileES6  = this.compileES6 || require('broccoli-es6-concatenator');
  this.mergeTrees  = this.mergeTrees || require('broccoli-merge-trees');
  this.jshintTrees = this.jshintTrees|| require('broccoli-jshint');
  this.concatFiles = this.concatFiles|| require('broccoli-concat');
  this.fileMover   = this.fileMover  || require('broccoli-file-mover');
};

Addon.prototype._unwatchedTreeGenerator = function unwatchedTree(dir) {
  return {
    read:    function() { return dir; },
    cleanup: function() { }
  };
};

Addon.prototype.isDevelopingAddon = function() {
  return process.env.EMBER_ADDON_ENV === 'development';
};

Addon.prototype.treeGenerator = function(dir) {
  var tree;
  if (this.isDevelopingAddon()) {
    tree = dir;
  } else {
    tree = this._unwatchedTreeGenerator(dir);
  }

  return tree;
};

Addon.prototype.treePaths = {
  app:               'app',
  styles:            'app/styles',
  templates:         'app/templates',
  addon:             'addon',
  'addon-styles':    'addon/styles',
  'addon-templates': 'addon/templates',
  vendor:            'vendor',
  'test-support':    'test-support'
};

Addon.prototype.treeFor = function treeFor(name) {
  this._requireBuildPackages();

  var tree;
  var trees = [];

  if (tree = this._treeFor(name)) {
    trees.push(tree);
  }

  if (this.isDevelopingAddon() && this.app.hinting && name === 'app') {
    trees.push(this.jshinting());
  }

  return this.mergeTrees(trees);
};

Addon.prototype._treeFor = function _treeFor(name) {
  var treePath = path.join(this.root, this.treePaths[name]);
  var tree;

  if (fs.existsSync(treePath)) {
    tree = this.treeGenerator(treePath);

    if (name === 'addon') {
      tree = this.treeForAddon(tree);
    }
  }

  return tree;
};

Addon.prototype.included = function(app) {
  this.app = app;
};

Addon.prototype.includedModules = function() {
  if (this._includedModules) {
    return this._includedModules;
  }

  var moduleName = this.moduleName();
  var treePath   = path.join(this.root, this.treePaths['addon']);

  this._includedModules = glob.sync(path.join(treePath, '**/*.js')).reduce(function(ignoredModules, filePath) {
    ignoredModules[filePath.replace(treePath, moduleName).slice(0, -3)] = ['default'];
    return ignoredModules;
  }, {});

  return this._includedModules;
};

Addon.prototype.treeForAddon = function(tree) {
  this._requireBuildPackages();

  var addonTree = this.compileAddon(tree);
  var stylesTree = this.compileStyles(this._treeFor('addon-styles'));
  var templatesTree = this.compileTemplates(this._treeFor('addon-templates'));

  var jsTree = this.concatFiles(this.mergeTrees([addonTree, templatesTree].filter(Boolean)), {
    inputFiles: ['*.js', '**/*.js'],
    outputFile: '/' + this.name + '.js',
    allowNone: true
  });

  return this.mergeTrees([jsTree, stylesTree].filter(Boolean));
};

Addon.prototype.compileStyles = function(tree) {
  this._requireBuildPackages();

  if (tree) {
    var styleFiles = pickFiles(tree, {
      srcDir: '/styles',
      destDir: '/'
    });
    var processedStyles = preprocessCss(styleFiles, '/', '/', {
      registry: this.registry
    });
    return this.fileMover(processedStyles, {
      srcFile: '/' + this.app.name + '.css',
      destFile: '/' + this.name + '.css'
    });
  }
};

Addon.prototype.compileTemplates = function(tree) {
  this._requireBuildPackages();

  if (tree) {
    var standardTemplates = this.pickFiles(tree, {
      srcDir: '/',
      destDir: this.name + '/templates'
    });

    var podTemplates = this.pickFiles(tree, {
      srcDir: '/',
      files: ['**/template.*'],
      destDir: this.name + '/',
      allowEmpty: true
    });

    return preprocessTemplates(this.mergeTrees([standardTemplates, podTemplates]), {
      registry: this.registry
    });
  }
};

Addon.prototype.compileAddon = function(tree) {
  this._requireBuildPackages();

  if (Object.keys(this.includedModules()).length === 0) {
    return;
  }

  var addonJs = this.addonJsFiles(tree);

  var es6Tree = this.compileES6(addonJs, {
    ignoredModules: Object.keys(this.app.importWhitelist),
    inputFiles: [this.name + '/**/*.js'],
    wrapInEval: this.app.options.wrapInEval,
    outputFile: '/' + this.name + '.js'
  });

  this.app.importWhitelist = assign(this.app.importWhitelist, this.includedModules());

  return es6Tree;
};

Addon.prototype.jshinting = function() {
  this._requireBuildPackages();

  var addonJs = this.addonJsFiles('addon');
  var jshintedAddon = this.jshintTrees(addonJs, {
    jshintrcPath: this.app.options.jshintrc.app,
    description: 'JSHint - Addon'
  });
  return this.pickFiles(jshintedAddon, {
    srcDir: '/',
    destDir: this.name + '/tests/'
  });
};

Addon.prototype.addonJsFiles = function(tree) {
  var files = pickFiles(tree, {
    srcDir: '/',
    files: ['**/*.js'],
    destDir: this.name,
    allowEmpty: true
  });

  return preprocessJs(files, '/', this.name, {
    registry: this.registry
  });
};

Addon.prototype.moduleName = function() {
  return this.name.toLowerCase().replace(/\s/g, '-');
};

Addon.prototype.blueprintsPath = function() {
  var blueprintPath = path.join(this.root, 'blueprints');

  if (fs.existsSync(blueprintPath)) {
    return blueprintPath;
  }
};

Addon.resolvePath = function(addon) {
  var addonMain;

  deprecate(addon.pkg.name + ' is using the deprecated ember-addon-main definition. It should be updated to {\'ember-addon\': {\'main\': \'' + addon.pkg['ember-addon-main'] + '\'}}', addon.pkg['ember-addon-main']);

  addonMain = addon.pkg['ember-addon-main'] || addon.pkg['ember-addon'].main || 'index.js';

  // Resolve will fail unless it has an extension
  if(!path.extname(addonMain)) {
    addonMain += '.js';
  }

  return path.resolve(addon.path, addonMain);
};

Addon.lookup = function(addon) {
  var Constructor, addonModule, modulePath, moduleDir;

  modulePath = Addon.resolvePath(addon);
  moduleDir  = path.dirname(modulePath);

  if (fs.existsSync(modulePath)) {
    addonModule = require(modulePath);

    if (typeof addonModule === 'function') {
      Constructor = addonModule;
      Constructor.prototype.root = Constructor.prototype.root || moduleDir;
    } else {
      Constructor = Addon.extend(assign({root: moduleDir}, addonModule));
    }
  } else {
    Constructor = Addon.extend({
      name: '(generated ' + addon.pkg.name + ' addon)',
      root: moduleDir
    });
  }

  return Constructor;
};

module.exports = Addon;

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014-2020 Bjoern Kimminich.
 * SPDX-License-Identifier: MIT
 */

const models = require('../models/index')

module.exports.getAddress = function getAddress () {
  return async (req, res, next) => {
    const addresses = await models.Address.findAll({ where: { UserId: req.body.UserId } })
    res.status(200).json({ status: 'success', data: addresses })
  }
}

module.exports.getAddressById = function getAddressById () {
  return async (req, res, next) => {
    const address = await models.Address.findOne({ where: { id: req.params.id, UserId: req.body.UserId } })
    if (address) {
      res.status(200).json({ status: 'success', data: address })
    } else {
      res.status(400).json({ status: 'error', data: 'Malicious activity detected.' })
    }
  }
}

module.exports.delAddressById = function delAddressById () {
  return async (req, res, next) => {
    const address = await models.Address.destroy({ where: { id: req.params.id, UserId: req.body.UserId } })
    if (address) {
      res.status(200).json({ status: 'success', data: 'Address deleted successfully.' })
    } else {
      res.status(400).json({ status: 'error', data: 'Malicious activity detected.' })
    }
  }
}
<commit_msg>Will this be automatically fixed?<commit_after>/*
 * Copyright (c) 2014-2020 Bjoern Kimminich.
 * SPDX-License-Identifier: MIT
 */

const models = require('../models/index')

module.exports.getAddress = function getAddress () {
  return async (req, res, next) => {
    const addresses =  await models.Address.findAll({ where: { UserId: req.body.UserId } })
    res.status(200).json({ status: 'success', data: addresses })
  }
}

module.exports.getAddressById = function getAddressById () {
  return async (req, res, next) => {
    const address = await models.Address.findOne({ where: { id: req.params.id, UserId: req.body.UserId } })
    if (address) {
      res.status(200).json({ status: 'success', data: address })
    } else {
      res.status(400).json({ status: 'error', data: 'Malicious activity detected.' })
    }
  }
}

module.exports.delAddressById = function delAddressById () {
  return async (req, res, next) => {
    const address = await models.Address.destroy({ where: { id: req.params.id, UserId: req.body.UserId } })
    if (address) {
      res.status(200).json({ status: 'success', data: 'Address deleted successfully.' })
    } else {
      res.status(400).json({ status: 'error', data: 'Malicious activity detected.' })
    }
  }
}
<|endoftext|>


<commit_before>var path = require( 'path' )
  , dbModules = [ 'orm', 'odm' ]
  , moduleLoader = require( 'utils' ).moduleLoader.getInstance()
  , models = {};

modules.forEach( function( moduleName ) {
  if ( moduleLoader.moduleIsEnabled( moduleName ) ) {
    models[ type ] = {};
    moduleLoader.modules.forEach( function( theModule ) {
        Object.keys( theModule.models[ type ] ).forEach( function( key ) {
            models[ type ][ key ] = theModule.models[ type ][ key ];
            models[ type ][ key ][ type.toUpperCase() ] = true;
        });
    });
  }
});

console.dir( models );

module.exports = models;<commit_msg>Fixing up require( 'models ')<commit_after>var path = require( 'path' )
  , dbModules = [ 'orm', 'odm' ]
  , moduleLoader = require( 'utils' ).moduleLoader.getInstance()
  , models = {};

dbModules.forEach( function( type ) {
  if ( moduleLoader.moduleIsEnabled( type ) ) {
    models[ type ] = {};
    moduleLoader.modules.forEach( function( theModule ) {
        Object.keys( theModule.models[ type ] ).forEach( function( key ) {
            models[ type ][ key ] = theModule.models[ type ][ key ];
            models[ type ][ key ][ type.toUpperCase() ] = true;
        });
    });
  }
});

module.exports = models;<|endoftext|>


<commit_before>module.exports = function(req, res) {
  var MAX_REMIXES = 5;
  var make = require("../lib/makeapi");

  function renderError(message) {
    return res.render("details.html", {error:message});
  }

  // Use a URL in the querystring or an ID
  var searchOptions = {},
      searchCriteria;
  if ( req.query.id ) {
    searchCriteria = "id";
    searchOptions.id = req.query.id;
  } else if ( req.query.url ) {
    searchCriteria = "url";
    searchOptions.url = decodeURIComponent( req.query.url );
  } else {
    return renderError("No URL or ID was passed");
  }

  make.find(searchOptions).process( function( err, data ) {
    if ( err ) {
      return renderError("Looks like there is a problem with the make API");
    }
    if ( data && !data.length ) {
      return renderError("No make was found :(");
    }
    var makeData = data[ 0 ];

    // Prep remixes, max of 10
    makeData.remixes( function( err, remixData ) {
      if ( err ) {
        return renderError("Looks like there is a problem with the make API");
      }
      makeData.remixList = [];

      for ( var i = 0; i < Math.min( remixData.length, MAX_REMIXES ); i++ ) {
        makeData.remixList.push({
          url: remixData[ i ].url,
          username: remixData[ i ].username
        });
      }

      if ( remixData.length >= MAX_REMIXES ) {
        makeData.remixCount = remixData.length + "+ remixes";
      } else if ( remixData.length > 1 ) {
        makeData.remixCount = remixData.length + " remixes";
      } else if ( remixData.length === 1 ) {
        makeData.remixCount = "1 remix";
      }

      // Prep original source
      if ( makeData.remixedFrom ) {
        make[ searchCriteria ]( makeData.remixedFrom ).then( function( err, remixedFromData ) {
          if ( err ) {
            return renderError( "Looks like there is a problem with the make API" );
          }

          if ( remixedFromData && remixedFromData.length ) {
            makeData.remixedFromData = {};
            makeData.remixedFromData.url = remixedFromData[ 0 ].url;
            makeData.remixedFromData.username = remixedFromData[ 0 ].username;
          }
          res.render( "details.html", makeData );
        });
      } else {
        res.render( "details.html", makeData );
      }
     });
  });
};

<commit_msg>Fix Bug 870054 - Implement accurate remix count<commit_after>module.exports = function(req, res) {
  var MAX_REMIXES = 5;
  var make = require("../lib/makeapi");

  function renderError(message) {
    return res.render("details.html", {error:message});
  }

  // Use a URL in the querystring or an ID
  var searchOptions = {},
      searchCriteria;
  if ( req.query.id ) {
    searchCriteria = "id";
    searchOptions.id = req.query.id;
  } else if ( req.query.url ) {
    searchCriteria = "url";
    searchOptions.url = decodeURIComponent( req.query.url );
  } else {
    return renderError("No URL or ID was passed");
  }

  make.find(searchOptions).process( function( err, data ) {
    if ( err ) {
      return renderError("Looks like there is a problem with the make API");
    }
    if ( data && !data.length ) {
      return renderError("No make was found :(");
    }
    var makeData = data[ 0 ];

    // Prep remixes, max of 10
    makeData.remixes( function( err, remixData, totalHits ) {
      if ( err ) {
        return renderError("Looks like there is a problem with the make API");
      }
      makeData.remixList = [];

      for ( var i = 0; i < Math.min( remixData.length, MAX_REMIXES ); i++ ) {
        makeData.remixList.push({
          url: remixData[ i ].url,
          username: remixData[ i ].username
        });
      }

      if ( totalHits === 1 ) {
        makeData.remixCount = "1 remix";
      } else {
        makeData.remixCount = totalHits + " remixes";
      }

      // Prep original source
      if ( makeData.remixedFrom ) {
        make[ searchCriteria ]( makeData.remixedFrom ).then( function( err, remixedFromData ) {
          if ( err ) {
            return renderError( "Looks like there is a problem with the make API" );
          }

          if ( remixedFromData && remixedFromData.length ) {
            makeData.remixedFromData = {};
            makeData.remixedFromData.url = remixedFromData[ 0 ].url;
            makeData.remixedFromData.username = remixedFromData[ 0 ].username;
          }
          res.render( "details.html", makeData );
        });
      } else {
        res.render( "details.html", makeData );
      }
     });
  });
};

<|endoftext|>


<commit_before>/*
 * npm.js: Simple utilities for working with npm.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var npm = require('npm'),
    npmout = require('npm/lib/utils/output'),
    npmls = require('npm/lib/utils/read-installed'),
    haibu = require('../../haibu');

function logApp(app, message) {
  return [app.user, app.name, message].join(':')
}

var npmConfig = {
  _exit: false,
  exit: false,
  'unsafe-perm': true
};

//
// Monkey patch `npmout.write()` so that we don't need log or out files
//
npmout.write = function () {
  var args = Array.prototype.slice.call(arguments),
      message = '',
      callback;

  args.forEach(function (arg) {
    if (typeof arg === 'function') {
      callback = arg;
    }
    else {
      message += arg;
    }
  });

  haibu.emit('npm:output', 'info', { info: message });
  callback();
};
//
// ### function load (callback)
// #### @callback {function} Continuation to respond to when complete.
// Loads npm with the default `npmConfig`.
//
exports.load = function (callback) {
  haibu.emit('npm:load', 'info', haibu.utils.clone(npmConfig));
  npm.load(npmConfig, function (err) {
    if (err) {
      haibu.emit('npm:load', 'error', { error: err.message });
      return callback(err);
    }

    haibu.emit('npm:load:success', 'silly');
    callback();
  });
};

//
// ### function loadDependencies (callback)
// #### @app {Object} Application to load dependencies for
// #### @callback {function} Continuation to pass control back to when complete.
// Loads npm and the dependencies for the target `app`
//
exports.loadDependencies = function (app, callback) {
  var self = this;
  exports.load(function (err) {
    if (err) {
      return callback(err);
    }

    if (typeof app.dependencies === 'undefined' || Object.keys(app.dependencies).length === 0) {
      haibu.emit(logApp(app, 'npm:install:none'), 'info', { app: app.name });
      return callback(null, true, []);
    }

    var dependencies = Object.keys(app.dependencies);
    haibu.emit(logApp(app, 'npm:install:load'), 'info', { app: app.name, dependencies: dependencies });
    callback(null, dependencies);
  });
};

//
// ### function install (dir, target, callback)
// #### @dir {string} Directory to install targets into.
// #### @target {Object|Array} Target dependencies or application to install.
// #### @callback {function} Continuation to pass control back to when complete.
// Install the `target` dependencies, either an Array of dependencies or a package.json
// manifest with potential dependencies.
//
exports.install = function (dir, target, callback) {
  if (!dir) {
    return callback(new Error('Cannot install npm dependencies without a target directory.'));
  }

  var meta = {};

  //
  // Install all dependencies into the target directory
  //
  function installAll(deps) {
    npm.commands.install(dir, deps, function (err) {
      if (err) {
        return callback(err);
      }

      haibu.emit('npm:install:success', 'info', meta);
      callback(null, deps);
    });
  }

  //
  // Loads all dependencies for the `app` manifest and then installs
  // them into the target directory.
  //
  function loadAppAndInstall(app) {
    exports.loadDependencies(target, function (err, dependencies) {
      if (err) {
        return callback(err);
      }
      else if (dependencies === true) {
        return callback(null, []);
      }

      meta = {
        app: target.name,
        dependencies: dependencies
      };

      haibu.emit('npm:install:start', 'info', meta);
      installAll(dependencies);
    });
  }

  //
  // Load npm and install the raw list of dependencies
  //
  function loadAndInstall() {
    meta = { packages: target };
    exports.load(function (err) {
      if (err) {
        return callback(err);
      }

      installAll(target);
    });
  }

  return Array.isArray(target)
    ? loadAndInstall()
    : loadAppAndInstall();
};

//
// ### function list (dir, app, callback)
// #### @dir {string} Directory to install targets into.
// #### @app {Object} Application to list dependencies for.
// #### @callback {function} Continuation to pass control back to when complete.
//
//
exports.list = function (dir, app, callback) {
  exports.loadDependencies(app, function (err, dependencies) {
    if (err) {
      return callback(err);
    }
    else if (dependencies === true) {
      return callback(null, true, []);
    }

    var all = dependencies.slice(0);
    haibu.emit(logApp(app, 'npm:list'), 'info', { app: app.name, dependencies: dependencies });
    npmls(dir, function (err, list) {
      if (err) {
        return callback(err);
      }

      callback(null, list && list.dependencies && Object.keys(list.dependencies));
    });
  });
};<commit_msg>[minor] Only invoke the callback if it exists<commit_after>/*
 * npm.js: Simple utilities for working with npm.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var npm = require('npm'),
    npmout = require('npm/lib/utils/output'),
    npmls = require('npm/lib/utils/read-installed'),
    haibu = require('../../haibu');

function logApp(app, message) {
  return [app.user, app.name, message].join(':')
}

var npmConfig = {
  _exit: false,
  exit: false,
  'unsafe-perm': true
};

//
// Monkey patch `npmout.write()` so that we don't need log or out files
//
npmout.write = function () {
  var args = Array.prototype.slice.call(arguments),
      message = '',
      callback;

  args.forEach(function (arg) {
    if (typeof arg === 'function') {
      callback = arg;
    }
    else {
      message += arg;
    }
  });

  haibu.emit('npm:output', 'info', { info: message });

  if (callback) {
    callback();
  }
};
//
// ### function load (callback)
// #### @callback {function} Continuation to respond to when complete.
// Loads npm with the default `npmConfig`.
//
exports.load = function (callback) {
  haibu.emit('npm:load', 'info', haibu.utils.clone(npmConfig));
  npm.load(npmConfig, function (err) {
    if (err) {
      haibu.emit('npm:load', 'error', { error: err.message });
      return callback(err);
    }

    haibu.emit('npm:load:success', 'silly');
    callback();
  });
};

//
// ### function loadDependencies (callback)
// #### @app {Object} Application to load dependencies for
// #### @callback {function} Continuation to pass control back to when complete.
// Loads npm and the dependencies for the target `app`
//
exports.loadDependencies = function (app, callback) {
  var self = this;
  exports.load(function (err) {
    if (err) {
      return callback(err);
    }

    if (typeof app.dependencies === 'undefined' || Object.keys(app.dependencies).length === 0) {
      haibu.emit(logApp(app, 'npm:install:none'), 'info', { app: app.name });
      return callback(null, true, []);
    }

    var dependencies = Object.keys(app.dependencies);
    haibu.emit(logApp(app, 'npm:install:load'), 'info', { app: app.name, dependencies: dependencies });
    callback(null, dependencies);
  });
};

//
// ### function install (dir, target, callback)
// #### @dir {string} Directory to install targets into.
// #### @target {Object|Array} Target dependencies or application to install.
// #### @callback {function} Continuation to pass control back to when complete.
// Install the `target` dependencies, either an Array of dependencies or a package.json
// manifest with potential dependencies.
//
exports.install = function (dir, target, callback) {
  if (!dir) {
    return callback(new Error('Cannot install npm dependencies without a target directory.'));
  }

  var meta = {};

  //
  // Install all dependencies into the target directory
  //
  function installAll(deps) {
    npm.commands.install(dir, deps, function (err) {
      if (err) {
        return callback(err);
      }

      haibu.emit('npm:install:success', 'info', meta);
      callback(null, deps);
    });
  }

  //
  // Loads all dependencies for the `app` manifest and then installs
  // them into the target directory.
  //
  function loadAppAndInstall(app) {
    exports.loadDependencies(target, function (err, dependencies) {
      if (err) {
        return callback(err);
      }
      else if (dependencies === true) {
        return callback(null, []);
      }

      meta = {
        app: target.name,
        dependencies: dependencies
      };

      haibu.emit('npm:install:start', 'info', meta);
      installAll(dependencies);
    });
  }

  //
  // Load npm and install the raw list of dependencies
  //
  function loadAndInstall() {
    meta = { packages: target };
    exports.load(function (err) {
      if (err) {
        return callback(err);
      }

      installAll(target);
    });
  }

  return Array.isArray(target)
    ? loadAndInstall()
    : loadAppAndInstall();
};

//
// ### function list (dir, app, callback)
// #### @dir {string} Directory to install targets into.
// #### @app {Object} Application to list dependencies for.
// #### @callback {function} Continuation to pass control back to when complete.
//
//
exports.list = function (dir, app, callback) {
  exports.loadDependencies(app, function (err, dependencies) {
    if (err) {
      return callback(err);
    }
    else if (dependencies === true) {
      return callback(null, true, []);
    }

    var all = dependencies.slice(0);
    haibu.emit(logApp(app, 'npm:list'), 'info', { app: app.name, dependencies: dependencies });
    npmls(dir, function (err, list) {
      if (err) {
        return callback(err);
      }

      callback(null, list && list.dependencies && Object.keys(list.dependencies));
    });
  });
};<|endoftext|>


<commit_before>module.exports = function(app, auth) {
  var moment = require('moment')
    , Location = require('../models/location')
    , Layer = require('../models/layer')
    , Feature = require('../models/feature')
    , access = require('../access')
    , generate_kml = require('../utilities/generate_kml')
    , async = require('async')
    , fs = require('fs')
    , sys = require('sys')
    , exec = require('child_process').exec;
;

  var p***REMOVED***port = auth.p***REMOVED***port;

// export locations into KML
  app.get(
    '/api/export',
    function(req, res) {

      var userLocations;
      var layerLookup = {};
      var featuresLookup = {};

      var filterTime = req.query.time_filter;
      var filterExportLayers = req.query.export_layers;
      var filterFft = req.query.fft_layer;

      var currentDate = new Date();
      var currentTmpDir = "/tmp/mage-export-" + currentDate.getTime();

      if(!filterExportLayers && !filterFft) {
        return res.send(400, "Error.  Please Select Layer for Export.");
      }

      //BEGIN SERIES FUNCTIONS
      async.series([

        //SERIES FUNCTION 1: Get layers for lookup
        function(done) {
          //get layers for lookup
          Layer.getLayers(function (err, layers) {
            if(err) {
              console.log(err);
              return done(err);
            }
            for (var i in layers) {
              //layerLookup[layers[i].id] = layers[i];
              var layer = layers[i];
              layerLookup[layer.id] = layer;
            }
            done();
          });
          //END get layers for lookup
        },

        //SERIES FUNCTION 2: Get features for lookup
        function(done) {

          if(!filterExportLayers) {
            return done();
          }

          var exportLayerIds = filterExportLayers.split(',');
          async.each(exportLayerIds, function(id, done){
            layer = layerLookup[id];
            Feature.getFeatures(layer, {}, function(featureResponse) {
              if(featureResponse) {
                featuresLookup[id] = featureResponse;
                done();
              }
            });
          },
          function(){
            done();
          });
        },

        //SERIES FUNCTION 3: Get locations for KML export
        function(done) {
          //FFT
          Location.getLocationsWithFilters(req.user, filterTime, 100000, function(err, locationResponse) {
            if(err) {
              console.log(err);
              return done(err);
            }
            userLocations = locationResponse;
            done();
          });
          //FFT
        },

        //SERIES FUNCTION 4: Make tmp staging directory.
        function(done) {
          child = exec("mkdir -p " + currentTmpDir + "/icons", function (error, stdout, stderr) {
            sys.print('stdout: ' + stdout);
            sys.print('stderr: ' + stderr);
            if (error !== null) {
              console.log('exec error: ' + error);
            }
            done();
          });
        },

        //SERIES FUNCTION 5: Copy kml-icons to staging area.
        function(done) {
          child = exec("cp public/img/kml-icons/*.png  " + currentTmpDir + "/icons", function (error, stdout, stderr) {
            sys.print('stdout: ' + stdout);
            sys.print('stderr: ' + stderr);
            if (error !== null) {
              console.log('exec error: ' + error);
            }
            done();
          });
        },

        //SERIES FUNCTION 6: Write the actual KML.
        function(done) {

          var filename = "mage-export-" + currentDate.getTime() + ".kml"
          var stream = fs.createWriteStream(currentTmpDir + "/" + filename);
          stream.once('open', function(fd) {

            //res.writeHead(200,{"Content-Type": "application/vnd.google-earth.kml+xml" ,
            //                   "Content-Disposition": "attachment; filename=MAGE-export.kml"});

            stream.write(generate_kml.generateKMLHeader());
            stream.write(generate_kml.generateKMLDocument());

            //writing requested feature layers
            if(filterExportLayers) {

              var exportLayerIds = filterExportLayers.split(',');
              for(var i in exportLayerIds) {

                var layerId = exportLayerIds[i];
                var layer = layerLookup[layerId];
                var features = featuresLookup[layerId];

                if(layer) {
                  stream.write(generate_kml.generateKMLFolderStart(layer.name));
                  for(var j in features) {
                    feature = features[j];
                    lon = feature.geometry.coordinates[0];
                    lat = feature.geometry.coordinates[1];
                    desc = feature.properties.TYPE;
                    stream.write(generate_kml.generatePlacemark(feature._id, feature.properties.TYPE, lon ,lat ,0, desc));
                  }
                  stream.write(generate_kml.generateKMLFolderClose());
                }
              }
            }

            //writing requested FFT locations
            if(filterFft) {
              for(var i in userLocations) {
                var user = userLocations[i];
                stream.write(generate_kml.generateKMLFolderStart('user: ' + user.user));
                for(var j in user.locations) {
                  var location = user.locations[j];
                  if(location) {
                    lon = location.geometry.coordinates[0];
                    lat = location.geometry.coordinates[1];
                    desc = location.properties.createdOn;
                    stream.write(generate_kml.generatePlacemark('point' + j, 'FFT' , lon ,lat ,0, desc));
                  }
                }
                stream.write(generate_kml.generateKMLFolderClose());
              }
            }
            stream.write(generate_kml.generateKMLDocumentClose());
            stream.end(generate_kml.generateKMLClose());
            done();
          });
        },

        //SERIES FUNCTION 7: Create KMZ
        function(done) {
          child = exec("zip -r " +
                       currentTmpDir + "/mage-export-" + currentDate.getTime() + ".kmz " +
                       currentTmpDir + "/*", function (error, stdout, stderr) {
            sys.print('stdout: ' + stdout);
            sys.print('stderr: ' + stderr);
            if (error !== null) {
              console.log('exec error: ' + error);
            }
            done();
          });
        }

      ],

      //SERIES FUNCTION...EVERYTHING ELSE IS DONE
      function(err) {

        var filename = currentTmpDir + "/mage-export-" + currentDate.getTime() + ".kmz";

        fs.exists(filename, function(exists) {
        if(!exists) {
            //res.writeHead(404, {"Content-Type": "text/plain"});
            //res.write("404 Not Found\n");
            //res.close();
            return;
        }

        fs.readFile(filename, "binary", function(err, file) {
            if(err) {
                //res.writeHead(500, {"Content-Type": "text/plain"});
                //res.write(err + "\n");
                //res.close();
                return;
            }

            res.writeHead(200,{"Content-Type": "application/vnd.google-earth.kml+xml" ,
                               "Content-Disposition": "attachment; filename=mage-export-" + currentDate.getTime() + ".kmz"});

            res.write(file,"binary");
            res.end();
        });
    });

      });
      //END SERIES FUNCTIONS

      //res.end('123');
    }
  );

  //var makeDirectories =

  //var copyIcons

}<commit_msg>code cleanup...<commit_after>module.exports = function(app, auth) {
  var moment = require('moment')
    , Location = require('../models/location')
    , Layer = require('../models/layer')
    , Feature = require('../models/feature')
    , access = require('../access')
    , generate_kml = require('../utilities/generate_kml')
    , async = require('async')
    , fs = require('fs')
    , sys = require('sys')
    , exec = require('child_process').exec;
;

  var p***REMOVED***port = auth.p***REMOVED***port;

// export locations into KML
  app.get(
    '/api/export',
    function(req, res) {

      var userLocations;
      var layerLookup = {};
      var featuresLookup = {};

      var filterTime = req.query.time_filter;
      var filterExportLayers = req.query.export_layers;
      var filterFft = req.query.fft_layer;

      var currentDate = new Date();
      var currentTmpDir = "/tmp/mage-export-" + currentDate.getTime();

      if(!filterExportLayers && !filterFft) {
        return res.send(400, "Error.  Please Select Layer for Export.");
      }

      //BEGIN SERIES FUNCTIONS
      async.series([

        //SERIES FUNCTION 1: Get layers for lookup
        function(done) {
          //get layers for lookup
          Layer.getLayers(function (err, layers) {
            if(err) {
              console.log(err);
              return done(err);
            }
            for (var i in layers) {
              //layerLookup[layers[i].id] = layers[i];
              var layer = layers[i];
              layerLookup[layer.id] = layer;
            }
            done();
          });
          //END get layers for lookup
        },

        //SERIES FUNCTION 2: Get features for lookup
        function(done) {

          if(!filterExportLayers) {
            return done();
          }

          var exportLayerIds = filterExportLayers.split(',');
          async.each(exportLayerIds, function(id, done){
            layer = layerLookup[id];
            Feature.getFeatures(layer, {}, function(featureResponse) {
              if(featureResponse) {
                featuresLookup[id] = featureResponse;
                done();
              }
            });
          },
          function(){
            done();
          });
        },

        //SERIES FUNCTION 3: Get locations for KML export
        function(done) {
          //FFT
          Location.getLocationsWithFilters(req.user, filterTime, 100000, function(err, locationResponse) {
            if(err) {
              console.log(err);
              return done(err);
            }
            userLocations = locationResponse;
            done();
          });
          //FFT
        },

        //SERIES FUNCTION 4: Make tmp staging directory.
        function(done) {
          child = exec("mkdir -p " + currentTmpDir + "/icons", function (error, stdout, stderr) {
            sys.print('stdout: ' + stdout);
            sys.print('stderr: ' + stderr);
            if (error !== null) {
              console.log('exec error: ' + error);
            }
            done();
          });
        },

        //SERIES FUNCTION 5: Copy kml-icons to staging area.
        function(done) {
          child = exec("cp public/img/kml-icons/*.png  " + currentTmpDir + "/icons", function (error, stdout, stderr) {
            sys.print('stdout: ' + stdout);
            sys.print('stderr: ' + stderr);
            if (error !== null) {
              console.log('exec error: ' + error);
            }
            done();
          });
        },

        //SERIES FUNCTION 6: Write the actual KML.
        function(done) {

          var filename = "mage-export-" + currentDate.getTime() + ".kml"
          var stream = fs.createWriteStream(currentTmpDir + "/" + filename);
          stream.once('open', function(fd) {

            //res.writeHead(200,{"Content-Type": "application/vnd.google-earth.kml+xml" ,
            //                   "Content-Disposition": "attachment; filename=MAGE-export.kml"});

            stream.write(generate_kml.generateKMLHeader());
            stream.write(generate_kml.generateKMLDocument());

            //writing requested feature layers
            if(filterExportLayers) {

              var exportLayerIds = filterExportLayers.split(',');
              for(var i in exportLayerIds) {

                var layerId = exportLayerIds[i];
                var layer = layerLookup[layerId];
                var features = featuresLookup[layerId];

                if(layer) {
                  stream.write(generate_kml.generateKMLFolderStart(layer.name));
                  for(var j in features) {
                    feature = features[j];
                    lon = feature.geometry.coordinates[0];
                    lat = feature.geometry.coordinates[1];
                    desc = feature.properties.TYPE;
                    stream.write(generate_kml.generatePlacemark(feature._id, feature.properties.TYPE, lon ,lat ,0, desc));
                  }
                  stream.write(generate_kml.generateKMLFolderClose());
                }
              }
            }

            //writing requested FFT locations
            if(filterFft) {
              for(var i in userLocations) {
                var user = userLocations[i];
                stream.write(generate_kml.generateKMLFolderStart('user: ' + user.user));
                for(var j in user.locations) {
                  var location = user.locations[j];
                  if(location) {
                    lon = location.geometry.coordinates[0];
                    lat = location.geometry.coordinates[1];
                    desc = location.properties.createdOn;
                    stream.write(generate_kml.generatePlacemark('point' + j, 'FFT' , lon ,lat ,0, desc));
                  }
                }
                stream.write(generate_kml.generateKMLFolderClose());
              }
            }
            stream.write(generate_kml.generateKMLDocumentClose());
            stream.end(generate_kml.generateKMLClose());
            done();
          });
        },

        //SERIES FUNCTION 7: Create KMZ
        function(done) {
          child = exec("zip -r " +
                       currentTmpDir + "/mage-export-" + currentDate.getTime() + ".kmz " +
                       currentTmpDir + "/*", function (error, stdout, stderr) {
            sys.print('stdout: ' + stdout);
            sys.print('stderr: ' + stderr);
            if (error !== null) {
              console.log('exec error: ' + error);
            }
            done();
          });
        }
      ],

      //SERIES FUNCTION...EVERYTHING ELSE IS DONE
      function(err) {

        var filename = currentTmpDir + "/mage-export-" + currentDate.getTime() + ".kmz";

        fs.exists(filename, function(exists) {
        if(!exists) {
          res.writeHead(404, {"Content-Type": "text/plain"});
          res.write("404 Not Found\n");
          res.close();
          return;
        }

        fs.readFile(filename, "binary", function(err, file) {
          if(err) {
            res.writeHead(500, {"Content-Type": "text/plain"});
            res.write(err + "\n");
            res.close();
            return;
          }

          res.writeHead(200,{"Content-Type": "application/vnd.google-earth.kml+xml" ,
                             "Content-Disposition": "attachment; filename=mage-export-" + currentDate.getTime() + ".kmz"});
          res.write(file,"binary");
          res.end();
        });
      });
    });}
    //END ASYNCH
  );

}<|endoftext|>


<commit_before>module.exports.DEF_CTRL_METHODS = ['_get', '_post', '_delete', '_put'];
module.exports.DEF_CTRL_NAME = "Ctrl.js";

module.exports.handler = function(ctrl1, file2, server, Hapi){

    this.connect = function(ctrl, file){
        var ctrlWithHandlers = require(ctrl);
        var ctrlname = (file.split(module.exports.DEF_CTRL_NAME)[0]).toLowerCase();
        var handlerPath = ctrlname != 'index' ?  '/' + ctrlname + '/' : '/';

        // load config for controller from controller
        var config = {};
        if(typeof ctrlWithHandlers.$getConfig === 'function') {
            config = ctrlWithHandlers.$getConfig();
        } else if( typeof ctrlWithHandlers.$init === 'function'){
            ctrlWithHandlers.$init(server, Hapi);
        }

        for(var handlerName in ctrlWithHandlers){
            var handlerObject = ctrlWithHandlers[handlerName];
            if(typeof handlerObject === 'function'){
                if(handlerName !== '$init' || handlerName !== '$getConfig'){
                    getMethodAndRegisterRoute(handlerObject, handlerName, handlerPath);
                }
            } else {
                console.error('unknow route ' + handlerName + ' in ' + filePath);
            }
        }
    }

    function getMethodAndRegisterRoute(handlerObject, handlerName, handlerPath) {
        for (var methodIdx = 0; methodIdx <= module.exports.DEF_CTRL_METHODS.length; methodIdx++) {
            if (methodIdx == module.exports.DEF_CTRL_METHODS.length) {
                console.error('unknow method for handler ' + handlerName);

                var handlerMethods = '';
                module.exports.DEF_CTRL_METHODS.forEach(function (idx, val) {
                    handlerMethods += idx + ' '
                });
                console.info('possible methods for handler:' + handlerMethods);
                console.info('like: ' + handlerName + module.exports.DEF_CTRL_METHODS[0]);
                break;
            }

            var methodType = module.exports.DEF_CTRL_METHODS[methodIdx];
            if (handlerName.indexOf(methodType) != -1) {
                var handlerNameFinal = handlerName.split(methodType)[0];
                if (handlerNameFinal != 'index') {
                    handlerPath += handlerNameFinal;
                    //registerRoute(methodType, handlerPath + '/', handlerObject, 'extra?');
                    registerRoute(methodType, handlerPath + '/', handlerObject, '{params*}');
                }
                registerRoute(methodType, handlerPath, handlerObject, '');
                break;
            }
        }
        return {methodIdx: methodIdx, handlerMethods: handlerMethods, methodType: methodType, handlerNameFinal: handlerNameFinal};
    }

    function registerRoute(methodType, handlerPath, shandler, extra){
        //console.log('register' + file + '/' + name);
        var config_handler = {
            handler: shandler
        };

        var setRoute = {
            method : methodType.substr(1),
            path : handlerPath + extra ,
            config : config_handler
        };

        console.log('route ' + setRoute.method + ' ' + setRoute.path)
        // Add the route
        server.addRoute(setRoute);
    }

    this.connect(ctrl1, file2);
}
<commit_msg>parse config and send to controller route<commit_after>module.exports.DEF_CTRL_METHODS = ['_get', '_post', '_delete', '_put'];
module.exports.DEF_CTRL_NAME = "Ctrl.js";
/**
 * /*  Output:

 [{
        HAPPY - not method: 'get',
        HAPPY - not path: '/test/{p}/end',
        settings: {
            handler: [Function],
            method: 'get',
            plugins: {},
            app: {},
            validate: {},
            payload: 'stream',
            auth: undefined,
            cache: [Object] }
    }]
/**
 * http://spumko.github.io/resource/api/#server-route-routes-
 * @type {{auth: boolean, params: string}}
 */
var ctrlConfigDefault = {
    /**
     * authorisation - example 'password'
     */
    auth : false,
    /**
     * params - examples:
     *      {params*}
     *      {name?}
     */
    params : ''
}

function fillUpWithConfig(localConf, upConf){
    var conf = localConf;
    if(!conf){
        conf = {};
    }

    // check just the items whic his default config
    // otherwise can by taken config from localconfig for current handler as well
    for(var prop in ctrlConfigDefault){
        if(typeof conf[prop] === 'undefined'){
            // fill up by upConf or default conf
            conf[prop] = upConf ? upConf[prop] : ctrlConfigDefault[prop];
        }
    }

    return conf;
}

module.exports.handler = function(ctrl1, file2, server, Hapi){

    this.connect = function(ctrl, file){
        var ctrlWithHandlers = require(ctrl);
        var ctrlname = (file.split(module.exports.DEF_CTRL_NAME)[0]).toLowerCase();
        var handlerPath = ctrlname != 'index' ?  '/' + ctrlname + '/' : '/';

        // load config for controller from controller
        var configCtrl = null;
        if(typeof ctrlWithHandlers.$getConfig === 'function') {
            configCtrl = fillUpWithConfig(ctrlWithHandlers.$getConfig());
        } else {
            configCtrl = fillUpWithConfig(null);
        }

        console.log('confgCtrl : ');
        console.log(configCtrl);

        if( typeof ctrlWithHandlers.$init === 'function'){
            ctrlWithHandlers.$init(server, Hapi);
        }

        for(var handlerName in ctrlWithHandlers){
            var handlerObject = ctrlWithHandlers[handlerName];
            if(typeof handlerObject === 'function'){
                if(handlerName !== '$init' || handlerName !== '$getConfig'){
                    // get config for
                    var configHandler = fillUpWithConfig(configCtrl[handlerName], configCtrl);

                    console.log('confgHandler : ');
                    console.log(configHandler);
                    getMethodAndRegisterRoute(handlerObject, handlerName, handlerPath, configHandler);
                }
            } else {
                console.error('unknow route ' + handlerName + ' in ' + filePath);
            }
        }
    }

    function getMethodAndRegisterRoute(handlerObject, handlerName, handlerPath, configHandler) {
        for (var methodIdx = 0; methodIdx <= module.exports.DEF_CTRL_METHODS.length; methodIdx++) {
            if (methodIdx == module.exports.DEF_CTRL_METHODS.length) {
                console.error('unknow method for handler ' + handlerName);

                var handlerMethods = '';
                module.exports.DEF_CTRL_METHODS.forEach(function (idx, val) {
                    handlerMethods += idx + ' '
                });
                console.info('possible methods for handler:' + handlerMethods);
                console.info('like: ' + handlerName + module.exports.DEF_CTRL_METHODS[0]);
                break;
            }

            var methodType = module.exports.DEF_CTRL_METHODS[methodIdx];
            if (handlerName.indexOf(methodType) != -1) {
                var handlerNameFinal = handlerName.split(methodType)[0];
                if (handlerNameFinal != 'index') {
                    handlerPath += handlerNameFinal;
                    //registerRoute(methodType, handlerPath + '/', handlerObject, 'extra?');
                    registerRoute(methodType, handlerPath + '/', handlerObject, '{params*}');
                }
                registerRoute(methodType, handlerPath, handlerObject, '');
                break;
            }
        }
        return {methodIdx: methodIdx, handlerMethods: handlerMethods, methodType: methodType, handlerNameFinal: handlerNameFinal};
    }

    function registerRoute(methodType, handlerPath, shandler, extra){
        //console.log('register' + file + '/' + name);
        var config_handler = {
            handler: shandler
        };

        var setRoute = {
            method : methodType.substr(1),
            path : handlerPath + extra ,
            config : config_handler
        };

        console.log('route ' + setRoute.method + ' ' + setRoute.path)
        // Add the route
        server.addRoute(setRoute);
    }

    this.connect(ctrl1, file2);
}
<|endoftext|>


<commit_before>/*

Copyright 2014, 2015 Roland Bouman (roland.bouman@gmail.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/
var _Event;
(_Event = function(e) {
    if (!e) {
        e = win.event;
    }
    this.browserEvent = e;
    return this;
}).prototype = {
    getType: function(){
      return this.browserEvent.type;
    },
    getTarget: function(){
        if (this.target) return this.target;
        var browserEvent = this.browserEvent;
        var target;
        if (browserEvent.target) {
            target = browserEvent.target;
        }
        else
        if (browserEvent.srcElement) {
            target = browserEvent.srcElement
        }
        else {
            target = null;
            return target;
        }
        if (target.nodeType === 3) {
          target = target.parentNode;
        }
        return target;
    },
    getButton: function(){
        if (doc.attachEvent) {
            switch (this.browserEvent.button) {
                case 1:
                    return 0;
                case 2:
                    return 2;
                case 4:
                    return 1;
            }
        }
        else
        if (doc.addEventListener) {
            return this.browserEvent.button;
        }
        return null;
    },
    getKeyCode: function(){
        return this.browserEvent.keyCode;
    },
    getShiftKey: function(){
        return this.browserEvent.shiftKey;
    },
    getCtrlKey: function(){
        return this.browserEvent.ctrlKey;
    },
    getXY: function(){
        //var p = pos(this.getTarget());
      var touches = this.browserEvent.touches;
      if (touches && touches.length) {
        return {
            x: touches[0].clientX,
            y: touches[0].clientY
        }
      }
      else {
        return {
            x: this.browserEvent.clientX,
            y: this.browserEvent.clientY
        }
      }
    },
    preventDefault: function() {
      if (this.browserEvent.preventDefault) {
        this.browserEvent.preventDefault();
      }
      else {
        this.browserEvent.returnValue = false;
      }
    },
    save: function(){
        var proto = _Event.prototype, savedEvent = new _Event.Saved(), property;
        for (property in proto) {
            if (property.indexOf("get")===0 && iFun(proto[property])) {
                savedEvent[
                    property.substr(3,1).toLowerCase() + property.substr(4)
                ] = this[property]();
            }
        }
        return savedEvent;
    }
};

(_Event.Saved = function() {
}).prototype = {
    destroy: function(){
        for (var p in this) {
            if (this.hasOwnProperty(p)){
                delete this.p;
            }
        }
    }
};

(function(){
var property;
for (property in _Event.prototype) {
    if (property.indexOf("get")===0 && iFun(_Event.prototype[property])) {
        _Event.Saved.prototype[property] = new Function(
            "return this." + property.substr(3,1).toLowerCase() + property.substr(4) + ";"
        )
    }
}
})();

var GlobalEvent = new _Event(null);

_Event.get = function(e) {
    if (!e) e = win.event;
    GlobalEvent.browserEvent = e;
    return GlobalEvent;
};

function listen(node, type, listener, scope) {
  var i, n;
  if (iArr(node)) {
    n = node.length;
    for (i = 0; i < n; i++){
      listen(node[i], type, listener, scope);
    }
    return;
  }
  else
  if (iArr(type)) {
    n = type.length;
    for (i = 0; i < n; i++){
      listen(node, type[i], listener, scope);
    }
    return;
  }
  else
  if (iArr(listener)) {
    n = listener.length;
    for (i = 0; i < n; i++){
      listen(node, type, listener[i], scope);
    }
    return;
  }
  else {
    if (!scope) scope = win;
    if (listener && (node === win || (node = gEl(node)))) {
      if (node.addEventListener) {
          node.addEventListener(type, function(e){
              listener.call(scope, _Event.get(e));
          }, false);
      }
      else
      if (node.attachEvent){
          node.attachEvent("on" + type, function(){
              listener.call(scope, _Event.get(win.event));
          });
      }
    }
    else {
      throw "Couldn't listen to this object";
    }
  }
}

function unlisten(node, type, listener) {
  var method;
  if (iFun(node.removeEventListener)) method = node.removeEventListener;
  else
  if (iFun(node.detachEvent)) method = node.detachEvent;
  if (method) method.call(node, type, listener);
}
<commit_msg>Fixed button detection for IE9.<commit_after>/*

Copyright 2014, 2015 Roland Bouman (roland.bouman@gmail.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/
var _Event;
(_Event = function(e) {
    if (!e) {
        e = win.event;
    }
    this.browserEvent = e;
    return this;
}).prototype = {
    getType: function(){
      return this.browserEvent.type;
    },
    getTarget: function(){
        if (this.target) return this.target;
        var browserEvent = this.browserEvent;
        var target;
        if (browserEvent.target) {
            target = browserEvent.target;
        }
        else
        if (browserEvent.srcElement) {
            target = browserEvent.srcElement
        }
        else {
            target = null;
            return target;
        }
        if (target.nodeType === 3) {
          target = target.parentNode;
        }
        return target;
    },
    getButton: function(){
        if (typeof(doc.addEventListener) === "function") {
            return this.browserEvent.button;
        }
        else
        if (typeof(doc.attachEvent) === "function") {
            switch (this.browserEvent.button) {
                case 1:
                    return 0;
                case 2:
                    return 2;
                case 4:
                    return 1;
            }
        }
        return null;
    },
    getKeyCode: function(){
        return this.browserEvent.keyCode;
    },
    getShiftKey: function(){
        return this.browserEvent.shiftKey;
    },
    getCtrlKey: function(){
        return this.browserEvent.ctrlKey;
    },
    getXY: function(){
        //var p = pos(this.getTarget());
      var touches = this.browserEvent.touches;
      if (touches && touches.length) {
        return {
            x: touches[0].clientX,
            y: touches[0].clientY
        }
      }
      else {
        return {
            x: this.browserEvent.clientX,
            y: this.browserEvent.clientY
        }
      }
    },
    preventDefault: function() {
      if (this.browserEvent.preventDefault) {
        this.browserEvent.preventDefault();
      }
      else {
        this.browserEvent.returnValue = false;
      }
    },
    save: function(){
        var proto = _Event.prototype, savedEvent = new _Event.Saved(), property;
        for (property in proto) {
            if (property.indexOf("get")===0 && iFun(proto[property])) {
                savedEvent[
                    property.substr(3,1).toLowerCase() + property.substr(4)
                ] = this[property]();
            }
        }
        return savedEvent;
    }
};

(_Event.Saved = function() {
}).prototype = {
    destroy: function(){
        for (var p in this) {
            if (this.hasOwnProperty(p)){
                delete this.p;
            }
        }
    }
};

(function(){
var property;
for (property in _Event.prototype) {
    if (property.indexOf("get")===0 && iFun(_Event.prototype[property])) {
        _Event.Saved.prototype[property] = new Function(
            "return this." + property.substr(3,1).toLowerCase() + property.substr(4) + ";"
        )
    }
}
})();

var GlobalEvent = new _Event(null);

_Event.get = function(e) {
    if (!e) e = win.event;
    GlobalEvent.browserEvent = e;
    return GlobalEvent;
};

function listen(node, type, listener, scope) {
  var i, n;
  if (iArr(node)) {
    n = node.length;
    for (i = 0; i < n; i++){
      listen(node[i], type, listener, scope);
    }
    return;
  }
  else
  if (iArr(type)) {
    n = type.length;
    for (i = 0; i < n; i++){
      listen(node, type[i], listener, scope);
    }
    return;
  }
  else
  if (iArr(listener)) {
    n = listener.length;
    for (i = 0; i < n; i++){
      listen(node, type, listener[i], scope);
    }
    return;
  }
  else {
    if (!scope) scope = win;
    if (listener && (node === win || (node = gEl(node)))) {
      if (node.addEventListener) {
          node.addEventListener(type, function(e){
              listener.call(scope, _Event.get(e));
          }, false);
      }
      else
      if (node.attachEvent){
          node.attachEvent("on" + type, function(){
              listener.call(scope, _Event.get(win.event));
          });
      }
    }
    else {
      throw "Couldn't listen to this object";
    }
  }
}

function unlisten(node, type, listener) {
  var method;
  if (iFun(node.removeEventListener)) method = node.removeEventListener;
  else
  if (iFun(node.detachEvent)) method = node.detachEvent;
  if (method) method.call(node, type, listener);
}
<|endoftext|>