<commit_before>/**
 * Structure
 * =========
 *
 * A convenient structure to extend objects from that comes with very common
 * boiler plate methods:
 * - fromObject
 * - fromBr
 * - toBw
 * - fromBuffer
 * - fromFastBuffer
 * - toBuffer
 * - toFastBuffer
 * - fromHex
 * - toHex
 * - fromString
 * - toString
 * - fromJson
 * - toJson
 */
'use strict'
let dependencies = {
  Br: require('./br'),
  Bw: require('./bw')
}

let inject = function (deps) {
  let Br = deps.Br
  let Bw = deps.Bw

  function Struct () {
    if (!(this instanceof Struct)) {
      return new Struct()
    }
  }

  Struct.prototype.fromObject = function (obj) {
    if (!obj) {
      return this
    }
    for (let key of Object.keys(obj)) {
      if (obj[key] !== undefined) {
        this[key] = obj[key]
      }
    }
    return this
  }

  Struct.prototype.fromBr = function (br /* , ...rest*/) {
    if (!(br instanceof Br)) {
      throw new Error('br must be a buffer reader')
    }
    throw new Error('not implemented')
  }

  Struct.prototype.toBw = function (bw /* ...rest*/) {
    throw new Error('not implemented')
  }

  /**
   * It is very often the case that you want to create a bitcoin object from a
   * stream of small buffers rather than from a buffer of the correct length.
   * For instance, if streaming from the network or disk. The genFromBuffers
   * method is a generator which produces an iterator. Use .next(buf) to pass
   * in a small buffer. The iterator will end when it has received enough data
   * to produce the object. In some cases it is able to yield the number of
   * bytes it is expecting, but that is not always known.
   */
  Struct.prototype.genFromBuffers = function * () {
    throw new Error('not implemented')
  }

  /**
   * A convenience method used by from the genFromBuffers* generators.
   * Basically lets you expect a certain number of bytes (len) and keeps
   * yielding until you give it enough. It yields the expected amount
   * remaining, and returns an object containing a buffer of the expected
   * length, and, if any, the remainder buffer.
   */
  Struct.prototype.expect = function * (len, startbuf) {
    let buf = startbuf
    let bw = new Bw()
    let gotlen = 0
    if (startbuf) {
      bw.write(startbuf)
      gotlen += startbuf.length
    }
    let remainderbuf
    while (gotlen < len) {
      let remainderlen = (len - gotlen)
      buf = yield remainderlen
      if (!buf) {
        continue
      }
      bw.write(buf)
      gotlen += buf.length
    }
    buf = bw.toBuffer()
    let overlen = gotlen - len
    remainderbuf = buf.slice(buf.length - overlen, buf.length)
    buf = buf.slice(0, buf.length - overlen)
    return {
      buf: buf,
      remainderbuf: remainderbuf
    }
  }

  /**
   * Convert a buffer into an object, i.e. deserialize the object.
   */
  Struct.prototype.fromBuffer = function (buf /*, ...rest*/) {
    if (!Buffer.isBuffer(buf)) {
      throw new Error('buf must be a buffer')
    }
    let rest = Array.prototype.slice.call(arguments, 1)
    let br = new Br(buf)
    let args = [br].concat(rest)
    return this.fromBr.apply(this, args)
  }

  /**
   * The complement of toFastBuffer - see description for toFastBuffer
   */
  Struct.prototype.fromFastBuffer = function (buf /*, ...rest*/) {
    if (buf.length === 0) {
      return this
    } else {
      return this.fromBuffer.apply(this, arguments)
    }
  }

  /**
   * Convert the object into a buffer, i.e. serialize the object. This method
   * may block the main thread.
   */
  Struct.prototype.toBuffer = function (/* ...rest*/) {
    return this.toBw.apply(this, arguments).toBuffer()
  }

  /**
   * Sometimes the toBuffer method has cryptography and blocks the main thread,
   * and we need a non-blocking way to serialize an object. That is what
   * toFastBuffer is. Of course it defaults to just using toBuffer if an object
   * hasn't implemented it. If your regular toBuffer method blocks, like with
   * Bip32, then you should implement this method to be non-blocking. This
   * method is used to send objects to the workers. i.e., for converting a
   * Bip32 object to a string, we need to encode it as a buffer in a
   * non-blocking manner with toFastBuffer, send it to a worker, then the
   * worker converts it to a string, which is a blocking operation.
   *
   * It is very common to want to convert a blank object to a zero length
   * buffer, so we can transport a blank object to a worker. So that behavior
   * is included by default.
   */
  Struct.prototype.toFastBuffer = function (/* ...rest*/) {
    if (Object.keys(this).length === 0) {
      return new Buffer(0)
    } else {
      return this.toBuffer.apply(this, arguments)
    }
  }

  Struct.prototype.fromHex = function (hex /* , ...rest*/) {
    let rest = Array.prototype.slice.call(arguments, 1)
    let buf
    try {
      buf = new Buffer(hex, 'hex')
    } catch (e) {
      throw new Error('invalid hex string')
    }
    let args = [buf].concat(rest)
    return this.fromBuffer.apply(this, args)
  }

  Struct.prototype.fromFastHex = function (hex /* , ...rest*/) {
    let rest = Array.prototype.slice.call(arguments, 1)
    let buf
    try {
      buf = new Buffer(hex, 'hex')
    } catch (e) {
      throw new Error('invalid hex string')
    }
    let args = [buf].concat(rest)
    return this.fromFastBuffer.apply(this, args)
  }

  Struct.prototype.toHex = function (/* ...rest*/) {
    return this.toBuffer.apply(this, arguments).toString('hex')
  }

  Struct.prototype.toFastHex = function (/* ...rest*/) {
    return this.toFastBuffer.apply(this, arguments).toString('hex')
  }

  Struct.prototype.fromString = function (str/* , ...rest*/) {
    if (typeof str !== 'string') {
      throw new Error('str must be a string')
    }
    return this.fromHex.apply(this, arguments)
  }

  Struct.prototype.toString = function (/* ...rest*/) {
    return this.toHex.apply(this, arguments)
  }

  Struct.prototype.fromJson = function (json/* , ...rest*/) {
    throw new Error('not implemented')
  }

  Struct.prototype.toJson = function (/* ...rest*/) {
    throw new Error('not implemented')
  }

  return Struct
}

inject = require('injecter')(inject, dependencies)
let Struct = inject()
module.exports = Struct
<commit_msg>use class syntax for Struct<commit_after>/**
 * Structure
 * =========
 *
 * A convenient structure to extend objects from that comes with very common
 * boiler plate methods:
 * - fromObject
 * - fromBr
 * - toBw
 * - fromBuffer
 * - fromFastBuffer
 * - toBuffer
 * - toFastBuffer
 * - fromHex
 * - toHex
 * - fromString
 * - toString
 * - fromJson
 * - toJson
 */
'use strict'
let dependencies = {
  Br: require('./br'),
  Bw: require('./bw')
}

let inject = function (deps) {
  let Br = deps.Br
  let Bw = deps.Bw

  class Struct {

    fromObject (obj) {
      if (!obj) {
        return this
      }
      for (let key of Object.keys(obj)) {
        if (obj[key] !== undefined) {
          this[key] = obj[key]
        }
      }
      return this
    }

    fromBr (br) {
      if (!(br instanceof Br)) {
        throw new Error('br must be a buffer reader')
      }
      throw new Error('not implemented')
    }

    toBw (bw) {
      throw new Error('not implemented')
    }

    /**
     * It is very often the case that you want to create a bitcoin object from a
     * stream of small buffers rather than from a buffer of the correct length.
     * For instance, if streaming from the network or disk. The genFromBuffers
     * method is a generator which produces an iterator. Use .next(buf) to pass
     * in a small buffer. The iterator will end when it has received enough data
     * to produce the object. In some cases it is able to yield the number of
     * bytes it is expecting, but that is not always known.
     */
    * genFromBuffers () {
      throw new Error('not implemented')
    }

    /**
     * A convenience method used by from the genFromBuffers* generators.
     * Basically lets you expect a certain number of bytes (len) and keeps
     * yielding until you give it enough. It yields the expected amount
     * remaining, and returns an object containing a buffer of the expected
     * length, and, if any, the remainder buffer.
     */
    * expect (len, startbuf) {
      let buf = startbuf
      let bw = new Bw()
      let gotlen = 0
      if (startbuf) {
        bw.write(startbuf)
        gotlen += startbuf.length
      }
      let remainderbuf
      while (gotlen < len) {
        let remainderlen = (len - gotlen)
        buf = yield remainderlen
        if (!buf) {
          continue
        }
        bw.write(buf)
        gotlen += buf.length
      }
      buf = bw.toBuffer()
      let overlen = gotlen - len
      remainderbuf = buf.slice(buf.length - overlen, buf.length)
      buf = buf.slice(0, buf.length - overlen)
      return {
        buf: buf,
        remainderbuf: remainderbuf
      }
    }

    /**
     * Convert a buffer into an object, i.e. deserialize the object.
     */
    fromBuffer (buf, ...rest) {
      if (!Buffer.isBuffer(buf)) {
        throw new Error('buf must be a buffer')
      }
      let br = new Br(buf)
      let args = [br].concat(rest)
      return this.fromBr.apply(this, args)
    }

    /**
     * The complement of toFastBuffer - see description for toFastBuffer
     */
    fromFastBuffer (buf) {
      if (buf.length === 0) {
        return this
      } else {
        return this.fromBuffer.apply(this, arguments)
      }
    }

    /**
     * Convert the object into a buffer, i.e. serialize the object. This method
     * may block the main thread.
     */
    toBuffer (...rest) {
      return this.toBw.apply(this, rest).toBuffer()
    }

    /**
     * Sometimes the toBuffer method has cryptography and blocks the main thread,
     * and we need a non-blocking way to serialize an object. That is what
     * toFastBuffer is. Of course it defaults to just using toBuffer if an object
     * hasn't implemented it. If your regular toBuffer method blocks, like with
     * Bip32, then you should implement this method to be non-blocking. This
     * method is used to send objects to the workers. i.e., for converting a
     * Bip32 object to a string, we need to encode it as a buffer in a
     * non-blocking manner with toFastBuffer, send it to a worker, then the
     * worker converts it to a string, which is a blocking operation.
     *
     * It is very common to want to convert a blank object to a zero length
     * buffer, so we can transport a blank object to a worker. So that behavior
     * is included by default.
     */
    toFastBuffer () {
      if (Object.keys(this).length === 0) {
        return new Buffer(0)
      } else {
        return this.toBuffer.apply(this, arguments)
      }
    }

    fromHex (hex, ...rest) {
      let buf
      try {
        buf = new Buffer(hex, 'hex')
      } catch (e) {
        throw new Error('invalid hex string')
      }
      let args = [buf].concat(rest)
      return this.fromBuffer.apply(this, args)
    }

    fromFastHex (hex, ...rest) {
      let buf
      try {
        buf = new Buffer(hex, 'hex')
      } catch (e) {
        throw new Error('invalid hex string')
      }
      let args = [buf].concat(rest)
      return this.fromFastBuffer.apply(this, args)
    }

    toHex () {
      return this.toBuffer.apply(this, arguments).toString('hex')
    }

    toFastHex () {
      return this.toFastBuffer.apply(this, arguments).toString('hex')
    }

    fromString (str) {
      if (typeof str !== 'string') {
        throw new Error('str must be a string')
      }
      return this.fromHex.apply(this, arguments)
    }

    toString () {
      return this.toHex.apply(this, arguments)
    }

    fromJson (json) {
      throw new Error('not implemented')
    }

    toJson () {
      throw new Error('not implemented')
    }
  }

  return Struct
}

inject = require('injecter')(inject, dependencies)
let Struct = inject()
module.exports = Struct
<|endoftext|>


<commit_before>'use strict';

/**
 * Set the styles for a template.
 * @param {Object} req HTTP response object.
 * @param {Object} res HTTP request object.
 * @param {Array} templateStyles An array of script objects.
 * @return {Promise} Resolves to an array or styles.
 */
const setTemplateStyles = (req, res, templateStyles) => new Promise((resolve, reject) => {

    const linz = require('../');

    const defaults = [
        {
            href: '//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,400,300,600,700',
            rel: 'stylesheet',
        },
        {
            crossorigin: 'anonymous',
            href: '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css',
            integrity: 'sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u',
            rel: 'stylesheet',

        },
        {
            crossorigin: 'anonymous',
            href: '//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',
            integrity: 'sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN',
            rel: 'stylesheet',
        },
        {
            crossorigin: 'anonymous',
            href: '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css',
            integrity: 'sha256-yMjaV542P+q1RnH6XByCPDfUFhmOafWbeLPmqKh11zo=',
            rel: 'stylesheet',
        },
        {
            href: `${linz.get('admin path')}/public/css/multiselect.min.css`,
            rel: 'stylesheet',
        },
        {
            href: `${linz.get('admin path')}/public/css/noty.css`,
            rel: 'stylesheet',
        },
        {
            href: `${linz.get('admin path')}/public/css/linz.css?v4`,
            rel: 'stylesheet',
        },
    ];

    if (linz.app.locals.adminCSSFile) {
        defaults.push({
            href: linz.app.locals.adminCSSFile,
            rel: 'stylesheet',
        });
    }

    res.locals.styles = [].concat(defaults, templateStyles)
        .filter(style => style !== undefined);

    const customStyles = linz.get('styles');

    if (!customStyles) {
        return resolve(res.locals.styles);
    }

    customStyles(req, res)
        .then(resolve)
        .catch(reject);

});

module.exports = setTemplateStyles;
<commit_msg>Cache bust the linz css<commit_after>'use strict';

/**
 * Set the styles for a template.
 * @param {Object} req HTTP response object.
 * @param {Object} res HTTP request object.
 * @param {Array} templateStyles An array of script objects.
 * @return {Promise} Resolves to an array or styles.
 */
const setTemplateStyles = (req, res, templateStyles) => new Promise((resolve, reject) => {

    const linz = require('../');

    const defaults = [
        {
            href: '//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,400,300,600,700',
            rel: 'stylesheet',
        },
        {
            crossorigin: 'anonymous',
            href: '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css',
            integrity: 'sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u',
            rel: 'stylesheet',

        },
        {
            crossorigin: 'anonymous',
            href: '//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',
            integrity: 'sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN',
            rel: 'stylesheet',
        },
        {
            crossorigin: 'anonymous',
            href: '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css',
            integrity: 'sha256-yMjaV542P+q1RnH6XByCPDfUFhmOafWbeLPmqKh11zo=',
            rel: 'stylesheet',
        },
        {
            href: `${linz.get('admin path')}/public/css/multiselect.min.css`,
            rel: 'stylesheet',
        },
        {
            href: `${linz.get('admin path')}/public/css/noty.css`,
            rel: 'stylesheet',
        },
        {
            href: `${linz.get('admin path')}/public/css/linz.css?v5`,
            rel: 'stylesheet',
        },
    ];

    if (linz.app.locals.adminCSSFile) {
        defaults.push({
            href: linz.app.locals.adminCSSFile,
            rel: 'stylesheet',
        });
    }

    res.locals.styles = [].concat(defaults, templateStyles)
        .filter(style => style !== undefined);

    const customStyles = linz.get('styles');

    if (!customStyles) {
        return resolve(res.locals.styles);
    }

    customStyles(req, res)
        .then(resolve)
        .catch(reject);

});

module.exports = setTemplateStyles;
<|endoftext|>


<commit_before>var tagged = function () {
    //
};

var tags = {
    //
};

var constants = {
    start: '\u001b[',
    sc:    ';',
    end:   'm',
    off:   '\u001b[0m'
};

var ansi = { 'off':         0
           , '0':           0
           , 'unset':       0
           , 'default':     0
           , 'clear':       0
           , 'bold':        1
           , 'b':           1
           , 'bright':      1
           , 'italic':      3
           , 'i':           3
           , 'underline':   4
           , 'u':           4
           , 'blink':       5
           , 'inverse':     7
           , 'hidden':      8
           , 'black':      30
           , 'red':        31
           , 'green':      32
           , 'yellow':     33
           , 'blue':       34
           , 'magenta':    35
           , 'cyan':       36
           , 'white':      37
           , 'bg.black':   40
           , 'bg.red':     41
           , 'bg.green':   42
           , 'bg.yellow':  43
           , 'bg.blue':    44
           , 'bg.magenta': 45
           , 'bg.cyan':    46
           , 'bg.white':   47 };

tagged._tags = tags;
tagged._ansi = ansi;

// name: string
// [style]: styleString ('off')
// [borderLeft] and [borderRight]: string ('' and '')
// [borderStyle]: styleString|'inherit' ('inherit')
// [width]: number (undefined)
// [digits]: number (undefined)
// [base]: number (10)
// [zeros]: true|false (false)
// [plus]: true|false (false)
// [align]: 'left'|'center'|'right' ('left')
// [trim]: true|false (true)
// [overflow]: 'resize'|'hidden'|'ellipsis' ('ellipsis')

tagged.add = function (name, o) {
    o.style = o.style ? tagged.parseStyle(o.style) : tagged.parseStyle('off');

    o.borderLeft = o.borderLeft || '';
    o.borderRight = o.borderRight || '';
    o.borderStyle = o.borderStyle || 'inherit';
    o.borderStyle = (o.borderStyle == 'inherit') ? o.style : o.borderStyle;

    o.borderLeft = o.borderStyle + o.borderLeft + constants.off;
    o.borderRight = o.borderStyle + o.borderRight + constants.off;

    o.base = o.base || 10;
    o.align = o.align || 'left';
    o.trim = (typeof o.trim == 'undefined') ? true : o.trim;
    o.overflow = o.overflow || 'ellipsis';

    tags[name] = o;
};

tagged.remove = function (name) {
    // tags[options.name];
};

tagged.fillString = function (l, c) {
    if (l === 0) {
        return '';
    }
    var l2 = l / 2;
    var r = c;

    while (r.length <= l2) {
        r += r;
    }

    return r + r.substring(0, l - r.length);
};

tagged.format = function () {
    var formatted = '';

    if (arguments.length == 1) {
        if (typeof arguments[0].length !== 'number') {
            var x = arguments[0];

            for (var key in x) {
                var tag      = tags[key]
                  , t        = x[key]
                  , negative = false;

                if (tag) {
                    formatted += tag.borderLeft;

                    formatted += tag.style;

                    if (typeof t == 'number') {
                        if (t < 0) {
                            negative = true;
                            t = Math.abs(t);
                        }

                        t = t.toString(tag.base);

                        var dot = t.indexOf('.');
                        if ((dot >= 0) && tag.digits)
                            t = t.substr(0, dot + 1 + tag.digits);
                    }

                    t = t.toString();
                    t = tag.trim ? t.trim() : t;

                    var w = t.length, width = tag.width || w;
                    w = (negative || tag.plus) ? w + 1 : w;

                    if ((!tag.zeros) || (tag.align == 'center') || (tag.align == 'left') || (w > width))
                        t = (negative ? '-' : '') + ((tag.plus && !negative) ? '+' : '') + t;

                    console.log(w, width);

                    if (w > width) {
                        if (tag.overflow == 'hidden') {
                            if (tag.align == 'right')
                                t = t.substr(w - width, width);
                            else
                                t = t.substr(0, width);
                        } else if (tag.overflow == 'ellipsis') {
                            if (tag.align == 'right')
                                t = '…' + t.substr(w - width - 1, width - 1);
                            else
                                t = t.substr(0, width - 1) + '…';
                        }
                    } else if (w < width) {
                        var d = width - w
                          , c = tag.zeros ? '0' : ' ';

                        if (tag.align == 'right') {
                            t = tagged.fillString(d, c) + t;
                            if (tag.zeros)
                                t = (negative ? '-' : '') + ((tag.plus && !negative) ? '+' : '') + t;
                        } else if (tag.align == 'center') {
                            var fl, fr;
                            fl = fr = Math.floor(d / 2);
                            if ((fl + fr) != d)
                                fl++;

                            t = tagged.fillString(fr, ' ') + t + tagged.fillString(fl, ' ');
                        } else {
                            t += tagged.fillString(d, ' ');
                        }
                    }

                    formatted += t;

                    formatted += constants.off;

                    formatted += tags[key].borderRight;
                    formatted += '\n';
                } else {
                    formatted += x[key] + '\n';
                }
            }
        } else {
            formatted += tagged.format.apply(null, arguments[0]);
        }
    } else if (arguments.length > 1) {
        for (var i = 0, l = arguments.length; i < l; i++)
            formatted += tagged.format(arguments[i]);
    }

    return formatted;
};

tagged.parseColorNumber = function (s) {
    var m = s.match(/(bg\.)?color\((\d{1,3})\)/);
    if (m)
        return (m[1] ? '48;5;' : '38;5;')
             + parseInt(m[2]);
};

tagged.parseHexColor = function (s) {
    var m = s.match(/(bg\.)?hex\(#([\dA-Fa-f]{6})\)/);
    if (m) {
        var rgb = parseInt(m[2], 16)
          , r   = (rgb >> 16) & 0xff
          , g   = (rgb >> 8)  & 0xff
          , b   =  rgb        & 0xff;

        return (m[1] ? '48;2;' : '38;2;')
            + r + ';' + g + ';' + b;
    }
};

/**
 * Parse style string to ansi codes string.
 * @param {string} style
 * @returns {string}
 */
tagged.parseStyle = function (style) {
    style = style || 0;
    style = style + '';

    return constants.start + style.split(',').map(function (x) {
        x = x.trim();
        return tagged.parseHexColor(x) || tagged.parseColorNumber(x) || ansi[x];
    }).join(constants.sc) + constants.end;
};

module.exports = tagged;
<commit_msg>Pre-release<commit_after>var tagged = function () {
    var formatted = tagged.format.apply(null, arguments);
    console.log(formatted);
};

var tags = {
    //
};

var constants = {
    start: '\u001b[',
    sc:    ';',
    end:   'm',
    off:   '\u001b[0m'
};

var ansi = { 'off':         0
           , '0':           0
           , 'unset':       0
           , 'default':     0
           , 'clear':       0
           , 'bold':        1
           , 'b':           1
           , 'bright':      1
           , 'italic':      3
           , 'i':           3
           , 'underline':   4
           , 'u':           4
           , 'blink':       5
           , 'inverse':     7
           , 'hidden':      8
           , 'black':      30
           , 'red':        31
           , 'green':      32
           , 'yellow':     33
           , 'blue':       34
           , 'magenta':    35
           , 'cyan':       36
           , 'white':      37
           , 'bg.black':   40
           , 'bg.red':     41
           , 'bg.green':   42
           , 'bg.yellow':  43
           , 'bg.blue':    44
           , 'bg.magenta': 45
           , 'bg.cyan':    46
           , 'bg.white':   47 };

tagged._tags = tags;
tagged._ansi = ansi;

// name: string
// [style]: styleString ('off')
// [borderLeft] and [borderRight]: string ('' and '')
// [borderStyle]: styleString|'inherit' ('inherit')
// [width]: number (undefined)
// [digits]: number (undefined)
// [base]: number (10)
// [zeros]: true|false (false)
// [plus]: true|false (false)
// [align]: 'left'|'center'|'right' ('left')
// [trim]: true|false (true)
// [overflow]: 'resize'|'hidden'|'ellipsis' ('ellipsis')

tagged.add = function (name, o) {
    o.style = o.style ? tagged.parseStyle(o.style) : tagged.parseStyle('off');

    o.borderLeft = o.borderLeft || '';
    o.borderRight = o.borderRight || '';
    o.borderStyle = o.borderStyle || 'inherit';
    o.borderStyle = (o.borderStyle == 'inherit') ? o.style : o.borderStyle;

    o.borderLeft = o.borderStyle + o.borderLeft + constants.off;
    o.borderRight = o.borderStyle + o.borderRight + constants.off;

    o.base = o.base || 10;
    o.align = o.align || 'left';
    o.trim = (typeof o.trim == 'undefined') ? true : o.trim;
    o.overflow = o.overflow || 'ellipsis';

    tags[name] = o;
};

tagged.remove = function (name) {
    // tags[options.name];
};

tagged.fillString = function (l, c) {
    if (l === 0) {
        return '';
    }
    var l2 = l / 2;
    var r = c;

    while (r.length <= l2) {
        r += r;
    }

    return r + r.substring(0, l - r.length);
};

tagged.format = function () {
    var formatted = '';

    if (arguments.length == 1) {
        if (typeof arguments[0].length !== 'number') {
            var x = arguments[0];

            for (var key in x) {
                var tag      = tags[key]
                  , t        = x[key]
                  , negative = false;

                if (tag) {
                    formatted += tag.borderLeft;

                    formatted += tag.style;

                    if (typeof t == 'number') {
                        if (t < 0) {
                            negative = true;
                            t = Math.abs(t);
                        }

                        t = t.toString(tag.base);

                        var dot = t.indexOf('.');
                        if ((dot >= 0) && tag.digits)
                            t = t.substr(0, dot + 1 + tag.digits);
                    }

                    t = t.toString();
                    t = tag.trim ? t.trim() : t;

                    var w = t.length, width = tag.width || w;
                    w = (negative || tag.plus) ? w + 1 : w;

                    if ((!tag.zeros) || (tag.align == 'center') || (tag.align == 'left') || (w > width))
                        t = (negative ? '-' : '') + ((tag.plus && !negative) ? '+' : '') + t;

                    if (w > width) {
                        if (tag.overflow == 'hidden') {
                            if (tag.align == 'right')
                                t = t.substr(w - width, width);
                            else
                                t = t.substr(0, width);
                        } else if (tag.overflow == 'ellipsis') {
                            if (tag.align == 'right')
                                t = '…' + t.substr(w - width - 1, width - 1);
                            else
                                t = t.substr(0, width - 1) + '…';
                        }
                    } else if (w < width) {
                        var d = width - w
                          , c = tag.zeros ? '0' : ' ';

                        if (tag.align == 'right') {
                            t = tagged.fillString(d, c) + t;
                            if (tag.zeros)
                                t = (negative ? '-' : '') + ((tag.plus && !negative) ? '+' : '') + t;
                        } else if (tag.align == 'center') {
                            var fl, fr;
                            fl = fr = Math.floor(d / 2);
                            if ((fl + fr) != d)
                                fl++;

                            t = tagged.fillString(fr, ' ') + t + tagged.fillString(fl, ' ');
                        } else {
                            t += tagged.fillString(d, ' ');
                        }
                    }

                    formatted += t;

                    formatted += constants.off;

                    formatted += tags[key].borderRight;
                    formatted += '\n';
                } else {
                    formatted += x[key] + '\n';
                }
            }
        } else {
            formatted += tagged.format.apply(null, arguments[0]);
        }
    } else if (arguments.length > 1) {
        for (var i = 0, l = arguments.length; i < l; i++)
            formatted += tagged.format(arguments[i]);
    }

    return formatted;
};

tagged.parseColorNumber = function (s) {
    var m = s.match(/(bg\.)?color\((\d{1,3})\)/);
    if (m)
        return (m[1] ? '48;5;' : '38;5;')
             + parseInt(m[2]);
};

tagged.parseHexColor = function (s) {
    var m = s.match(/(bg\.)?hex\(#([\dA-Fa-f]{6})\)/);
    if (m) {
        var rgb = parseInt(m[2], 16)
          , r   = (rgb >> 16) & 0xff
          , g   = (rgb >> 8)  & 0xff
          , b   =  rgb        & 0xff;

        return (m[1] ? '48;2;' : '38;2;')
            + r + ';' + g + ';' + b;
    }
};

/**
 * Parse style string to ansi codes string.
 * @param {string} style
 * @returns {string}
 */
tagged.parseStyle = function (style) {
    style = style || 0;
    style = style + '';

    return constants.start + style.split(',').map(function (x) {
        x = x.trim();
        return tagged.parseHexColor(x) || tagged.parseColorNumber(x) || ansi[x];
    }).join(constants.sc) + constants.end;
};

module.exports = tagged;
<|endoftext|>


<commit_before>'use strict';

var ERROR_CODE = 'Terror codes collision detected in the %name%&.extendCodes call for code "%code%"';

var has = Object.prototype.hasOwnProperty;

/**
 * @constructor
 * @param {String|Number} [code=Terror.CODES.UNKNOWN_ERROR]
 * @param {String} [message]
 * @returns {Terror}
 * @example
 *      ```
 *      var MyError = Terror.create('MyError', {
 *          MY_FAULT: "It\'s my own fault, because %reason%"
 *      });
 *
 *      try {
 *          // dangerous code here
 *      } catch(err) {
 *          MyError.createError(MyError.CODES.MY_FAULT, err)
 *              .bind({ reason: 'something strange happens!' })
 *              .log();
 *      }
 *
 *      // try to use Terror#ensureError if catched error can be Terror successor or not
 *
 *      try {
 *          // dangerous code here
 *      } catch(err) {
 *          MyError.ensureError(err, MyError.CODES.MY_FAULT)
 *              .bind({ reason: 'i was sad when write code above' })
 *              .log();
 *      }
 *
 *      // or simply log and throw Terror
 *
 *      throw MyError.createError(MyError.CODES.MY_FAULT, { reason: 'i was too stupid!' })
 *          .log('warn');
 *      ```
 */
function Terror(code, message) {
    var msg;
    var original;

    this.code = code == null ? Terror.CODES.UNKNOWN_ERROR : code;

    if (isString(message)) {
        msg = message;
    } else {
        msg = this.constructor.MESSAGES[this.code];

        if (isError(message)) {
            original = message;
        }
    }

    this.data = {};
    this.message = msg;
    this.originalError = original;
    this._isTerror = true;
    this._isLogged = false;

    return captureStackTrace(this, this.constructor);
}

inherits(Terror, Error);

module.exports = Terror;

/**
 *
 * @type {String}
 * @default 'ERROR'
 */
Terror.DEFAULT_ERROR_LEVEL = 'ERROR';

/**
 *
 * @type {Object}
 */
Terror.CODES = {
    UNKNOWN_ERROR: 'UNKNOWN_ERROR'
};

/**
 *
 * @type {Object}
 */
Terror.MESSAGES = {
    UNKNOWN_ERROR: 'Unknown error'
};

/**
 *
 * @type {Number}
 * @default 10
 */
Terror.stackTraceLimit = 10;

/**
 * @param {String} name Error class name
 * @param {Object} [codes] hash { ERROR_CODE: 'error message', … }
 */
Terror.create = function(name, codes) {
    var Inheritor = function(code, message) {
        Terror.call(this, code, message);
    };

    inherits(Inheritor, this);

    // link contructors methods
    Inheritor.create = this.create;
    Inheritor.extendCodes = this.extendCodes;
    Inheritor.is = this.is;
    Inheritor.setLogger = this.setLogger;
    Inheritor.createError = this.createError;
    Inheritor.ensureError = this.ensureError;
    Inheritor.stackTraceLimit = this.stackTraceLimit;

    // copy static fields
    Inheritor.CODES = copyPlainObject(this.CODES);
    Inheritor.MESSAGES = copyPlainObject(this.MESSAGES);
    Inheritor.DEFAULT_ERROR_LEVEL = this.DEFAULT_ERROR_LEVEL;

    if (isObject(codes)) {
        Inheritor.extendCodes(codes);
    }

    Inheritor.prototype.name = name;

    return Inheritor;
};

/**
 * Extends existing CODE and MESSAGE hashes.
 * @param {Object} codes { CODE_NAME: 'error message', … }
 * @throws {Terror} TerrorError if collisions detected.
 * @returns {Terror} constructor
 */
Terror.extendCodes = function(codes) {
    for (var code in codes) {
        if (has.call(codes, code)) {
            if (has.call(this.CODES, code)) {
                throw Terror.createError(null, ERROR_CODE).bind({
                    name: this.prototype.name,
                    code: code
                });
            }

            this.CODES[code] = code;
            this.MESSAGES[code] = codes[code];
        }
    }

    return this;
};

/**
 * @param {String|Number} [code]
 * @param {String|Error|Object} [message] error message, Error or key-value hash for binding
 * @returns {Terror} new Terror instance
 */
Terror.createError = function(code, message) {
    var Const = this === Terror ? Terror : this;
    var msg;
    var data;

    if (isString(message) || isError(message)) {
        msg = message;
    } else {
        data = message;
    }

    var error = new Const(code, msg).bind(data);

    return captureStackTrace(error, this.createError);
};

/**
 * @param {Error|Terror} error
 * @param {String|Number} [code]
 * @returns {Terror}
 */
Terror.ensureError = function(error, code) {
    return error instanceof this ? error : this.createError(code, error);
};

/**
 * @param {*} error
 * @returns {Boolean}
 */
Terror.isTerror = function(error) {
    if ( ! error) {
        return false;
    } else {
        return error._isTerror === true;
    }
};

/**
 * @param {Function} logger (String message, String errorLevel)
 * @returns {Terror} constructor
 */
Terror.setLogger = function(logger) {
    this.prototype.logger = logger;

    return this;
};

/**
 * @default 'Terror'
 * @type {String}
 */
Terror.prototype.name = 'Terror';

/**
 * @param {*} [level] – error level, any value allowed by logger
 * @returns {Terror} self
 */
Terror.prototype.log = function(level) {
    if (this._isLogged || isNotFunction(this.logger)) {
        return this;
    }

    this.logger(this.getFullStack(), level);
    this._isLogged = true;

    return this;
};

/**
 * Default logger writes error message to console using logMultilineError
 * @param {String} message
 * @param {String} [level=ERROR]
 */
Terror.prototype.logger = function(message, level) {
    this.logMultilineError(message, level);
};

/**
 * Default multiine error formatiing for simple text loggers,
 * such as console.log or any one, which write message as line in the text file.
 * @param {String} message
 * @param {String} [level=ERROR]
 * @param {Function} [log=console.log] (String formattedMessageRow)
 * @returns {Terror}
 */
Terror.prototype.logMultilineError = function(message, level, log) {
    var _level = (level || this.constructor.DEFAULT_ERROR_LEVEL).toUpperCase();
    var _log = log;
    var arrows = '\n' + new Array(_level.length + 1).join('>') + ' ';

    if (isNotFunction(_log)) {
        _log = defaultLog;
    }

    _log(_level + ' ' + message.replace(/\n/g, arrows));

    return this;
};

/**
 *
 * @returns {String}
 */
Terror.prototype.getFullMessage = function() {
    var error = this;
    var result = '';
    var msg;

    do {
        msg = error.message;

        if (msg) {
            if (msg[msg.length - 1] !== '.') {
                msg += '.';
            }

            result += ' ' + msg;
        }

        error = error.originalError;
    } while (error);

    return this.code + result;
};

/**
 *
 * @returns {String}
 */
Terror.prototype.getFullStack = function() {
    var error = this;
    var result = new Array(0);
    var indent = '';
    var stack;

    do {
        if (error.stack) {
            // @see https://nodejs.org/api/errors.html#errors_error_message
            // The message passed to the constructor
            // will also appear in the first line of the stack trace of the Error,
            // however changing this property after the Error object is created
            // may not change the first line of the stack trace
            // (for example, when error.stack is read before this property is changed).
            stack = String(error.stack);
            if (stack.indexOf('%') > -1) {
                // nodejs@8 is affected
                stack = sPrintF(stack, this.data);
            }

            stack = stack.replace(/\n/g, '\n' + indent) + '\n';
        } else {
            stack = error.name + ': ' + error.message;
        }

        result.push(indent + (has.call(error, 'code') ? error.code + ' ' : '') + stack);

        indent += '    ';
    } while ((error = error.originalError));

    return result.join('\n');
};

/**
 * Check is an error instanciated from `Ctor` and error code equals passed code.
 * @param {String} code
 * @param {Error} error
 * @returns {Boolean}
 */
Terror.is = function(code, error) {
    return (error instanceof this) && error.code === code;
};

/**
 * @param {Object} data
 * @returns {Terror} self
 */
Terror.prototype.bind = function(data) {
    if (data == null) {
        return this;
    }

    for (var propName in data) {
        if (has.call(data, propName)) {
            this.data[propName] = data[propName];
        }
    }

    return this.setMessage(this.message);
};

/**
 *
 * @param {String} message
 * @returns {Terror}
 */
Terror.prototype.setMessage = function(message) {
    this.message = isString(message) && message.indexOf('%') > -1 ? sPrintF(message, this.data) : message;

    return this;
};

function isError(value) {
    return value instanceof Error;
}

function isString(value) {
    return typeof value === 'string';
}

function isObject(value) {
    return typeof value === 'object' && value !== null;
}

function isNotFunction(fnc) {
    return typeof fnc !== 'function';
}

function defaultLog(msg) {
    /* eslint-disable no-console */
    console.log(msg);
    /* eslint-enable no-console */
}

function sPrintF(str, data) {
    return str.replace(/%(\S+?)%/g, function (match, variable) {
        return has.call(data, variable) ? data[variable] : match;
    });
}

function copyPlainObject(src) {
    var object = {};

    for (var key in src) {
        if (has.call(src, key)) {
            object[key] = src[key];
        }
    }

    return object;
}

function captureStackTrace(error, fnc) {
    if (Error.captureStackTrace) {
        var stackTraceLimit = Error.stackTraceLimit;

        Error.stackTraceLimit = error.constructor.stackTraceLimit;
        Error.captureStackTrace(error, fnc);
        Error.stackTraceLimit = stackTraceLimit;
    }

    return error;
}

function inherits(Ctor, SuperCtor) {
    if (Object.create) {
        Ctor.prototype = Object.create(SuperCtor.prototype, {
            constructor: {
                value: Ctor,
                enumerable: false,
                writable: true,
                configurable: true
            }
        });
    } else {
        Const.prototype = SuperCtor.prototype;
        new Const(Ctor);
    }
}

function Const(ctor) {
    this.constructor = ctor;
    ctor.prototype = this;

    Const.prototype = Object.prototype;
}
<commit_msg>Use cached regexp for performance<commit_after>'use strict';

var ERROR_CODE = 'Terror codes collision detected in the %name%&.extendCodes call for code "%code%"';

var has = Object.prototype.hasOwnProperty;

var NEW_LINE_RE = /\n/g;
var TEMPLATE_RE = /%(\S+?)%/g;

/**
 * @constructor
 * @param {String|Number} [code=Terror.CODES.UNKNOWN_ERROR]
 * @param {String} [message]
 * @returns {Terror}
 * @example
 *      ```
 *      var MyError = Terror.create('MyError', {
 *          MY_FAULT: "It\'s my own fault, because %reason%"
 *      });
 *
 *      try {
 *          // dangerous code here
 *      } catch(err) {
 *          MyError.createError(MyError.CODES.MY_FAULT, err)
 *              .bind({ reason: 'something strange happens!' })
 *              .log();
 *      }
 *
 *      // try to use Terror#ensureError if catched error can be Terror successor or not
 *
 *      try {
 *          // dangerous code here
 *      } catch(err) {
 *          MyError.ensureError(err, MyError.CODES.MY_FAULT)
 *              .bind({ reason: 'i was sad when write code above' })
 *              .log();
 *      }
 *
 *      // or simply log and throw Terror
 *
 *      throw MyError.createError(MyError.CODES.MY_FAULT, { reason: 'i was too stupid!' })
 *          .log('warn');
 *      ```
 */
function Terror(code, message) {
    var msg;
    var original;

    this.code = code == null ? Terror.CODES.UNKNOWN_ERROR : code;

    if (isString(message)) {
        msg = message;
    } else {
        msg = this.constructor.MESSAGES[this.code];

        if (isError(message)) {
            original = message;
        }
    }

    this.data = {};
    this.message = msg;
    this.originalError = original;
    this._isTerror = true;
    this._isLogged = false;

    return captureStackTrace(this, this.constructor);
}

inherits(Terror, Error);

module.exports = Terror;

/**
 *
 * @type {String}
 * @default 'ERROR'
 */
Terror.DEFAULT_ERROR_LEVEL = 'ERROR';

/**
 *
 * @type {Object}
 */
Terror.CODES = {
    UNKNOWN_ERROR: 'UNKNOWN_ERROR'
};

/**
 *
 * @type {Object}
 */
Terror.MESSAGES = {
    UNKNOWN_ERROR: 'Unknown error'
};

/**
 *
 * @type {Number}
 * @default 10
 */
Terror.stackTraceLimit = 10;

/**
 * @param {String} name Error class name
 * @param {Object} [codes] hash { ERROR_CODE: 'error message', … }
 */
Terror.create = function(name, codes) {
    var Inheritor = function(code, message) {
        Terror.call(this, code, message);
    };

    inherits(Inheritor, this);

    // link contructors methods
    Inheritor.create = this.create;
    Inheritor.extendCodes = this.extendCodes;
    Inheritor.is = this.is;
    Inheritor.setLogger = this.setLogger;
    Inheritor.createError = this.createError;
    Inheritor.ensureError = this.ensureError;
    Inheritor.stackTraceLimit = this.stackTraceLimit;

    // copy static fields
    Inheritor.CODES = copyPlainObject(this.CODES);
    Inheritor.MESSAGES = copyPlainObject(this.MESSAGES);
    Inheritor.DEFAULT_ERROR_LEVEL = this.DEFAULT_ERROR_LEVEL;

    if (isObject(codes)) {
        Inheritor.extendCodes(codes);
    }

    Inheritor.prototype.name = name;

    return Inheritor;
};

/**
 * Extends existing CODE and MESSAGE hashes.
 * @param {Object} codes { CODE_NAME: 'error message', … }
 * @throws {Terror} TerrorError if collisions detected.
 * @returns {Terror} constructor
 */
Terror.extendCodes = function(codes) {
    for (var code in codes) {
        if (has.call(codes, code)) {
            if (has.call(this.CODES, code)) {
                throw Terror.createError(null, ERROR_CODE).bind({
                    name: this.prototype.name,
                    code: code
                });
            }

            this.CODES[code] = code;
            this.MESSAGES[code] = codes[code];
        }
    }

    return this;
};

/**
 * @param {String|Number} [code]
 * @param {String|Error|Object} [message] error message, Error or key-value hash for binding
 * @returns {Terror} new Terror instance
 */
Terror.createError = function(code, message) {
    var Const = this === Terror ? Terror : this;
    var msg;
    var data;

    if (isString(message) || isError(message)) {
        msg = message;
    } else {
        data = message;
    }

    var error = new Const(code, msg).bind(data);

    return captureStackTrace(error, this.createError);
};

/**
 * @param {Error|Terror} error
 * @param {String|Number} [code]
 * @returns {Terror}
 */
Terror.ensureError = function(error, code) {
    return error instanceof this ? error : this.createError(code, error);
};

/**
 * @param {*} error
 * @returns {Boolean}
 */
Terror.isTerror = function(error) {
    if ( ! error) {
        return false;
    } else {
        return error._isTerror === true;
    }
};

/**
 * @param {Function} logger (String message, String errorLevel)
 * @returns {Terror} constructor
 */
Terror.setLogger = function(logger) {
    this.prototype.logger = logger;

    return this;
};

/**
 * @default 'Terror'
 * @type {String}
 */
Terror.prototype.name = 'Terror';

/**
 * @param {*} [level] – error level, any value allowed by logger
 * @returns {Terror} self
 */
Terror.prototype.log = function(level) {
    if (this._isLogged || isNotFunction(this.logger)) {
        return this;
    }

    this.logger(this.getFullStack(), level);
    this._isLogged = true;

    return this;
};

/**
 * Default logger writes error message to console using logMultilineError
 * @param {String} message
 * @param {String} [level=ERROR]
 */
Terror.prototype.logger = function(message, level) {
    this.logMultilineError(message, level);
};

/**
 * Default multiine error formatiing for simple text loggers,
 * such as console.log or any one, which write message as line in the text file.
 * @param {String} message
 * @param {String} [level=ERROR]
 * @param {Function} [log=console.log] (String formattedMessageRow)
 * @returns {Terror}
 */
Terror.prototype.logMultilineError = function(message, level, log) {
    var _level = (level || this.constructor.DEFAULT_ERROR_LEVEL).toUpperCase();
    var _log = log;
    var arrows = '\n' + new Array(_level.length + 1).join('>') + ' ';

    if (isNotFunction(_log)) {
        _log = defaultLog;
    }

    _log(_level + ' ' + message.replace(NEW_LINE_RE, arrows));

    return this;
};

/**
 *
 * @returns {String}
 */
Terror.prototype.getFullMessage = function() {
    var error = this;
    var result = '';
    var msg;

    do {
        msg = error.message;

        if (msg) {
            if (msg[msg.length - 1] !== '.') {
                msg += '.';
            }

            result += ' ' + msg;
        }

        error = error.originalError;
    } while (error);

    return this.code + result;
};

/**
 *
 * @returns {String}
 */
Terror.prototype.getFullStack = function() {
    var error = this;
    var result = new Array(0);
    var indent = '';
    var stack;

    do {
        if (error.stack) {
            // @see https://nodejs.org/api/errors.html#errors_error_message
            // The message passed to the constructor
            // will also appear in the first line of the stack trace of the Error,
            // however changing this property after the Error object is created
            // may not change the first line of the stack trace
            // (for example, when error.stack is read before this property is changed).
            stack = String(error.stack);
            if (stack.indexOf('%') > -1) {
                // nodejs@8 is affected
                stack = sPrintF(stack, this.data);
            }

            stack = stack.replace(NEW_LINE_RE, '\n' + indent) + '\n';
        } else {
            stack = error.name + ': ' + error.message;
        }

        result.push(indent + (has.call(error, 'code') ? error.code + ' ' : '') + stack);

        indent += '    ';
    } while ((error = error.originalError));

    return result.join('\n');
};

/**
 * Check is an error instanciated from `Ctor` and error code equals passed code.
 * @param {String} code
 * @param {Error} error
 * @returns {Boolean}
 */
Terror.is = function(code, error) {
    return (error instanceof this) && error.code === code;
};

/**
 * @param {Object} data
 * @returns {Terror} self
 */
Terror.prototype.bind = function(data) {
    if (data == null) {
        return this;
    }

    for (var propName in data) {
        if (has.call(data, propName)) {
            this.data[propName] = data[propName];
        }
    }

    return this.setMessage(this.message);
};

/**
 *
 * @param {String} message
 * @returns {Terror}
 */
Terror.prototype.setMessage = function(message) {
    this.message = isString(message) && message.indexOf('%') > -1 ? sPrintF(message, this.data) : message;

    return this;
};

function isError(value) {
    return value instanceof Error;
}

function isString(value) {
    return typeof value === 'string';
}

function isObject(value) {
    return typeof value === 'object' && value !== null;
}

function isNotFunction(fnc) {
    return typeof fnc !== 'function';
}

function defaultLog(msg) {
    /* eslint-disable no-console */
    console.log(msg);
    /* eslint-enable no-console */
}

function sPrintF(str, data) {
    return str.replace(TEMPLATE_RE, function (match, variable) {
        return has.call(data, variable) ? data[variable] : match;
    });
}

function copyPlainObject(src) {
    var object = {};

    for (var key in src) {
        if (has.call(src, key)) {
            object[key] = src[key];
        }
    }

    return object;
}

function captureStackTrace(error, fnc) {
    if (Error.captureStackTrace) {
        var stackTraceLimit = Error.stackTraceLimit;

        Error.stackTraceLimit = error.constructor.stackTraceLimit;
        Error.captureStackTrace(error, fnc);
        Error.stackTraceLimit = stackTraceLimit;
    }

    return error;
}

function inherits(Ctor, SuperCtor) {
    if (Object.create) {
        Ctor.prototype = Object.create(SuperCtor.prototype, {
            constructor: {
                value: Ctor,
                enumerable: false,
                writable: true,
                configurable: true
            }
        });
    } else {
        Const.prototype = SuperCtor.prototype;
        new Const(Ctor);
    }
}

function Const(ctor) {
    this.constructor = ctor;
    ctor.prototype = this;

    Const.prototype = Object.prototype;
}
<|endoftext|>


<commit_before>module.exports = {
  init: function () {
    global.isTest = true

    return (fn, app, title) => {
      const request = require('supertest')
      var port

      try {
        port = require('find-port-sync')()
      } catch (_) {
        port = 62369
      }

      global.DP_TEST_PORT = port

      describe(title || 'WebServer', () => {
        var http

        before(() => {
          http = app.dp.listen(port)

          if (global.__dpModelEngine__.destroyed) {
            global.__dpModelEngine__.registerDsn(app.dp.config.cfg.databaseDsn)
            global.__dpModelEngine__.destroyed = false
          }
        })

        after(() => {
          if (global.__dpModelEngine__ && global.__dpModelEngine__._conn) {
            Object.keys(global.__dpModelEngine__._conn).forEach((key) => {
              global.__dpModelEngine__._conn[key].destroy()
              delete global.__dpModelEngine__._conn[key]
            })
          }

          if (global.__dpSessionEngine__ && global.__dpSessionEngine__.engine) {
            global.__dpSessionEngine__.engine().close()
          }

          global.__dpModelEngine__.destroyed = true

          http.close()
          http = undefined
        })

        fn(() => {
          return request(http)
        })
      })
    }
  }
}
<commit_msg>Assign port first.<commit_after>module.exports = {
  init: function () {
    let port

    try {
      port = require('find-port-sync')()
    } catch (_) {
      port = 62369
    }

    global.DP_TEST_PORT = port
    global.isTest = true

    return (fn, app, title) => {
      const request = require('supertest')

      describe(title || 'WebServer', () => {
        var http

        before(() => {
          http = app.dp.listen(port)

          if (global.__dpModelEngine__.destroyed) {
            global.__dpModelEngine__.registerDsn(app.dp.config.cfg.databaseDsn)
            global.__dpModelEngine__.destroyed = false
          }
        })

        after(() => {
          if (global.__dpModelEngine__ && global.__dpModelEngine__._conn) {
            Object.keys(global.__dpModelEngine__._conn).forEach((key) => {
              global.__dpModelEngine__._conn[key].destroy()
              delete global.__dpModelEngine__._conn[key]
            })
          }

          if (global.__dpSessionEngine__ && global.__dpSessionEngine__.engine) {
            global.__dpSessionEngine__.engine().close()
          }

          global.__dpModelEngine__.destroyed = true

          http.close()
          http = undefined
        })

        fn(() => {
          return request(http)
        })
      })
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>update mockScript<commit_after><|endoftext|>


<commit_before><commit_msg>show#image: fix small bugs and some small changes<commit_after><|endoftext|>


<commit_before>var matchRule = require('./matchRule'),
    getRuleKeys = require('./getRuleKeys'),
    sanitiseRegex = /[#\-\[\]^$*?+{}|]|\.(?!(?:\.)|`)/g;

function sanitise(rule){
    return rule.replace(sanitiseRegex, '\\$&');
}

function createRuleRegex(rule){
    return new RegExp(
        '^' +
        sanitise(rule)
        .replace(/`(?:\\`|[^`])*?\.\.\.`/g, '(.*?)')
        .replace(/`(?:\\`|[^`])*?`/g, '([^/]*?)') +
        '$');
}

function matchUrl(pathname, ruleDefinition){
    var match = pathname.match(ruleDefinition.regex);

    if(!match){
        return;
    }

    var tokens = {};

    for(var i = 0; i < ruleDefinition.keys.length; i++){
        var token = match[i+1];

        if (token) {
            tokens[ruleDefinition.keys[i].replace(/\.\.\.$/, '')] = token;
        }
    }

    return {
        route: ruleDefinition.route,
        rule: ruleDefinition.rule,
        regex: ruleDefinition.regex,
        tokens: tokens
    };
}

function createRouteMatcher(ruleDefinitions){
    return function(pathname){
        for(var i = 0; i < ruleDefinitions.length; i++){
            var match = matchUrl(pathname, ruleDefinitions[i]);

            if(match){
                return match;
            }
        }
    };
}

module.exports = function(route){
    var rules = matchRule(route),
        ruleDefinitions = [];

    if(route == null || !rules){
        throw 'Could not parse route: ' + route;
    }

    for(var i = 0; i < rules.length; i++){
        ruleDefinitions[i] = {
            route: route,
            rule: rules[i],
            keys: getRuleKeys(rules[i]),
            regex: createRuleRegex(rules[i])
        };
    }

    return createRouteMatcher(ruleDefinitions);
};<commit_msg>Removed unnecessary token check<commit_after>var matchRule = require('./matchRule'),
    getRuleKeys = require('./getRuleKeys'),
    sanitiseRegex = /[#\-\[\]^$*?+{}|]|\.(?!(?:\.)|`)/g;

function sanitise(rule){
    return rule.replace(sanitiseRegex, '\\$&');
}

function createRuleRegex(rule){
    return new RegExp(
        '^' +
        sanitise(rule)
        .replace(/`(?:\\`|[^`])*?\.\.\.`/g, '(.*?)')
        .replace(/`(?:\\`|[^`])*?`/g, '([^/]*?)') +
        '$');
}

function matchUrl(pathname, ruleDefinition){
    var match = pathname.match(ruleDefinition.regex);

    if(!match){
        return;
    }

    var tokens = {};

    for(var i = 0; i < ruleDefinition.keys.length; i++){
        tokens[ruleDefinition.keys[i].replace(/\.\.\.$/, '')] = match[i+1];
    }

    return {
        route: ruleDefinition.route,
        rule: ruleDefinition.rule,
        regex: ruleDefinition.regex,
        tokens: tokens
    };
}

function createRouteMatcher(ruleDefinitions){
    return function(pathname){
        for(var i = 0; i < ruleDefinitions.length; i++){
            var match = matchUrl(pathname, ruleDefinitions[i]);

            if(match){
                return match;
            }
        }
    };
}

module.exports = function(route){
    var rules = matchRule(route),
        ruleDefinitions = [];

    if(route == null || !rules){
        throw 'Could not parse route: ' + route;
    }

    for(var i = 0; i < rules.length; i++){
        ruleDefinitions[i] = {
            route: route,
            rule: rules[i],
            keys: getRuleKeys(rules[i]),
            regex: createRuleRegex(rules[i])
        };
    }

    return createRouteMatcher(ruleDefinitions);
};<|endoftext|>


<commit_before><commit_msg>Removing broken ShortLink functions.<commit_after><|endoftext|>


<commit_before><commit_msg>Page is now just a getter.<commit_after><|endoftext|>


<commit_before>var path = require("path");
var webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var loadersByExtension = require("./config/loadersByExtension");
var joinEntry = require("./config/joinEntry");

module.exports = function(options) {
	var entry = {
		main: reactEntry("main")
		// second: reactEntry("Second")
	};
	var loaders = {
		"coffee": "coffee-redux-loader",
		"jsx": options.hotComponents ? ["react-hot-loader", "jsx-loader?harmony"] : "jsx-loader?harmony",
		"json": "json-loader",
		// "js": {
			// loader: "6to5-loader",
			// include: path.join(__dirname, "app")
		// },
		"json5": "json5-loader",
		"txt": "raw-loader",
		"png|jpg|jpeg|gif|svg": "url-loader?limit=10000",
		"woff": "url-loader?limit=100000",
		"ttf|eot": "file-loader",
		"wav|mp3": "file-loader",
		"html": "html-loader",
		"md|markdown": ["html-loader", "markdown-loader"],
	};
	var stylesheetLoaders = {
		"css": "css-loader",
		"less": "css-loader!less-loader",
		"styl": "css-loader!stylus-loader",
		"sass": "css-loader!sass-loader",
	}
	var additionalLoaders = [
		// { test: /some-reg-exp$/, loader: "any-loader" }
	];
	var alias = {

	};
	var aliasLoader = {

	};
	var externals = [

	];
	var modulesDirectories = ["web_modules", "node_modules"];
	var extensions = ["", ".web.js", ".js", ".jsx"];
	var root = path.join(__dirname, "app");
	var publicPath = options.devServer ?
		"http://localhost:2992/_assets/" :
		"/_assets/";
	var output = {
		path: path.join(__dirname, "build", options.prerender ? "prerender" : "public"),
		publicPath: publicPath,
		filename: "[name].js" + (options.longTermCaching && !options.prerender ? "?[chunkhash]" : ""),
		chunkFilename: (options.devServer ? "[id].js" : "[name].js") + (options.longTermCaching && !options.prerender ? "?[chunkhash]" : ""),
		sourceMapFilename: "debugging/[file].map",
		libraryTarget: options.prerender ? "commonjs2" : undefined,
		pathinfo: options.debug,
	};
	var excludeFromStats = [
		/node_modules[\\\/]react(-router)?[\\\/]/,
		/node_modules[\\\/]items-store[\\\/]/
	];
	var plugins = [
		function() {
			if(!options.prerender) {
				this.plugin("done", function(stats) {
					var jsonStats = stats.toJson({
						chunkModules: true,
						exclude: excludeFromStats
					});
					jsonStats.publicPath = publicPath;
					require("fs").writeFileSync(path.join(__dirname, "build", "stats.json"), JSON.stringify(jsonStats));
				});
			}
		},
		new webpack.PrefetchPlugin("react"),
		new webpack.PrefetchPlugin("react/lib/ReactComponentBrowserEnvironment")
	];
	if(options.prerender) {
		aliasLoader["react-proxy$"] = "react-proxy/unavailable";
		externals.push(
			/^react(\/.*)?$/,
			/^reflux(\/.*)?$/,
			"superagent",
			"async"
		);
		plugins.push(new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }));
	}
	if(options.commonsChunk) {
		plugins.push(new webpack.optimize.CommonsChunkPlugin("commons", "commons.js" + (options.longTermCaching && !options.prerender ? "?[chunkhash]" : "")));
	}

	function reactEntry(name) {
		return (options.prerender ? "./config/prerender?" : "./config/app?") + name;
	}
	Object.keys(stylesheetLoaders).forEach(function(ext) {
		var loaders = stylesheetLoaders[ext];
		if(Array.isArray(loaders)) loaders = loaders.join("!");
		if(options.prerender) {
			stylesheetLoaders[ext] = "null-loader";
		} else if(options.separateStylesheet) {
			stylesheetLoaders[ext] = ExtractTextPlugin.extract("style-loader", loaders);
		} else {
			stylesheetLoaders[ext] = "style-loader!" + loaders;
		}
	});
	if(options.separateStylesheet && !options.prerender) {
		plugins.push(new ExtractTextPlugin("[name].css"));
	}
	if(options.minimize) {
		plugins.push(
			new webpack.optimize.UglifyJsPlugin(),
			new webpack.optimize.DedupePlugin(),
			new webpack.DefinePlugin({
				"process.env": {
					NODE_ENV: JSON.stringify("production")
				}
			}),
			new webpack.NoErrorsPlugin()
		);
	}

	return {
		entry: entry,
		output: output,
		target: options.prerender ? "node" : "web",
		module: {
			loaders: loadersByExtension(loaders).concat(loadersByExtension(stylesheetLoaders))
		},
		devtool: options.devtool,
		debug: options.debug,
		resolveLoader: {
			root: path.join(__dirname, "node_modules"),
			alias: aliasLoader
		},
		externals: externals,
		resolve: {
			root: root,
			modulesDirectories: modulesDirectories,
			extensions: extensions,
			alias: alias,
		},
		plugins: plugins,
		devServer: {
			stats: {
				exclude: excludeFromStats
			}
		}
	};
};
<commit_msg>casing<commit_after>var path = require("path");
var webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var loadersByExtension = require("./config/loadersByExtension");
var joinEntry = require("./config/joinEntry");

module.exports = function(options) {
	var entry = {
		main: reactEntry("main"),
		// second: reactEntry("second")
	};
	var loaders = {
		"coffee": "coffee-redux-loader",
		"jsx": options.hotComponents ? ["react-hot-loader", "jsx-loader?harmony"] : "jsx-loader?harmony",
		"json": "json-loader",
		// "js": {
			// loader: "6to5-loader",
			// include: path.join(__dirname, "app")
		// },
		"json5": "json5-loader",
		"txt": "raw-loader",
		"png|jpg|jpeg|gif|svg": "url-loader?limit=10000",
		"woff": "url-loader?limit=100000",
		"ttf|eot": "file-loader",
		"wav|mp3": "file-loader",
		"html": "html-loader",
		"md|markdown": ["html-loader", "markdown-loader"],
	};
	var stylesheetLoaders = {
		"css": "css-loader",
		"less": "css-loader!less-loader",
		"styl": "css-loader!stylus-loader",
		"sass": "css-loader!sass-loader",
	}
	var additionalLoaders = [
		// { test: /some-reg-exp$/, loader: "any-loader" }
	];
	var alias = {

	};
	var aliasLoader = {

	};
	var externals = [

	];
	var modulesDirectories = ["web_modules", "node_modules"];
	var extensions = ["", ".web.js", ".js", ".jsx"];
	var root = path.join(__dirname, "app");
	var publicPath = options.devServer ?
		"http://localhost:2992/_assets/" :
		"/_assets/";
	var output = {
		path: path.join(__dirname, "build", options.prerender ? "prerender" : "public"),
		publicPath: publicPath,
		filename: "[name].js" + (options.longTermCaching && !options.prerender ? "?[chunkhash]" : ""),
		chunkFilename: (options.devServer ? "[id].js" : "[name].js") + (options.longTermCaching && !options.prerender ? "?[chunkhash]" : ""),
		sourceMapFilename: "debugging/[file].map",
		libraryTarget: options.prerender ? "commonjs2" : undefined,
		pathinfo: options.debug,
	};
	var excludeFromStats = [
		/node_modules[\\\/]react(-router)?[\\\/]/,
		/node_modules[\\\/]items-store[\\\/]/
	];
	var plugins = [
		function() {
			if(!options.prerender) {
				this.plugin("done", function(stats) {
					var jsonStats = stats.toJson({
						chunkModules: true,
						exclude: excludeFromStats
					});
					jsonStats.publicPath = publicPath;
					require("fs").writeFileSync(path.join(__dirname, "build", "stats.json"), JSON.stringify(jsonStats));
				});
			}
		},
		new webpack.PrefetchPlugin("react"),
		new webpack.PrefetchPlugin("react/lib/ReactComponentBrowserEnvironment")
	];
	if(options.prerender) {
		aliasLoader["react-proxy$"] = "react-proxy/unavailable";
		externals.push(
			/^react(\/.*)?$/,
			/^reflux(\/.*)?$/,
			"superagent",
			"async"
		);
		plugins.push(new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }));
	}
	if(options.commonsChunk) {
		plugins.push(new webpack.optimize.CommonsChunkPlugin("commons", "commons.js" + (options.longTermCaching && !options.prerender ? "?[chunkhash]" : "")));
	}

	function reactEntry(name) {
		return (options.prerender ? "./config/prerender?" : "./config/app?") + name;
	}
	Object.keys(stylesheetLoaders).forEach(function(ext) {
		var loaders = stylesheetLoaders[ext];
		if(Array.isArray(loaders)) loaders = loaders.join("!");
		if(options.prerender) {
			stylesheetLoaders[ext] = "null-loader";
		} else if(options.separateStylesheet) {
			stylesheetLoaders[ext] = ExtractTextPlugin.extract("style-loader", loaders);
		} else {
			stylesheetLoaders[ext] = "style-loader!" + loaders;
		}
	});
	if(options.separateStylesheet && !options.prerender) {
		plugins.push(new ExtractTextPlugin("[name].css"));
	}
	if(options.minimize) {
		plugins.push(
			new webpack.optimize.UglifyJsPlugin(),
			new webpack.optimize.DedupePlugin(),
			new webpack.DefinePlugin({
				"process.env": {
					NODE_ENV: JSON.stringify("production")
				}
			}),
			new webpack.NoErrorsPlugin()
		);
	}

	return {
		entry: entry,
		output: output,
		target: options.prerender ? "node" : "web",
		module: {
			loaders: loadersByExtension(loaders).concat(loadersByExtension(stylesheetLoaders))
		},
		devtool: options.devtool,
		debug: options.debug,
		resolveLoader: {
			root: path.join(__dirname, "node_modules"),
			alias: aliasLoader
		},
		externals: externals,
		resolve: {
			root: root,
			modulesDirectories: modulesDirectories,
			extensions: extensions,
			alias: alias,
		},
		plugins: plugins,
		devServer: {
			stats: {
				exclude: excludeFromStats
			}
		}
	};
};
<|endoftext|>


<commit_before>// m15_001 marc-655
//
casper.test.begin('m15_001 marc-655 Subjects', 3, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/12439356';
var ENTITY=SERVER+USECASE;
	casper.start(ENTITY, function() {
	test.assertTextExists('Awakening to the great sleep war', 'page title Awakening... found');
	test.assertTextExists('Genre', 'Genre TAG 655');
	test.assertTextExists('Magic Realism (Literature)', 'found Subject Genre Magic Realism');
    }).run(function() {
        test.done();
    });
});
<commit_msg>fixed case on subject test<commit_after>// m15_001 marc-655
//
casper.test.begin('m15_001 marc-655 Subjects', 3, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/12439356';
var ENTITY=SERVER+USECASE;
	casper.start(ENTITY, function() {
	test.assertTextExists('Awakening to the great sleep war', 'page title Awakening... found');
	test.assertTextExists('Genre', 'Genre TAG 655');
	test.assertTextExists('Magic realism (Literature)', 'found Subject Genre Magic Realism');
    }).run(function() {
        test.done();
    });
});
<|endoftext|>


<commit_before>var equalHeights = function (columns) {

	var countOfColumns = [];
	var heightsOfColumns = [];
	var i = 0;

	while (i < columns.length) {
		countOfColumns.push(0);
		i++;
	}
	countOfColumns.forEach.call(columns, function (c, i, a) {
		heightsOfColumns.push([c, a[i].clientHeight]);
	});
	heightsOfColumns.sort(function (a, b) { return a[1] - b[1] });
	console.dir(heightsOfColumns);
}<commit_msg>Works, but an error is outputed in the console.<commit_after>var matchColumnHeight = function (columns) {
	var countOfColumns = [];
	var heightsOfColumns = [];

	for (var i = 0; i < columns.length; i++)
		countOfColumns.push(0);

	countOfColumns.forEach.call(columns, function (c, i, a) {
		heightsOfColumns.push([c, a[i].clientHeight]);
	});

	heightsOfColumns.sort(function (a, b) {
		return b[1] - a[1] });

	for (column in columns)
		columns[column].style.height = heightsOfColumns[0][1] + "px";
}<|endoftext|>


<commit_before>var _ = require('underscore'),
	uds = require('underscore.string');
var prefix = 'wx';

var ObjectList = {
  account: 'wxAccountList',
  follower: 'wxFollowerList'
};

function shouldLogin(req, res, next) {
  if(req.AV.user) {
    next();
  } else if(req.route.method == 'get' && req.route.path == '/admin') {
    res.redirect('/user#signin');
  } else {
    res.status(401).send('您还没有登录！');
  }
}

function filterData(req, res, next) {
  var data = {
    objectName: prefix + uds.classify(req.params.model),
    objectId: req.params.id,
    body: req.body,
    unique: []
  };
  var columns = [];
  switch(req.route.method) {
    case 'get':
      data.body = {
        index: req.query.index || 0,
        size: req.query.size || 10,
        rel: {}
      };
      switch(data.objectName) {
        case ObjectList.follower:
          var account = req.query.rel;
          if(account && _.isString(account)) {
            data.body.rel = {
              objectName: ObjectList.account,
              column: 'account',
              value: account
            }
          }
          break;
        default:
          break;
      }
      break;
    case 'post':
      switch(data.objectName) {
        case ObjectList.account:
          columns = ['sourceid','code','name','type','intro','appid','appSecret','token','encodingAESKey','method'];
          data.unique = ['sourceid'];
          data.body = _.pick(data.body, columns);
          data.body.token = 'wenode.avosapps.com';
          if( _.isEmpty(data.body.sourceid) ) {
            res.status(400).send('原始ID不能为空');
            return;
          }
          break;
        default:
          res.status(400).send('您访问的模型不存在');
          return;
      }
      break;
    case 'put':
      switch(data.objectName) {
        case ObjectList.ac:
          columns = ['intro','appSecret','encodingAESKey','method'];
          data.body = _.pick(data.body, columns);
          break;
        default:
          res.status(400).send('您访问的模型不存在');
          return;
      }
      break;
    case 'delete':
      break;
    default:
      break;
  }
  req.wenode_data = data;
  next();
}

function render(req, res) {
	res.render('main', {
		title: '管理页面',
		main: '

',
		appname: 'admin'
	});
}

function fetchModels(req, res) {
  var data = req.wenode_data;
  var AVObject = AV.Object.extend(data.objectName);
  var query = new AV.Query(AVObject);
  query.equalTo('owner', req.AV.user);
  if(!_.isEmpty(data.body.rel)) {
    var AVRelObject = AV.Object.extend(data.body.rel.objectName),
        relObject = new AVRelObject;
    relObject.id = data.body.rel.value;
    query.equalTo(data.body.rel.column, relObject);
  }
  query.limit(data.body.size);
  query.skip(data.body.index * data.body.size);
  query.ascending('createdAt');
  query.find({
    success: function(results) {
      res.status(200).json(results);
    },
    error: function(err) {
      res.status(500).send(err.message);
    }
  });
}

function createModel(req, res) {
  var data = req.wenode_data;

  var AVObject = AV.Object.extend(data.objectName),
    ACL = new AV.ACL(req.AV.user),
    object = new AVObject;

  ACL.setPublicReadAccess(true);

  object.setACL(ACL);
  data.body.owner = req.AV.user;
  object.set(data.body);

  if(_.isEmpty(data.unique)) {
    object.save(null).then(function(obj) {
      res.status(200).json(obj);
    }, function(err) {
      res.status(500).send(err.message);
    });
  } else {
    var query = new AV.Query(AVObject);
    for(var i in data.unique) {
      var column = data.unique[i];
      query.equalTo(column, data.body[column]);
    }
    query.count().then(function(count){
      if(count > 0) {
        res.status(403).send('违反唯一约束：' + uds.toSentence(data.unique));
      } else {
        object.save(null).then(function(obj) {
          res.status(200).json(obj);
        }, function(err) {
          res.status(500).send(err.message);
        });
      }
    }, function(err){
      res.status(500).send(err.message);
    });
  }
}

function updateModel(req, res) {
  var data = req.wenode_data;

  var AVObject = AV.Object.extend(data.objectName),
    object = new AVObject;
  object.id = data.objectId;
  object.set(data.body);
  object.save(null).then(function(obj) {
    res.status(200).json(obj);
  }, function(err) {
    res.status(500).send(err.message);
  });
}

function destroyModel(req, res) {
  var data = req.wenode_data;
  var AVObject = AV.Object.extend(data.objectName),
    object = new AVObject;
  object.id = data.objectId;
  object.destroy().then(function(obj){
    res.status(200).json(obj);
  }, function(err) {
    res.status(500).send(err.message);
  });
}

module.exports = {
	render: render,
  shouldLogin: shouldLogin,
  filterData: filterData,
	createModel: createModel,
	fetchModels: fetchModels,
	updateModel: updateModel,
	destroyModel: destroyModel
};<commit_msg>修复一个低级bug，及更改提示信息<commit_after>var _ = require('underscore'),
	uds = require('underscore.string');
var prefix = 'wx';

var ObjectList = {
  account: 'wxAccountList',
  follower: 'wxFollowerList'
};

function shouldLogin(req, res, next) {
  if(req.AV.user) {
    next();
  } else if(req.route.method == 'get' && req.route.path == '/admin') {
    res.redirect('/user#signin');
  } else {
    res.status(401).send('您还没有登录！');
  }
}

function filterData(req, res, next) {
  var data = {
    objectName: prefix + uds.classify(req.params.model),
    objectId: req.params.id,
    body: req.body,
    unique: []
  };
  var columns = [];
  switch(req.route.method) {
    case 'get':
      data.body = {
        index: req.query.index || 0,
        size: req.query.size || 10,
        rel: {}
      };
      switch(data.objectName) {
        case ObjectList.follower:
          var account = req.query.rel;
          if(account && _.isString(account)) {
            data.body.rel = {
              objectName: ObjectList.account,
              column: 'account',
              value: account
            }
          }
          break;
        default:
          break;
      }
      break;
    case 'post':
      switch(data.objectName) {
        case ObjectList.account:
          columns = ['sourceid','code','name','type','intro','appid','appSecret','token','encodingAESKey','method'];
          data.unique = ['sourceid'];
          data.body = _.pick(data.body, columns);
          data.body.token = 'wenode.avosapps.com';
          if( _.isEmpty(data.body.sourceid) ) {
            res.status(400).send('原始ID不能为空');
            return;
          }
          break;
        default:
          res.status(400).send('对不起，不支持您请求创建的对象');
          return;
      }
      break;
    case 'put':
      switch(data.objectName) {
        case ObjectList.account:
          columns = ['intro','appSecret','encodingAESKey','method'];
          data.body = _.pick(data.body, columns);
          break;
        case ObjectList.follower:
          columns = ['name','email','phone'];
          data.body = _.pick(data.body, columns);
          break;
        default:
          res.status(400).send('对不起，不支持您请求更新的对象');
          return;
      }
      break;
    case 'delete':
      break;
    default:
      break;
  }
  req.wenode_data = data;
  next();
}

function render(req, res) {
	res.render('main', {
		title: '管理页面',
		main: '

',
		appname: 'admin'
	});
}

function fetchModels(req, res) {
  var data = req.wenode_data;
  var AVObject = AV.Object.extend(data.objectName);
  var query = new AV.Query(AVObject);
  query.equalTo('owner', req.AV.user);
  if(!_.isEmpty(data.body.rel)) {
    var AVRelObject = AV.Object.extend(data.body.rel.objectName),
        relObject = new AVRelObject;
    relObject.id = data.body.rel.value;
    query.equalTo(data.body.rel.column, relObject);
  }
  query.limit(data.body.size);
  query.skip(data.body.index * data.body.size);
  query.ascending('createdAt');
  query.find({
    success: function(results) {
      res.status(200).json(results);
    },
    error: function(err) {
      res.status(500).send(err.message);
    }
  });
}

function createModel(req, res) {
  var data = req.wenode_data;

  var AVObject = AV.Object.extend(data.objectName),
    ACL = new AV.ACL(req.AV.user),
    object = new AVObject;

  ACL.setPublicReadAccess(true);

  object.setACL(ACL);
  data.body.owner = req.AV.user;
  object.set(data.body);

  if(_.isEmpty(data.unique)) {
    object.save(null).then(function(obj) {
      res.status(200).json(obj);
    }, function(err) {
      res.status(500).send(err.message);
    });
  } else {
    var query = new AV.Query(AVObject);
    for(var i in data.unique) {
      var column = data.unique[i];
      query.equalTo(column, data.body[column]);
    }
    query.count().then(function(count){
      if(count > 0) {
        res.status(403).send('违反唯一约束：' + uds.toSentence(data.unique));
      } else {
        object.save(null).then(function(obj) {
          res.status(200).json(obj);
        }, function(err) {
          res.status(500).send(err.message);
        });
      }
    }, function(err){
      res.status(500).send(err.message);
    });
  }
}

function updateModel(req, res) {
  var data = req.wenode_data;

  var AVObject = AV.Object.extend(data.objectName),
    object = new AVObject;
  object.id = data.objectId;
  object.set(data.body);
  object.save(null).then(function(obj) {
    res.status(200).json(obj);
  }, function(err) {
    res.status(500).send(err.message);
  });
}

function destroyModel(req, res) {
  var data = req.wenode_data;
  var AVObject = AV.Object.extend(data.objectName),
    object = new AVObject;
  object.id = data.objectId;
  object.destroy().then(function(obj){
    res.status(200).json(obj);
  }, function(err) {
    res.status(500).send(err.message);
  });
}

module.exports = {
	render: render,
  shouldLogin: shouldLogin,
  filterData: filterData,
	createModel: createModel,
	fetchModels: fetchModels,
	updateModel: updateModel,
	destroyModel: destroyModel
};<|endoftext|>


<commit_before>var request = require('supertest');
var app = require('./mb-logging-api-server');

describe('Requests to the root (/api) path', function() {

  it('Returns a 200 status code', function(done) {

    request(app)
      .get('/api')
      .expect(200)
      .end(function(error) {
        if (error) throw error;
        done();
      });

  });

});

describe('Requests to v1 root (/api/v1) path', function() {

  it('Returns a 200 status code', function(done) {

    request(app)
      .get('/api/v1')
      .expect(200)
      .end(function(error) {
        if (error) throw error;
        done();
      });

  });

});

describe('Requests to v1 imports (/api/v1/imports) path', function() {

  it('Returns a 400 status code when required parameters type, exists, source, origin, processed_timestamp and email or phone or drupal_uid are not defined.', function(done) {

    request(app)
      .post('/api/v1/imports')
      .expect(400)
      .end(function(error) {
        if (error) throw error;
        done();
      });

  });

});
<commit_msg>Add POST response code of 400 for /api/v1/imports/summaries and /api/v1/user/activity<commit_after>var request = require('supertest');
var app = require('./mb-logging-api-server');

describe('Requests to the root (/api) path', function() {

  it('Returns a 200 status code', function(done) {

    request(app)
      .get('/api')
      .expect(200)
      .end(function(error) {
        if (error) throw error;
        done();
      });

  });

});

describe('Requests to v1 root (/api/v1) path', function() {

  it('Returns a 200 status code', function(done) {

    request(app)
      .get('/api/v1')
      .expect(200)
      .end(function(error) {
        if (error) throw error;
        done();
      });

  });

});

describe('Requests to v1 imports (/api/v1/imports) path', function() {

  it('Returns a 400 status code when required parameters type, exists, source, origin, processed_timestamp and email or phone or drupal_uid are not defined.', function(done) {

    request(app)
      .post('/api/v1/imports')
      .expect(400)
      .end(function(error) {
        if (error) throw error;
        done();
      });

  });

});

describe('Requests to v1 imports (/api/v1/imports/summaries) path', function() {

  it('Returns a 400 status code when required parameters type,source, target_CSV_file, signup_count and skipped are not defined.', function(done) {

    request(app)
      .post('/api/v1/imports/summaries')
      .expect(400)
      .end(function(error) {
        if (error) throw error;
        done();
      });

  });

});

describe('Requests to v1 imports (/api/v1/user/activity) path', function() {

  it('Returns a 400 status code when required parameter vote is not defined.', function(done) {

    request(app)
      .post('/api/v1/user/activity')
      .expect(400)
      .end(function(error) {
        if (error) throw error;
        done();
      });

  });

});
<|endoftext|>


<commit_before>var path = require('path');
var autoprefixer = require('autoprefixer');

module.exports = {

  entry: {
    app: [path.resolve(__dirname, '../src/main.js')]
  },

  output: {
    path: path.resolve(__dirname, '../build'),
    publicPath: '/',
    filename: '[name].[hash].js',
    sourceMapFilename: '[name].[hash].js.map',
    chunkFilename: '[id].chunk.js',
  },

  resolve: {
    extensions: ['', '.js', '.html'],
    fallback: [path.join(__dirname, '../node_modules')],
    alias: {
      'src': path.resolve(__dirname, '../src'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components'),
      'state': path.resolve(__dirname, '../src/state'),
      'vue$': 'vue/dist/vue.js'
    }
  },

  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'eslint',
        include: path.resolve(__dirname, '../src'),
        exclude: /node_modules/
      }
    ],

    loaders: [
      {
        test: /\.html$/,
        loader: 'vue-html'
      },

      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      },

      {
        test: /\.(png|jpg|jpeg|gif)$/,
        loader: 'url?prefix=img/&limit=5000'
      },

      {
        test: /\.scss$/,
        loader: 'style!css!postcss!sass?sourceMap'
      },

      {
        test: /\.(ttf|eot|svg)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file'
      },

      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url?prefix=font/&limit=5000&mimetype=application/font-woff'
      }
    ]
  },

  babel: {
    presets: ['es2015'],
    plugins: ['transform-runtime']
  },

  eslint: {
    formatter: require('eslint-friendly-formatter')
  },

  postcss: function() {
    return [autoprefixer];
  }
};
<commit_msg>Switch vue-html-loader to html-loader<commit_after>var path = require('path');
var autoprefixer = require('autoprefixer');

module.exports = {

  entry: {
    app: [path.resolve(__dirname, '../src/main.js')]
  },

  output: {
    path: path.resolve(__dirname, '../build'),
    publicPath: '/',
    filename: '[name].[hash].js',
    sourceMapFilename: '[name].[hash].js.map',
    chunkFilename: '[id].chunk.js',
  },

  resolve: {
    extensions: ['', '.js', '.html'],
    fallback: [path.join(__dirname, '../node_modules')],
    alias: {
      'src': path.resolve(__dirname, '../src'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components'),
      'state': path.resolve(__dirname, '../src/state'),
      'vue$': 'vue/dist/vue.js'
    }
  },

  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'eslint',
        include: path.resolve(__dirname, '../src'),
        exclude: /node_modules/
      }
    ],

    loaders: [
      {
        test: /\.html$/,
        loader: 'html'
      },

      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      },

      {
        test: /\.(png|jpg|jpeg|gif)$/,
        loader: 'url?prefix=img/&limit=5000'
      },

      {
        test: /\.scss$/,
        loader: 'style!css!postcss!sass?sourceMap'
      },

      {
        test: /\.(ttf|eot|svg)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file'
      },

      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url?prefix=font/&limit=5000&mimetype=application/font-woff'
      }
    ]
  },

  babel: {
    presets: ['es2015'],
    plugins: ['transform-runtime']
  },

  eslint: {
    formatter: require('eslint-friendly-formatter')
  },

  postcss: function() {
    return [autoprefixer];
  }
};
<|endoftext|>


<commit_before>var app = angular.module("app", [
  'ngStorage',
  'ngRoute'
]);

var defaultSong = {text:
  "{t:Song Title}\n" +
  "{st:Artist Name}\n" +
  "Verse 1:\n" +
  "Click on the pencil and then copy [Am]paste a song in [C]ChordPro [E]format.\n"
  "Click on [Am]a chord [C]to change it's [E7]position.\n"
};

app.service('service', function($http){

  this.getSong = function(id) {
    if (!id || id == "") {
      return $http.post('/api/song', defaultSong)
    } else {
      return $http.get('/api/song/' + id)
    }
  }

  this.getSongs = function() {
    return $http.get('/api/song')
  }

  this.updateSong = function(songtext) {
    return $http.post('/api/song',songtext)
  }
  this.updateChord = function(chorddef, id) {
    return $http.put('/api/song/' + id,chorddef)
  }

  this.getFretboard = function() {
    return $http.get('/api/fretboard')
  }
  this.updateFretboard = function(chorddef) {
    return $http.post('/api/fretboard',chorddef)
  }
  this.updatePositionId = function(positionId) {
    return $http.put('/api/fretboard',positionId)
  }

});

app.config(function($routeProvider) {
    $routeProvider
      .when('/', { controller:'controller' , templateUrl:'views/song.html'})
      .when('/chord', { controller:'controller' , templateUrl:'views/chord.html'})
      .when('/song/:id', { controller:'controller' , templateUrl:'views/song.html'})
});

app.controller("controller", function($scope, $localStorage, $routeParams, service) {

  $scope.init = function() {

    var id = $routeParams.id;

    service.getSongs()
    .success(function(songs) {
      if (!id || id == "") {
        if (songs != null && songs.length > 0) {
          var length = songs.length - 1;
          id = length.toString();
        }
      }
      service.getSong(id)
      .success(function(song) {
        $scope.song = song;
      });
    });

    service.getFretboard()
    .success(function(fb) {
      $scope.fretboard = fb;
    });
  }

  $scope.filterMutedStrings = function(note) {
      return note.mute;
  }

  $scope.filterExcludeMutedStrings = function(note) {
      return !note.mute;
  }

  $scope.filterBaseFretNotZero = function(chorddef) {
      return chorddef.basefret != 0;
  }

  $scope.updateSong = function() {
    service.updateSong({text:$scope.song.text})
    .success(function(song) {
      $scope.song = song;
    });
  }

  $scope.editChord = function(chordId) {
    var ch = parseInt(chordId);
    if (ch >= 0 && ch < $scope.song.chorddefs.length) {
      service.updateFretboard($scope.song.chorddefs[ch])
      .success(function(fb) {
        $scope.fretboard = fb;
      });
    }
  }

  $scope.selectNote = function(posId) {
    service.updatePositionId({positionId:posId})
    .success(function(fb) {
      $scope.fretboard = fb;
    });
  }

  $scope.updateChord = function() {
    service.updateChord({chorddef:[$scope.fretboard.chorddef]}, $scope.song._id)
    .success(function(song) {
      $scope.song = song;
    });
  }

});
<commit_msg>fixed bug<commit_after>var app = angular.module("app", [
  'ngStorage',
  'ngRoute'
]);

var defaultSong = {text:
  "{t:Song Title}\n" +
  "{st:Artist Name}\n" +
  "Verse 1:\n" +
  "Click on the pencil and then copy [Am]paste a song in [C]ChordPro [E]format.\n" +
  "Click on [Am]a chord [C]to change it's [E7]position.\n"
};

app.service('service', function($http){

  this.getSong = function(id) {
    if (!id || id == "") {
      return $http.post('/api/song', defaultSong)
    } else {
      return $http.get('/api/song/' + id)
    }
  }

  this.getSongs = function() {
    return $http.get('/api/song')
  }

  this.updateSong = function(songtext) {
    return $http.post('/api/song',songtext)
  }
  this.updateChord = function(chorddef, id) {
    return $http.put('/api/song/' + id,chorddef)
  }

  this.getFretboard = function() {
    return $http.get('/api/fretboard')
  }
  this.updateFretboard = function(chorddef) {
    return $http.post('/api/fretboard',chorddef)
  }
  this.updatePositionId = function(positionId) {
    return $http.put('/api/fretboard',positionId)
  }

});

app.config(function($routeProvider) {
    $routeProvider
      .when('/', { controller:'controller' , templateUrl:'views/song.html'})
      .when('/chord', { controller:'controller' , templateUrl:'views/chord.html'})
      .when('/song/:id', { controller:'controller' , templateUrl:'views/song.html'})
});

app.controller("controller", function($scope, $localStorage, $routeParams, service) {

  $scope.init = function() {

    var id = $routeParams.id;

    service.getSongs()
    .success(function(songs) {
      if (!id || id == "") {
        if (songs != null && songs.length > 0) {
          var length = songs.length - 1;
          id = length.toString();
        }
      }
      service.getSong(id)
      .success(function(song) {
        $scope.song = song;
      });
    });

    service.getFretboard()
    .success(function(fb) {
      $scope.fretboard = fb;
    });
  }

  $scope.filterMutedStrings = function(note) {
      return note.mute;
  }

  $scope.filterExcludeMutedStrings = function(note) {
      return !note.mute;
  }

  $scope.filterBaseFretNotZero = function(chorddef) {
      return chorddef.basefret != 0;
  }

  $scope.updateSong = function() {
    service.updateSong({text:$scope.song.text})
    .success(function(song) {
      $scope.song = song;
    });
  }

  $scope.editChord = function(chordId) {
    var ch = parseInt(chordId);
    if (ch >= 0 && ch < $scope.song.chorddefs.length) {
      service.updateFretboard($scope.song.chorddefs[ch])
      .success(function(fb) {
        $scope.fretboard = fb;
      });
    }
  }

  $scope.selectNote = function(posId) {
    service.updatePositionId({positionId:posId})
    .success(function(fb) {
      $scope.fretboard = fb;
    });
  }

  $scope.updateChord = function() {
    service.updateChord({chorddef:[$scope.fretboard.chorddef]}, $scope.song._id)
    .success(function(song) {
      $scope.song = song;
    });
  }

});
<|endoftext|>