<commit_before>define(['js/ui/View', 'js/core/List', 'sprd/entity/FileSystemImage', 'flow', 'xaml!sprd/data/ImageServerDataSource', 'sprd/model/UploadImage', 'sprd/type/UploadDesign'],
    function (View, List, FileSystemImage, flow, ImageServerDataSource, UploadImage, UploadDesign) {

        return View.inherit('sprd.view.ImageUploadClass', {

            defaults: {
                items: List,
                imageWidth: 100,
                displayNotice: true,

                uploadContext: null
            },

            inject: {
                imageServer: ImageServerDataSource
            },

            _initializationComplete: function () {
                this.callBase();

                var self = this;
                this.$.items.bind('add', function () {
                    self.set('displayNotice', self.$.items.size() === 0);
                });

                this.$.items.bind('remove', function () {
                    self.set('displayNotice', self.$.items.size() === 0);
                });

            },

            dragEnter: function () {
                this.addClass('drag-over');
                return false;
            },

            dragOver: function (e) {
                e.preventDefault();
                return false;
            },

            dragExit: function () {
                this.removeClass('drag-over');
                return false;
            },

            dropImage: function (e) {

                this.removeClass('drag-over');
                if (e && e.$) {
                    e = e.$;

                    if (e.dataTransfer && e.dataTransfer.files.length) {
                        for (var i = 0; i < e.dataTransfer.files.length; i++) {
                            this._addAndUploadFile(e.dataTransfer.files[i]);
                        }
                    }
                }

                e.preventDefault();
                e.stopPropagation();
                return false;

            },

            _addAndUploadFile: function (file) {
                var reader = new FileReader();

                var fileSystemImage = new FileSystemImage({
                    file: file
                });

                var uploadDesign = new UploadDesign({
                    image: fileSystemImage,
                    file: file
                });

                reader.onload = function (evt) {
                    fileSystemImage.set('url', evt.target.result);
                };

                reader.readAsDataURL(file);

                this._addUploadDesign(uploadDesign);
                this._upload(uploadDesign);
            },

            _addUploadDesign: function (uploadDesign) {
                this.$.items.add(uploadDesign, 0);
            },

            _upload: function (uploadDesign) {

                var self = this,
                    uploadContext = this.$.uploadContext,
                    imageServer = this.$.imageServer,
                    file = uploadDesign.$.file;

                if (!uploadContext) {
                    uploadDesign.set('state', UploadDesign.State.ERROR);
                    this.log("No upload context set. Cancel upload", "warn");
                    return;
                }

                uploadDesign.set('state', UploadDesign.State.LOADING);

                flow()
                    .seq(function (cb) {
                        uploadContext.fetch(null, cb);
                    })
                    .seq("design", function () {
                        var design = uploadContext.getCollection("designs").createItem();
                        design.set("name", file.name);

                        return design;
                    })
                    .seq(function (cb) {
                        this.vars["design"].save(null, cb);
                    })
                    .seq(function (cb) {
                        var design = this.vars["design"];
                        var uploadImage = imageServer.createEntity(UploadImage, design.$.id);

                        uploadImage.set("file", file);
                        uploadDesign.set({
                            design: design,
                            id: design.$.id
                        });

                        uploadImage.save({
                            xhrBeforeSend: function (xhr) {
                                if (xhr && xhr.upload) {
                                    xhr.upload.onprogress = function (e) {
                                        uploadDesign.set('uploadProgress', 100 / e.total * e.loaded);
                                    }
                                }

                                xhr.onload = function () {
                                    uploadDesign.set('uploadProgress', 100);
                                }

                            }
                        }, cb);
                    })
                    .exec(function (err) {
                        if (!err) {
                            uploadDesign.set('state', UploadDesign.State.LOADED);
                            self.trigger("uploadComplete", {
                                uploadDesign: uploadDesign
                            });
                        } else {
                            self.trigger("uploadError", {
                                error: err,
                                uploadDesign: uploadDesign
                            });
                        }

                    });

            }
        });
    });<commit_msg>fixed upload notice<commit_after>define(['js/ui/View', 'js/core/List', 'sprd/entity/FileSystemImage', 'flow', 'xaml!sprd/data/ImageServerDataSource', 'sprd/model/UploadImage', 'sprd/type/UploadDesign'],
    function (View, List, FileSystemImage, flow, ImageServerDataSource, UploadImage, UploadDesign) {

        return View.inherit('sprd.view.ImageUploadClass', {

            defaults: {
                items: List,
                imageWidth: 100,
                displayNotice: true,

                uploadContext: null
            },

            inject: {
                imageServer: ImageServerDataSource
            },

            _initializationComplete: function () {
                this.callBase();

                var self = this,
                    eventHandler = function () {
                        self.set('displayNotice', self.$.items.size() === 0);
                    };

                this.$.items.bind('add', eventHandler);
                this.$.items.bind('remove', eventHandler);
                this.$.items.bind('reset', eventHandler);

            },

            dragEnter: function () {
                this.addClass('drag-over');
                return false;
            },

            dragOver: function (e) {
                e.preventDefault();
                return false;
            },

            dragExit: function () {
                this.removeClass('drag-over');
                return false;
            },

            dropImage: function (e) {

                this.removeClass('drag-over');
                if (e && e.$) {
                    e = e.$;

                    if (e.dataTransfer && e.dataTransfer.files.length) {
                        for (var i = 0; i < e.dataTransfer.files.length; i++) {
                            this._addAndUploadFile(e.dataTransfer.files[i]);
                        }
                    }
                }

                e.preventDefault();
                e.stopPropagation();
                return false;

            },

            _addAndUploadFile: function (file) {
                var reader = new FileReader();

                var fileSystemImage = new FileSystemImage({
                    file: file
                });

                var uploadDesign = new UploadDesign({
                    image: fileSystemImage,
                    file: file
                });

                reader.onload = function (evt) {
                    fileSystemImage.set('url', evt.target.result);
                };

                reader.readAsDataURL(file);

                this._addUploadDesign(uploadDesign);
                this._upload(uploadDesign);
            },

            _addUploadDesign: function (uploadDesign) {
                this.$.items.add(uploadDesign, 0);
            },

            _upload: function (uploadDesign) {

                var self = this,
                    uploadContext = this.$.uploadContext,
                    imageServer = this.$.imageServer,
                    file = uploadDesign.$.file;

                if (!uploadContext) {
                    uploadDesign.set('state', UploadDesign.State.ERROR);
                    this.log("No upload context set. Cancel upload", "warn");
                    return;
                }

                uploadDesign.set('state', UploadDesign.State.LOADING);

                flow()
                    .seq(function (cb) {
                        uploadContext.fetch(null, cb);
                    })
                    .seq("design", function () {
                        var design = uploadContext.getCollection("designs").createItem();
                        design.set("name", file.name);

                        return design;
                    })
                    .seq(function (cb) {
                        this.vars["design"].save(null, cb);
                    })
                    .seq(function (cb) {
                        var design = this.vars["design"];
                        var uploadImage = imageServer.createEntity(UploadImage, design.$.id);

                        uploadImage.set("file", file);
                        uploadDesign.set({
                            design: design,
                            id: design.$.id
                        });

                        uploadImage.save({
                            xhrBeforeSend: function (xhr) {
                                if (xhr && xhr.upload) {
                                    xhr.upload.onprogress = function (e) {
                                        uploadDesign.set('uploadProgress', 100 / e.total * e.loaded);
                                    }
                                }

                                xhr.onload = function () {
                                    uploadDesign.set('uploadProgress', 100);
                                }

                            }
                        }, cb);
                    })
                    .exec(function (err) {
                        if (!err) {
                            uploadDesign.set('state', UploadDesign.State.LOADED);
                            self.trigger("uploadComplete", {
                                uploadDesign: uploadDesign
                            });
                        } else {
                            self.trigger("uploadError", {
                                error: err,
                                uploadDesign: uploadDesign
                            });
                        }

                    });

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


<commit_before>/*
Language: Bash
Author: vah <vahtenberg@gmail.com>
Contributrors: Benjamin Pannell <contact@sierrasoftworks.com>
Website: https://www.gnu.org/software/bash/
Category: common
*/

export default function(hljs) {
  var VAR = {
    className: 'variable',
    variants: [
      {begin: /\$[\w\d#@][\w\d_]*/},
      {begin: /\$\{(.*?)}/}
    ]
  };
  var SUBST = {
    className: 'subst',
    begin: /\$\(/, end: /\)/,
    contains: [hljs.BACKSLASH_ESCAPE]
  };
  var QUOTE_STRING = {
    className: 'string',
    begin: /"/, end: /"/,
    contains: [
      hljs.BACKSLASH_ESCAPE,
      VAR,
      SUBST
    ]
  };
  SUBST.contains.push(QUOTE_STRING);
  var ESCAPED_QUOTE = {
    className: '',
    begin: /\\"/

  };
  var APOS_STRING = {
    className: 'string',
    begin: /'/, end: /'/
  };
  const ARITHEMETIC = {
    begin: /\$\(\(/,
    end: /\)\)/,
    contains: [
      { begin: /\d+#[0-9a-f]+/, className: "number" },
      hljs.NUMBER_MODE,
      VAR
    ]
  };

  return {
    name: 'Bash',
    aliases: ['sh', 'zsh'],
    lexemes: /\b-?[a-z\._]+\b/,
    keywords: {
      keyword:
        'if then else elif fi for while in do done case esac function',
      literal:
        'true false',
      built_in:
        // Shell built-ins
        // http://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
        'break cd continue eval exec exit export getopts hash pwd readonly return shift test times ' +
        'trap umask unset ' +
        // Bash built-ins
        'alias bind builtin caller command declare echo enable help let local logout mapfile printf ' +
        'read readarray source type typeset ulimit unalias ' +
        // Shell modifiers
        'set shopt ' +
        // Zsh built-ins
        'autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles ' +
        'compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate ' +
        'fc fg float functions getcap getln history integer jobs kill limit log noglob popd print ' +
        'pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit ' +
        'unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof ' +
        'zpty zregexparse zsocket zstyle ztcp',
      _:
        '-ne -eq -lt -gt -f -d -e -s -l -a' // relevance booster
    },
    contains: [
      {
        className: 'meta',
        begin: /^#![^\n]+sh\s*$/,
        relevance: 10
      },
      {
        className: 'function',
        begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/,
        returnBegin: true,
        contains: [hljs.inherit(hljs.TITLE_MODE, {begin: /\w[\w\d_]*/})],
        relevance: 0
      },
      ARITHEMETIC,
      hljs.HASH_COMMENT_MODE,
      QUOTE_STRING,
      ESCAPED_QUOTE,
      APOS_STRING,
      VAR
    ]
  };
}
<commit_msg>(chore) cleanup bash a bit<commit_after>/*
Language: Bash
Author: vah <vahtenberg@gmail.com>
Contributrors: Benjamin Pannell <contact@sierrasoftworks.com>
Website: https://www.gnu.org/software/bash/
Category: common
*/

export default function(hljs) {
  const VAR = {
    className: 'variable',
    variants: [
      {begin: /\$[\w\d#@][\w\d_]*/},
      {begin: /\$\{(.*?)}/}
    ]
  };
  const SUBST = {
    className: 'subst',
    begin: /\$\(/, end: /\)/,
    contains: [hljs.BACKSLASH_ESCAPE]
  };
  const QUOTE_STRING = {
    className: 'string',
    begin: /"/, end: /"/,
    contains: [
      hljs.BACKSLASH_ESCAPE,
      VAR,
      SUBST
    ]
  };
  SUBST.contains.push(QUOTE_STRING);
  const ESCAPED_QUOTE = {
    className: '',
    begin: /\\"/

  };
  const APOS_STRING = {
    className: 'string',
    begin: /'/, end: /'/
  };
  const ARITHMETIC = {
    begin: /\$\(\(/,
    end: /\)\)/,
    contains: [
      { begin: /\d+#[0-9a-f]+/, className: "number" },
      hljs.NUMBER_MODE,
      VAR
    ]
  };
  const SHEBANG = {
    className: 'meta',
    begin: /^#![^\n]+sh\s*$/,
    relevance: 10
  };
  const FUNCTION = {
    className: 'function',
    begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/,
    returnBegin: true,
    contains: [hljs.inherit(hljs.TITLE_MODE, {begin: /\w[\w\d_]*/})],
    relevance: 0
  };

  return {
    name: 'Bash',
    aliases: ['sh', 'zsh'],
    lexemes: /\b-?[a-z\._]+\b/,
    keywords: {
      keyword:
        'if then else elif fi for while in do done case esac function',
      literal:
        'true false',
      built_in:
        // Shell built-ins
        // http://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
        'break cd continue eval exec exit export getopts hash pwd readonly return shift test times ' +
        'trap umask unset ' +
        // Bash built-ins
        'alias bind builtin caller command declare echo enable help let local logout mapfile printf ' +
        'read readarray source type typeset ulimit unalias ' +
        // Shell modifiers
        'set shopt ' +
        // Zsh built-ins
        'autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles ' +
        'compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate ' +
        'fc fg float functions getcap getln history integer jobs kill limit log noglob popd print ' +
        'pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit ' +
        'unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof ' +
        'zpty zregexparse zsocket zstyle ztcp',
      _:
        '-ne -eq -lt -gt -f -d -e -s -l -a' // relevance booster
    },
    contains: [
      SHEBANG,
      FUNCTION,
      ARITHMETIC,
      hljs.HASH_COMMENT_MODE,
      QUOTE_STRING,
      ESCAPED_QUOTE,
      APOS_STRING,
      VAR
    ]
  };
}
<|endoftext|>


<commit_before>'use strict';
/**
 * Provides a unified interface for some
 * specific IO related tasks provided from
 * different modules.
 *
 * 	@module lib/dir
 */
const fs = require('fs-extra');
const emptyDir = require('empty-dir');
const cpr = require('cpr');

// Module API
module.exports = {
  isEmpty: emptyDir.sync,
  copy: cpr,
  clean: fs.emptyDirSync
};
<commit_msg>Remove bogus character in jsdoc<commit_after>'use strict';
/**
 * Provides a unified interface for some
 * specific IO related tasks provided from
 * different modules.
 *
 * @module lib/dir
 */
const fs = require('fs-extra');
const emptyDir = require('empty-dir');
const cpr = require('cpr');

// Module API
module.exports = {
  isEmpty: emptyDir.sync,
  copy: cpr,
  clean: fs.emptyDirSync
};
<|endoftext|>


<commit_before>//Overloaded dox.js

dox = require('dox');

// Overwrite context patterns for Oracle
dox.contextPatternMatchers = [
  //Procedure/Function
  function (str) {
    if (/^\s*(procedure|function)\s+([\w$]+)\s*/.exec(str)) {
      return {
          type: RegExp.$1
        , name: RegExp.$2
        , header: str.split(/\s+(as|is|begin)\s+/gi)[0]

      };
    }
  },

  //Constants
  function (str) {
    if (/^\s*[\w$]+\s+constant\s+/.exec(str)) {
      var
        ret = {
          type : 'constants',
          header : str,
          constants : []
        },
        constantsArr = str.split(';')
      ;

      constantsArr.forEach(function(constant){
        // Comments after constants may still be in the array.
        // As such only allow definitions of constants
        if (/^\s*\w+\s+constant\s+.+:=.+$/gi.test(constant)){
          var
            myConstant = {
              name : '',
              // Remove any "\n" and the begining
              code : constant.replace(/^[\n]*/, '') + ';' //Need to re-append missing ";" since removed with .split
            }
          ;

          /^\s*([\w]+)\s+constant\s+/.exec(constant);
          myConstant.name = RegExp.$1.trim();

          ret.constants.push(myConstant);
        }// if constant
      });//constantsArr.forEach

      return ret;
    }// if constant
  },

  //Types
  function (str) {
    if (/^\s*type\s+/.exec(str)) {
      var
        typesArr = str.split(';'),
        types = [];

      // Added in the typesArr[k] since there's a blank array element at end
      // TODO mdsouza: changet this to base name and code variables
      for(var i = 0; i < typesArr.length && typesArr[i]; i++){
        var myType = {
          name : '',
          // Remove any "\n" and the begining
          code : typesArr[i].replace(/^[\n]*/, '') + ';', //Need to re-append missing ";" since removed with .split
        };

        myType.name = myType.code.match(/\s*type\s+\w+/gi)[0].replace(/^\s*type/gi, '').trim();

        types.push(myType);
      }//typesArr

      return {
          type: 'types'
        , header: str
        , types: types
      };
    }
  }

];

module.exports = dox;
<commit_msg>Fix support for parsing pos files.<commit_after>//Overloaded dox.js

var
  dox = require('dox')
;

// Overwrite context patterns for Oracle
dox.contextPatternMatchers = [
  //Procedure/Function
  function (str) {
    if (/^\s*(procedure|function)\s+([\w$]+)\s*/.exec(str)) {
      return {
          type: RegExp.$1
        , name: RegExp.$2
        // Split on ";" for pks files. This may occur when on JavaDoc fn then another fn without JavaDoc
        , header: str.split(/(\s+(as|is|begin)\s+|;)/gi)[0]
      };
    }
  },

  //Constants
  function (str) {
    if (/^\s*[\w$]+\s+constant\s+/.exec(str)) {
      var
        ret = {
          type : 'constants',
          header : str,
          constants : []
        },
        constantsArr = str.split(';')
      ;

      constantsArr.forEach(function(constant){
        // Comments after constants may still be in the array.
        // As such only allow definitions of constants
        if (/^\s*\w+\s+constant\s+.+:=.+$/gi.test(constant)){
          var
            myConstant = {
              name : '',
              // Remove any "\n" and the begining
              code : constant.replace(/^[\n]*/, '') + ';' //Need to re-append missing ";" since removed with .split
            }
          ;

          /^\s*([\w]+)\s+constant\s+/.exec(constant);
          myConstant.name = RegExp.$1.trim();

          ret.constants.push(myConstant);
        }// if constant
      });//constantsArr.forEach

      return ret;
    }// if constant
  },

  //Types
  function (str) {
    if (/^\s*type\s+/.exec(str)) {
      var
        typesArr = str.split(';'),
        types = [];

      // Added in the typesArr[k] since there's a blank array element at end
      // TODO mdsouza: changet this to base name and code variables
      for(var i = 0; i < typesArr.length && typesArr[i]; i++){
        var myType = {
          name : '',
          // Remove any "\n" and the begining
          code : typesArr[i].replace(/^[\n]*/, '') + ';', //Need to re-append missing ";" since removed with .split
        };

        myType.name = myType.code.match(/\s*type\s+\w+/gi)[0].replace(/^\s*type/gi, '').trim();

        types.push(myType);
      }//typesArr

      return {
          type: 'types'
        , header: str
        , types: types
      };
    }
  }

];

module.exports = dox;
<|endoftext|>


<commit_before>;(function () {
  "use strict";

  var root = this

  var CryptoJS, BigInt, HLP
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = DSA
    CryptoJS = require('../vendor/crypto.js')
    BigInt = require('../vendor/bigint.js')
    HLP = require('./helpers.js')
  } else {
    // copy over and expose internals
    Object.keys(root.DSA).forEach(function (k) {
      DSA[k] = root.DSA[k]
    })
    root.DSA = DSA
    CryptoJS = root.CryptoJS
    BigInt = root.BigInt
    HLP = DSA.HLP
  }

  var ZERO = BigInt.str2bigInt('0', 10)
    , ONE = BigInt.str2bigInt('1', 10)
    , TWO = BigInt.str2bigInt('2', 10)
    , KEY_TYPE = '\x00\x00'

  var DEBUG = false
  function timer() {
    var start = (new Date()).getTime()
    return function (s) {
      if (!DEBUG || typeof console === 'undefined') return
      var t = (new Date()).getTime()
      console.log(s + ': ' + (t - start))
      start = t
    }
  }

  function makeRandom(min, max) {
    var c = BigInt.randBigInt(BigInt.bitSize(max))
    if (!HLP.between(c, min, max)) return makeRandom(min, max)
    return c
  }

  // altered BigInt.randProbPrime()
  // n rounds of Miller Rabin (after trial division with small primes)
  var rpprb = []
  function isProbPrime(k, n) {
    var i, B = 30000, l = BigInt.bitSize(k)
    var primes = BigInt.primes

    if (primes.length === 0)
      primes = BigInt.findPrimes(B)

    if (rpprb.length != k.length)
      rpprb = BigInt.dup(k)

    // check ans for divisibility by small primes up to B
    for (i = 0; (i < primes.length) && (primes[i] <= B); i++)
      if (BigInt.modInt(k, primes[i]) === 0 && !BigInt.equalsInt(k, primes[i]))
        return 0

    // do n rounds of Miller Rabin, with random bases less than k
    for (i = 0; i < n; i++) {
      BigInt.randBigInt_(rpprb, l, 0)
      while(!BigInt.greater(k, rpprb))  // pick a random rpprb that's < k
        BigInt.randBigInt_(rpprb, l, 0)
      if (!BigInt.millerRabin(k, rpprb))
        return 0
    }

    return 1
  }

  var bit_lengths = {
      '1024': { N: 160, repeat: 40 }  // 40x should give 2^-80 confidence
    , '2048': { N: 224, repeat: 56 }
    , '3072': { N: 256, repeat: 64 }
  }

  var primes = {}

  // follows go lang http://golang.org/src/pkg/crypto/dsa/dsa.go
  // fips version was removed in 0c99af0df3e7
  function generatePrimes(bit_length) {

    var t = timer()  // for debugging

    // number of MR tests to perform
    var repeat = bit_lengths[bit_length].repeat

    var N = bit_lengths[bit_length].N

    var LM1 = HLP.twotothe(bit_length - 1)
    var bl4 = 4 * bit_length
    var brk = false

    var q, p, rem, counter
    for (;;) {

      q = BigInt.randBigInt(N, 1)
      q[0] |= 1

      if (!isProbPrime(q, repeat)) continue
      t('q')

      for (counter = 0; counter < bl4; counter++) {
        p = BigInt.randBigInt(bit_length, 1)
        p[0] |= 1

        rem = BigInt.mod(p, q)
        rem = BigInt.sub(rem, ONE)
        p = BigInt.sub(p, rem)

        if (BigInt.greater(LM1, p)) continue
        if (!isProbPrime(p, repeat)) continue

        t('p')
        primes[bit_length] = { p: p, q: q }
        brk = true
        break
      }

      if (brk) break
    }

    var h = BigInt.dup(TWO)
    var pm1 = BigInt.sub(p, ONE)
    var e = BigInt.multMod(pm1, BigInt.inverseMod(q, p), p)

    var g
    for (;;) {
      g = BigInt.powMod(h, e, p)
      if (BigInt.equals(g, ONE)) {
        h = BigInt.add(h, ONE)
        continue
      }
      primes[bit_length].g = g
      t('g')
      return
    }

    throw new Error('Unreachable!')
  }

  function DSA(obj, opts) {
    if (!(this instanceof DSA)) return new DSA(obj, opts)

    // options
    opts = opts || {}

    // inherit
    if (obj) {
      var self = this
      ;['p', 'q', 'g', 'y', 'x'].forEach(function (prop) {
        self[prop] = obj[prop]
      })
      this.type = obj.type || KEY_TYPE
      return
    }

    // default to 1024
    var bit_length = parseInt(opts.bit_length ? opts.bit_length : 1024, 10)

    if (!bit_lengths[bit_length])
      throw new Error('Unsupported bit length.')

    // set primes
    if (!primes[bit_length])
      generatePrimes(bit_length)

    this.p = primes[bit_length].p
    this.q = primes[bit_length].q
    this.g = primes[bit_length].g

    // key type
    this.type = KEY_TYPE

    // private key
    this.x = makeRandom(ZERO, this.q)

    // public keys (p, q, g, y)
    this.y = BigInt.powMod(this.g, this.x, this.p)

    // nocache?
    if (opts.nocache) primes[bit_length] = null
  }

  DSA.prototype = {

    constructor: DSA,

    packPublic: function () {
      var str = this.type
      str += HLP.packMPI(this.p)
      str += HLP.packMPI(this.q)
      str += HLP.packMPI(this.g)
      str += HLP.packMPI(this.y)
      return str
    },

    packPrivate: function () {
      var str = this.packPublic() + HLP.packMPI(this.x)
      str = CryptoJS.enc.Latin1.parse(str)
      return str.toString(CryptoJS.enc.Base64)
    },

    sign: function (m) {
      m = CryptoJS.enc.Latin1.parse(m)  // CryptoJS.SHA1(m)
      m = BigInt.str2bigInt(m.toString(CryptoJS.enc.Hex), 16)
      var k, r = ZERO, s = ZERO
      while (BigInt.isZero(s) || BigInt.isZero(r)) {
        k = makeRandom(ZERO, this.q)
        r = BigInt.mod(BigInt.powMod(this.g, k, this.p), this.q)
        if (BigInt.isZero(r)) continue
        s = BigInt.inverseMod(k, this.q)
        s = BigInt.mult(s, BigInt.add(m, BigInt.mult(this.x, r)))
        s = BigInt.mod(s, this.q)
      }
      return [r, s]
    },

    fingerprint: function () {
      var pk = this.packPublic()
      if (this.type === KEY_TYPE) pk = pk.substring(2)
      pk = CryptoJS.enc.Latin1.parse(pk)
      return CryptoJS.SHA1(pk).toString(CryptoJS.enc.Hex)
    }

  }

  DSA.parsePublic = function (str, priv) {
    var fields = ['SHORT', 'MPI', 'MPI', 'MPI', 'MPI']
    if (priv) fields.push('MPI')
    str = HLP.splitype(fields, str)
    var obj = {
        type: str[0]
      , p: HLP.readMPI(str[1])
      , q: HLP.readMPI(str[2])
      , g: HLP.readMPI(str[3])
      , y: HLP.readMPI(str[4])
    }
    if (priv) obj.x = HLP.readMPI(str[5])
    return new DSA(obj)
  }

  function tokenizeStr(str) {
    var start, end

    start = str.indexOf("(")
    end = str.lastIndexOf(")")

    if (start < 0 || end < 0)
      throw new Error("Malformed S-Expression")

    str = str.substring(start + 1, end)

    var splt = str.search(/\s/)
    var obj = {
        type: str.substring(0, splt)
      , val: []
    }

    str = str.substring(splt + 1, end)
    start = str.indexOf("(")

    if (start < 0) obj.val.push(str)
    else {

      var i, len, ss, es
      while (start > -1) {
        i = start + 1
        len = str.length
        for (ss = 1, es = 0; i < len && es < ss; i++) {
          if (str[i] === "(") ss++
          if (str[i] === ")") es++
        }
        obj.val.push(tokenizeStr(str.substring(start, ++i)))
        str = str.substring(++i)
        start = str.indexOf("(")
      }

    }
    return obj
  }

  function parseLibotr(obj) {
    if (!obj.type) throw new Error("Parse error.")

    var o, val
    if (obj.type === "privkeys") {
      o = []
      obj.val.forEach(function (i) {
        o.push(parseLibotr(i))
      })
      return o
    }

    o = {}
    obj.val.forEach(function (i) {

      val = i.val[0]
      if (typeof val === "string") {

        if (val.indexOf("#") === 0) {
          val = val.substring(1, val.lastIndexOf("#"))
          val = BigInt.str2bigInt(val, 16)
        }

      } else {
        val = parseLibotr(i)
      }

      o[i.type] = val
    })

    return o
  }

  DSA.parsePrivate = function (str, libotr) {
    if (!libotr) {
      str = CryptoJS.enc.Base64.parse(str)
      str = str.toString(CryptoJS.enc.Latin1)
      return DSA.parsePublic(str, true)
    }
    // only returning the first key found
    return parseLibotr(tokenizeStr(str))[0]["private-key"].dsa
  }

  DSA.verify = function (key, m, r, s) {
    if (!HLP.between(r, ZERO, key.q) || !HLP.between(s, ZERO, key.q))
      return false

    var hm = CryptoJS.enc.Latin1.parse(m)  // CryptoJS.SHA1(m)
    hm = BigInt.str2bigInt(hm.toString(CryptoJS.enc.Hex), 16)

    var w = BigInt.inverseMod(s, key.q)
    var u1 = BigInt.multMod(hm, w, key.q)
    var u2 = BigInt.multMod(r, w, key.q)

    u1 = BigInt.powMod(key.g, u1, key.p)
    u2 = BigInt.powMod(key.y, u2, key.p)

    var v = BigInt.mod(BigInt.multMod(u1, u2, key.p), key.q)

    return BigInt.equals(v, r)
  }

}).call(this)<commit_msg>try to avoid key compromise from entropy failures<commit_after>;(function () {
  "use strict";

  var root = this

  var CryptoJS, BigInt, HLP
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = DSA
    CryptoJS = require('../vendor/crypto.js')
    BigInt = require('../vendor/bigint.js')
    HLP = require('./helpers.js')
  } else {
    // copy over and expose internals
    Object.keys(root.DSA).forEach(function (k) {
      DSA[k] = root.DSA[k]
    })
    root.DSA = DSA
    CryptoJS = root.CryptoJS
    BigInt = root.BigInt
    HLP = DSA.HLP
  }

  var ZERO = BigInt.str2bigInt('0', 10)
    , ONE = BigInt.str2bigInt('1', 10)
    , TWO = BigInt.str2bigInt('2', 10)
    , KEY_TYPE = '\x00\x00'

  var DEBUG = false
  function timer() {
    var start = (new Date()).getTime()
    return function (s) {
      if (!DEBUG || typeof console === 'undefined') return
      var t = (new Date()).getTime()
      console.log(s + ': ' + (t - start))
      start = t
    }
  }

  function makeRandom(min, max) {
    var c = BigInt.randBigInt(BigInt.bitSize(max))
    if (!HLP.between(c, min, max)) return makeRandom(min, max)
    return c
  }

  // altered BigInt.randProbPrime()
  // n rounds of Miller Rabin (after trial division with small primes)
  var rpprb = []
  function isProbPrime(k, n) {
    var i, B = 30000, l = BigInt.bitSize(k)
    var primes = BigInt.primes

    if (primes.length === 0)
      primes = BigInt.findPrimes(B)

    if (rpprb.length != k.length)
      rpprb = BigInt.dup(k)

    // check ans for divisibility by small primes up to B
    for (i = 0; (i < primes.length) && (primes[i] <= B); i++)
      if (BigInt.modInt(k, primes[i]) === 0 && !BigInt.equalsInt(k, primes[i]))
        return 0

    // do n rounds of Miller Rabin, with random bases less than k
    for (i = 0; i < n; i++) {
      BigInt.randBigInt_(rpprb, l, 0)
      while(!BigInt.greater(k, rpprb))  // pick a random rpprb that's < k
        BigInt.randBigInt_(rpprb, l, 0)
      if (!BigInt.millerRabin(k, rpprb))
        return 0
    }

    return 1
  }

  var bit_lengths = {
      '1024': { N: 160, repeat: 40 }  // 40x should give 2^-80 confidence
    , '2048': { N: 224, repeat: 56 }
  }

  var primes = {}

  // follows go lang http://golang.org/src/pkg/crypto/dsa/dsa.go
  // fips version was removed in 0c99af0df3e7
  function generatePrimes(bit_length) {

    var t = timer()  // for debugging

    // number of MR tests to perform
    var repeat = bit_lengths[bit_length].repeat

    var N = bit_lengths[bit_length].N

    var LM1 = HLP.twotothe(bit_length - 1)
    var bl4 = 4 * bit_length
    var brk = false

    var q, p, rem, counter
    for (;;) {

      q = BigInt.randBigInt(N, 1)
      q[0] |= 1

      if (!isProbPrime(q, repeat)) continue
      t('q')

      for (counter = 0; counter < bl4; counter++) {
        p = BigInt.randBigInt(bit_length, 1)
        p[0] |= 1

        rem = BigInt.mod(p, q)
        rem = BigInt.sub(rem, ONE)
        p = BigInt.sub(p, rem)

        if (BigInt.greater(LM1, p)) continue
        if (!isProbPrime(p, repeat)) continue

        t('p')
        primes[bit_length] = { p: p, q: q }
        brk = true
        break
      }

      if (brk) break
    }

    var h = BigInt.dup(TWO)
    var pm1 = BigInt.sub(p, ONE)
    var e = BigInt.multMod(pm1, BigInt.inverseMod(q, p), p)

    var g
    for (;;) {
      g = BigInt.powMod(h, e, p)
      if (BigInt.equals(g, ONE)) {
        h = BigInt.add(h, ONE)
        continue
      }
      primes[bit_length].g = g
      t('g')
      return
    }

    throw new Error('Unreachable!')
  }

  function DSA(obj, opts) {
    if (!(this instanceof DSA)) return new DSA(obj, opts)

    // options
    opts = opts || {}

    // inherit
    if (obj) {
      var self = this
      ;['p', 'q', 'g', 'y', 'x'].forEach(function (prop) {
        self[prop] = obj[prop]
      })
      this.type = obj.type || KEY_TYPE
      return
    }

    // default to 1024
    var bit_length = parseInt(opts.bit_length ? opts.bit_length : 1024, 10)

    if (!bit_lengths[bit_length])
      throw new Error('Unsupported bit length.')

    // set primes
    if (!primes[bit_length])
      generatePrimes(bit_length)

    this.p = primes[bit_length].p
    this.q = primes[bit_length].q
    this.g = primes[bit_length].g

    // key type
    this.type = KEY_TYPE

    // private key
    this.x = makeRandom(ZERO, this.q)

    // public keys (p, q, g, y)
    this.y = BigInt.powMod(this.g, this.x, this.p)

    // nocache?
    if (opts.nocache) primes[bit_length] = null
  }

  DSA.prototype = {

    constructor: DSA,

    packPublic: function () {
      var str = this.type
      str += HLP.packMPI(this.p)
      str += HLP.packMPI(this.q)
      str += HLP.packMPI(this.g)
      str += HLP.packMPI(this.y)
      return str
    },

    packPrivate: function () {
      var str = this.packPublic() + HLP.packMPI(this.x)
      str = CryptoJS.enc.Latin1.parse(str)
      return str.toString(CryptoJS.enc.Base64)
    },

    // http://www.imperialviolet.org/2013/06/15/suddendeathentropy.html
    generateNonce: function (m) {
      var priv = HLP.bigInt2bits(BigInt.trim(this.x, 0))
      var rand = HLP.bigInt2bits(BigInt.randBigInt(256))

      var sha256 = CryptoJS.algo.SHA256.create()
      sha256.update(CryptoJS.enc.Latin1.parse(priv))
      sha256.update(m)
      sha256.update(CryptoJS.enc.Latin1.parse(rand))

      var hash = sha256.finalize()
      hash = HLP.bits2bigInt(hash.toString(CryptoJS.enc.Latin1))
      BigInt.rightShift_(hash, 256 - BigInt.bitSize(this.q))

      return HLP.between(hash, ZERO, this.q) ? hash : this.generateNonce(m)
    },

    sign: function (m) {
      m = CryptoJS.enc.Latin1.parse(m)
      var b = BigInt.str2bigInt(m.toString(CryptoJS.enc.Hex), 16)
      var k, r = ZERO, s = ZERO
      while (BigInt.isZero(s) || BigInt.isZero(r)) {
        k = this.generateNonce(m)
        r = BigInt.mod(BigInt.powMod(this.g, k, this.p), this.q)
        if (BigInt.isZero(r)) continue
        s = BigInt.inverseMod(k, this.q)
        s = BigInt.mult(s, BigInt.add(b, BigInt.mult(this.x, r)))
        s = BigInt.mod(s, this.q)
      }
      return [r, s]
    },

    fingerprint: function () {
      var pk = this.packPublic()
      if (this.type === KEY_TYPE) pk = pk.substring(2)
      pk = CryptoJS.enc.Latin1.parse(pk)
      return CryptoJS.SHA1(pk).toString(CryptoJS.enc.Hex)
    }

  }

  DSA.parsePublic = function (str, priv) {
    var fields = ['SHORT', 'MPI', 'MPI', 'MPI', 'MPI']
    if (priv) fields.push('MPI')
    str = HLP.splitype(fields, str)
    var obj = {
        type: str[0]
      , p: HLP.readMPI(str[1])
      , q: HLP.readMPI(str[2])
      , g: HLP.readMPI(str[3])
      , y: HLP.readMPI(str[4])
    }
    if (priv) obj.x = HLP.readMPI(str[5])
    return new DSA(obj)
  }

  function tokenizeStr(str) {
    var start, end

    start = str.indexOf("(")
    end = str.lastIndexOf(")")

    if (start < 0 || end < 0)
      throw new Error("Malformed S-Expression")

    str = str.substring(start + 1, end)

    var splt = str.search(/\s/)
    var obj = {
        type: str.substring(0, splt)
      , val: []
    }

    str = str.substring(splt + 1, end)
    start = str.indexOf("(")

    if (start < 0) obj.val.push(str)
    else {

      var i, len, ss, es
      while (start > -1) {
        i = start + 1
        len = str.length
        for (ss = 1, es = 0; i < len && es < ss; i++) {
          if (str[i] === "(") ss++
          if (str[i] === ")") es++
        }
        obj.val.push(tokenizeStr(str.substring(start, ++i)))
        str = str.substring(++i)
        start = str.indexOf("(")
      }

    }
    return obj
  }

  function parseLibotr(obj) {
    if (!obj.type) throw new Error("Parse error.")

    var o, val
    if (obj.type === "privkeys") {
      o = []
      obj.val.forEach(function (i) {
        o.push(parseLibotr(i))
      })
      return o
    }

    o = {}
    obj.val.forEach(function (i) {

      val = i.val[0]
      if (typeof val === "string") {

        if (val.indexOf("#") === 0) {
          val = val.substring(1, val.lastIndexOf("#"))
          val = BigInt.str2bigInt(val, 16)
        }

      } else {
        val = parseLibotr(i)
      }

      o[i.type] = val
    })

    return o
  }

  DSA.parsePrivate = function (str, libotr) {
    if (!libotr) {
      str = CryptoJS.enc.Base64.parse(str)
      str = str.toString(CryptoJS.enc.Latin1)
      return DSA.parsePublic(str, true)
    }
    // only returning the first key found
    return parseLibotr(tokenizeStr(str))[0]["private-key"].dsa
  }

  DSA.verify = function (key, m, r, s) {
    if (!HLP.between(r, ZERO, key.q) || !HLP.between(s, ZERO, key.q))
      return false

    var hm = CryptoJS.enc.Latin1.parse(m)  // CryptoJS.SHA1(m)
    hm = BigInt.str2bigInt(hm.toString(CryptoJS.enc.Hex), 16)

    var w = BigInt.inverseMod(s, key.q)
    var u1 = BigInt.multMod(hm, w, key.q)
    var u2 = BigInt.multMod(r, w, key.q)

    u1 = BigInt.powMod(key.g, u1, key.p)
    u2 = BigInt.powMod(key.y, u2, key.p)

    var v = BigInt.mod(BigInt.multMod(u1, u2, key.p), key.q)

    return BigInt.equals(v, r)
  }

}).call(this)<|endoftext|>


<commit_before>/*!
 * EJS
 * Copyright(c) 2012 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var utils = require('./utils')
  , path = require('path')
  , dirname = path.dirname
  , extname = path.extname
  , join = path.join
  , fs = require('fs')
  , read = fs.readFileSync
  , _DEFAULT_DELIMITER = '%';

/**
 * Intermediate js cache.
 *
 * @type Object
 */

var cache = {};

/**
 * Clear intermediate js cache.
 *
 * @api public
 */

exports.clearCache = function(){
  cache = {};
};

/**
 * Re-throw the given `err` in context to the
 * `str` of ejs, `filename`, and `lineno`.
 *
 * @param {Error} err
 * @param {String} str
 * @param {String} filename
 * @param {String} lineno
 * @api private
 */

function rethrow(err, str, filename, lineno){
  var lines = str.split('\n')
    , start = Math.max(lineno - 3, 0)
    , end = Math.min(lines.length, lineno + 3);

  // Error context
  var context = lines.slice(start, end).map(function(line, i){
    var curr = i + start + 1;
    return (curr == lineno ? ' >> ' : '    ')
      + curr
      + '| '
      + line;
  }).join('\n');

  // Alter exception message
  err.path = filename;
  err.message = (filename || 'ejs') + ':'
    + lineno + '\n'
    + context + '\n\n'
    + err.message;

  throw err;
}

/**
 * Parse the given `str` of ejs, returning the function body.
 *
 * @param {String} str
 * @return {String}
 * @api public
 */

function parse(str, options){
  var options = options || {}
    , d = options.delimiter || exports.delimiter || _DEFAULT_DELIMITER
    , open = '<' + d
    , close = d + '>'
    , filename = options.filename
    , compileDebug = options.compileDebug !== false
    , buf = "";

  buf += 'var buf = [];';
  if (false !== options._with) {
    buf += 'with (locals || {}) { ';
  }
  buf += 'buf.push(\'';

  var lineno = 1;

  var consumeEOL = false;
  for (var i = 0, len = str.length; i < len; ++i) {
    var stri = str[i];
    if (str.slice(i, open.length + i) == open) {
      i += open.length

      var prefix
        , postfix
        , line = (compileDebug ? '__line=' : '') + lineno
        , noEndNeeded = false;
      switch (str[i]) {
        case '=':
          prefix = "', escape((" + line + ', ';
          postfix = ")), '";
          ++i;
          break;
        case '-':
          prefix = "', (" + line + ', ';
          postfix = "), '";
          ++i;
          break;
        default:
          if (str.substr(i, d.length) == d) {
            noEndNeeded = true;
          } else {
            prefix = "');" + line + ';';
            postfix = "; buf.push('";
          }
      }

      if (noEndNeeded) {
        buf += "', '" + open + "', '";
        i += d.length - 1;
      } else {
        var end = str.indexOf(close, i);

        if (end < 0){
          throw new Error('Could not find matching close tag for "' + open + str[i - 1] + '".');
        }

        var js = str.substring(i, end)
          , start = i
          , include = null
          , n = 0;

        if ('-' == js[js.length-1]){
          js = js.substring(0, js.length - 2);
          consumeEOL = true;
        }

        if (0 == js.trim().indexOf('include')) {
          var name = js.trim().slice(7).trim();
          if (!filename) throw new Error('`include` requires the \'filename\' option.');
          var path = resolveInclude(name, filename);
          include = read(path, 'utf8');
          include = parse(include, { filename: path, _with: false, delimiter: d, compileDebug: compileDebug });
          buf += "' + (function(){" + include + "})() + '";
          js = '';
        }

        while (~(n = js.indexOf("\n", n))) n++, lineno++;

        switch(js[0]) {
          case d:
            js = " buf.push('" + open + js.substring(1).replace(/'/g, "\\'") + close + "');";
            break;
          case '#':
            js = "";
            break;
        }

        if (js) {
          if (js.lastIndexOf('//') > js.lastIndexOf('\n')) js += '\n';
          buf += prefix;
          buf += js;
          buf += postfix;
        }
        i += end - start + close.length - 1;
      }
    } else if (stri == "\\") {
      buf += "\\\\";
    } else if (stri == "'") {
      buf += "\\'";
    } else if (stri == "\r") {
      // ignore
    } else if (stri == "\n") {
      if (consumeEOL) {
        consumeEOL = false;
      } else {
        buf += "\\n";
        lineno++;
      }
    } else {
      buf += stri;
    }
  }

  if (false !== options._with) buf += "');}return buf.join('');";
  else buf += "');return buf.join('');";
  return buf;
};

/**
 * Compile the given `str` of ejs into a `Function`.
 *
 * @param {String} str
 * @param {Object} opts
 * @return {Function}
 * @api public
 */

var compile = exports.compile = function(str, opts){
  opts = opts || {};
  var escape = opts.escape || utils.escape;

  var input = JSON.stringify(str)
    , compileDebug = opts.compileDebug !== false
    , client = opts.client
    , filename = opts.filename
        ? JSON.stringify(opts.filename)
        : 'undefined';

  if (compileDebug) {
    // Adds the fancy stack trace meta info
    str = 'var __line = 1'
        +   ', __lines = ' + input
        +   ', __filename = ' + filename + ';'
        + 'try {'
        +   parse(str, opts)
        + '} catch (err) {'
        + '  rethrow(err, __lines, __filename, __line);'
        + '}';
  } else {
    str = parse(str, opts);
  }

  if (opts.debug) {
    console.log(str);
  }

  if (opts.client) {
    str = 'escape = escape || ' + escape.toString() + ';\n' + str;
    str = 'rethrow = rethrow || ' + rethrow.toString() + ';\n' + str;
  }

  try {
    fn = new Function('locals, escape, include, rethrow', str);
  }
  catch(e) {
    if (e instanceof SyntaxError) {
      if (opts.filename) {
        e.message += ' in ' + opts.filename;
      }
      e.message += ' while compiling ejs';
    }
    throw e;
  }

  if (client) return fn;

  return function(locals){
    return fn(locals, escape, null /* TODO */, rethrow);
  }
};

/**
 * Render the given `str` of ejs.
 *
 * Options:
 *
 *   - `locals`          Local variables object
 *   - `cache`           Compiled functions are cached, requires `filename`
 *   - `filename`        Used by `cache` to key caches
 *   - `scope`           Function execution context
 *   - `debug`           Output generated function body
 *
 * @param {String} str
 * @param {Object} options
 * @return {String}
 * @api public
 */

exports.render = function(str, locals, options){
  var fn
    , locals = locals || {}
    , options = options || {};

  if (options.cache) {
    if (options.filename) {
      fn = cache[options.filename] || (cache[options.filename] = compile(str, options));
    } else {
      throw new Error('"cache" option requires "filename".');
    }
  } else {
    fn = compile(str, options);
  }

  if (options.context) {
    return fn.call(options.context, locals);
  }
  return fn(locals);
};

/**
 * Render an EJS file at the given `path` and callback `fn(err, str)`.
 *
 * @param {String} path
 * @param {Object|Function} options or callback
 * @param {Function} fn
 * @api public
 */

exports.renderFile = function(path, locals, options, fn){
  arguments = Array.prototype.slice.call(arguments);
  arguments.shift(); // path
  fn = arguments.pop();
  locals = arguments.shift() || {};
  options = arguments.pop() || {};

  var key = path + ':string';

  options.filename = path;

  console.log(path, locals, options, fn)

  var str;
  try {
    str = options.cache
      ? cache[key] || (cache[key] = read(path, 'utf8'))
      : read(path, 'utf8');
    str = exports.render(str, locals, options);
  } catch (err) {
    fn(err);
    return;
  }
  fn(null, str);
};

/**
 * Resolve include `name` relative to `filename`.
 *
 * @param {String} name
 * @param {String} filename
 * @return {String}
 * @api private
 */

function resolveInclude(name, filename) {
  var path = join(dirname(filename), name);
  var ext = extname(name);
  if (!ext) path += '.ejs';
  return path;
}

// express support

exports.__express = exports.renderFile;

/**
 * Expose to require().
 */

if (require.extensions) {
  require.extensions['.ejs'] = function (module, filename) {
    filename = filename || module.filename;
    var options = { filename: filename, client: true }
      , template = fs.readFileSync(filename).toString()
      , fn = compile(template, options);
    module._compile('module.exports = ' + fn.toString() + ';', filename);
  };
} else if (require.registerExtension) {
  require.registerExtension('.ejs', function(src) {
    return compile(src, {});
  });
}
<commit_msg>Cleaner<commit_after>/*!
 * EJS
 * Copyright(c) 2012 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var utils = require('./utils')
  , path = require('path')
  , dirname = path.dirname
  , extname = path.extname
  , join = path.join
  , fs = require('fs')
  , read = fs.readFileSync
  , _DEFAULT_DELIMITER = '%';

/**
 * Intermediate js cache.
 *
 * @type Object
 */

var cache = {};

/**
 * Clear intermediate js cache.
 *
 * @api public
 */

exports.clearCache = function(){
  cache = {};
};

/**
 * Re-throw the given `err` in context to the
 * `str` of ejs, `filename`, and `lineno`.
 *
 * @param {Error} err
 * @param {String} str
 * @param {String} filename
 * @param {String} lineno
 * @api private
 */

function rethrow(err, str, filename, lineno){
  var lines = str.split('\n')
    , start = Math.max(lineno - 3, 0)
    , end = Math.min(lines.length, lineno + 3);

  // Error context
  var context = lines.slice(start, end).map(function(line, i){
    var curr = i + start + 1;
    return (curr == lineno ? ' >> ' : '    ')
      + curr
      + '| '
      + line;
  }).join('\n');

  // Alter exception message
  err.path = filename;
  err.message = (filename || 'ejs') + ':'
    + lineno + '\n'
    + context + '\n\n'
    + err.message;

  throw err;
}

/**
 * Parse the given `str` of ejs, returning the function body.
 *
 * @param {String} str
 * @return {String}
 * @api public
 */

function parse(str, options){
  var options = options || {}
    , d = options.delimiter || exports.delimiter || _DEFAULT_DELIMITER
    , open = '<' + d
    , close = d + '>'
    , filename = options.filename
    , compileDebug = options.compileDebug !== false
    , buf = "";

  buf += 'var buf = [];';
  console.log(options)
  if (false !== options._with) {
    buf += 'with (locals || {}) { ';
  }
  buf += 'buf.push(\'';

  var lineno = 1;

  var consumeEOL = false;
  for (var i = 0, len = str.length; i < len; ++i) {
    var stri = str[i];
    if (str.slice(i, open.length + i) == open) {
      i += open.length

      var prefix
        , postfix
        , line = (compileDebug ? '__line=' : '') + lineno
        , noEndNeeded = false;
      switch (str[i]) {
        case '=':
          prefix = "', escape((" + line + ', ';
          postfix = ")), '";
          ++i;
          break;
        case '-':
          prefix = "', (" + line + ', ';
          postfix = "), '";
          ++i;
          break;
        default:
          if (str.substr(i, d.length) == d) {
            buf += "', '" + open + "', '";
            i += d.length - 1;
            noEndNeeded = true;
            continue;
          } else {
            prefix = "');" + line + ';';
            postfix = "; buf.push('";
          }
      }

      var end = str.indexOf(close, i);

      if (end < 0){
        throw new Error('Could not find matching close tag for "' + open + str[i - 1] + '".');
      }

      var js = str.substring(i, end)
        , start = i
        , include = null
        , n = 0;

      if ('-' == js[js.length-1]){
        js = js.substring(0, js.length - 2);
        consumeEOL = true;
      }

      if (0 == js.trim().indexOf('include')) {
        var name = js.trim().slice(7).trim();
        if (!filename) throw new Error('`include` requires the \'filename\' option.');
        var path = resolveInclude(name, filename);
        include = read(path, 'utf8');
        include = parse(include, { filename: path, _with: false, delimiter: d, compileDebug: compileDebug });
        buf += "' + (function(){" + include + "})() + '";
        js = '';
      }

      while (~(n = js.indexOf("\n", n))) n++, lineno++;

      switch(js[0]) {
        case d:
          js = " buf.push('" + open + js.substring(1).replace(/'/g, "\\'") + close + "');";
          break;
        case '#':
          js = "";
          break;
      }

      if (js) {
        if (js.lastIndexOf('//') > js.lastIndexOf('\n')) js += '\n';
        buf += prefix;
        buf += js;
        buf += postfix;
      }
      i += end - start + close.length - 1;
    } else if (stri == "\\") {
      buf += "\\\\";
    } else if (stri == "'") {
      buf += "\\'";
    } else if (stri == "\r") {
      // ignore
    } else if (stri == "\n") {
      if (consumeEOL) {
        consumeEOL = false;
      } else {
        buf += "\\n";
        lineno++;
      }
    } else {
      buf += stri;
    }
  }

  if (false !== options._with) buf += "');}return buf.join('');";
  else buf += "');return buf.join('');";
  return buf;
};

/**
 * Compile the given `str` of ejs into a `Function`.
 *
 * @param {String} str
 * @param {Object} opts
 * @return {Function}
 * @api public
 */

var compile = exports.compile = function(str, opts){
  opts = opts || {};
  var escape = opts.escape || utils.escape;

  var input = JSON.stringify(str)
    , compileDebug = opts.compileDebug !== false
    , client = opts.client
    , filename = opts.filename
        ? JSON.stringify(opts.filename)
        : 'undefined';

  if (compileDebug) {
    // Adds the fancy stack trace meta info
    str = 'var __line = 1'
        +   ', __lines = ' + input
        +   ', __filename = ' + filename + ';'
        + 'try {'
        +   parse(str, opts)
        + '} catch (err) {'
        + '  rethrow(err, __lines, __filename, __line);'
        + '}';
  } else {
    str = parse(str, opts);
  }

  if (opts.debug) {
    console.log(str);
  }

  if (opts.client) {
    str = 'escape = escape || ' + escape.toString() + ';\n' + str;
    str = 'rethrow = rethrow || ' + rethrow.toString() + ';\n' + str;
  }

  try {
    fn = new Function('locals, escape, include, rethrow', str);
  }
  catch(e) {
    if (e instanceof SyntaxError) {
      if (opts.filename) {
        e.message += ' in ' + opts.filename;
      }
      e.message += ' while compiling ejs';
    }
    throw e;
  }

  if (client) return fn;

  return function(locals){
    return fn(locals, escape, null /* TODO */, rethrow);
  }
};

/**
 * Render the given `str` of ejs.
 *
 * Options:
 *
 *   - `locals`          Local variables object
 *   - `cache`           Compiled functions are cached, requires `filename`
 *   - `filename`        Used by `cache` to key caches
 *   - `scope`           Function execution context
 *   - `debug`           Output generated function body
 *
 * @param {String} str
 * @param {Object} options
 * @return {String}
 * @api public
 */

exports.render = function(str, locals, options){
  var fn
    , locals = locals || {}
    , options = options || {};

  if (options.cache) {
    if (options.filename) {
      fn = cache[options.filename] || (cache[options.filename] = compile(str, options));
    } else {
      throw new Error('"cache" option requires "filename".');
    }
  } else {
    fn = compile(str, options);
  }

  if (options.context) {
    return fn.call(options.context, locals);
  }
  return fn(locals);
};

/**
 * Render an EJS file at the given `path` and callback `fn(err, str)`.
 *
 * @param {String} path
 * @param {Object|Function} options or callback
 * @param {Function} fn
 * @api public
 */

exports.renderFile = function(path, locals, options, fn){
  arguments = Array.prototype.slice.call(arguments);
  arguments.shift(); // path
  fn = arguments.pop();
  locals = arguments.shift() || {};
  options = arguments.pop() || {};

  var key = path + ':string';

  options.filename = path;

  console.log(path, locals, options, fn)

  var str;
  try {
    str = options.cache
      ? cache[key] || (cache[key] = read(path, 'utf8'))
      : read(path, 'utf8');
    str = exports.render(str, locals, options);
  } catch (err) {
    fn(err);
    return;
  }
  fn(null, str);
};

/**
 * Resolve include `name` relative to `filename`.
 *
 * @param {String} name
 * @param {String} filename
 * @return {String}
 * @api private
 */

function resolveInclude(name, filename) {
  var path = join(dirname(filename), name);
  var ext = extname(name);
  if (!ext) path += '.ejs';
  return path;
}

// express support

exports.__express = exports.renderFile;

/**
 * Expose to require().
 */

if (require.extensions) {
  require.extensions['.ejs'] = function (module, filename) {
    filename = filename || module.filename;
    var options = { filename: filename, client: true }
      , template = fs.readFileSync(filename).toString()
      , fn = compile(template, options);
    module._compile('module.exports = ' + fn.toString() + ';', filename);
  };
} else if (require.registerExtension) {
  require.registerExtension('.ejs', function(src) {
    return compile(src, {});
  });
}
<|endoftext|>


<commit_before>/**
 * Env variable prod | dev | test
 *
 * @type {String}
 */
var env = 'dev';

switch(process.env.NODE_ENV){
  case 'prod':
    env = 'prod';
    break;
  case 'test':
    env = 'test';
    break;
}

module.exports = env;<commit_msg>update env config<commit_after>/**
 * Env variable prod | dev | test
 *
 * @type {String}
 */
var env = 'dev';

switch(process.env.NODE_ENV){
  case 'prod':
    env = 'prod';
    break;
  case 'test':
    env = 'test';
    break;
  case 'production':
    env = 'prod';
    break;
  case 'test':
    env = 'test';
    break;
}

module.exports = env;<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var ref = require('ref')
var assert = require('assert')
var debug = require('debug')('ffi:ffi')
var Struct = require('ref-struct')
var bindings = require('./bindings')

/**
 * Export some of the properties from the "bindings" file.
 */

;['HAS_OBJC', 'FFI_TYPES',
, 'FFI_OK', 'FFI_BAD_TYPEDEF', 'FFI_BAD_ABI'
, 'FFI_DEFAULT_ABI', 'FFI_LAST_ABI', 'FFI_SYSV', 'FFI_UNIX64', 'FFI_WIN64'
, 'FFI_STDCALL', 'FFI_THISCALL', 'FFI_FASTCALL', 'FFI_MS_CDECL'].forEach(function (prop) {
  if (!bindings.hasOwnProperty(prop)) {
    return debug('skipping exporting of non-existant property: %s', prop)
  }
  var desc = Object.getOwnPropertyDescriptor(bindings, prop)
  Object.defineProperty(exports, prop, desc)
})

/**
 * Set the `ffi_type` property on the built-in types.
 */

Object.keys(bindings.FFI_TYPES).forEach(function (name) {
  var type = bindings.FFI_TYPES[name]
  type.name = name
  if (name === 'pointer') return // there is no "pointer" type...
  ref.types[name].ffi_type = type
})

// make `size_t` use the "ffi_type_pointer"
ref.types.size_t.ffi_type = bindings.FFI_TYPES.pointer

// make `Utf8String` use "ffi_type_pointer"
var CString = ref.types.CString || ref.types.Utf8String
CString.ffi_type = bindings.FFI_TYPES.pointer

// make `Object` use the "ffi_type_pointer"
ref.types.Object.ffi_type = bindings.FFI_TYPES.pointer

// libffi is weird when it comes to long data types (defaults to 64-bit),
// so we emulate here, since some platforms have 32-bit longs and some
// platforms have 64-bit longs.
switch (ref.sizeof.long) {
  case 4:
    ref.types.ulong.ffi_type = bindings.FFI_TYPES.uint32
    ref.types.long.ffi_type = bindings.FFI_TYPES.int32
    break;
  case 8:
    ref.types.ulong.ffi_type = bindings.FFI_TYPES.uint64
    ref.types.long.ffi_type = bindings.FFI_TYPES.int64
    break;
  default:
    throw new Error('unsupported "long" size: ' + ref.sizeof.long)
}

/**
 * Alias the "ref" types onto ffi's exports, for convenience...
 */

exports.types = ref.types

// Include our other modules
exports.CIF = require('./cif')
exports.CIF_var = require('./cif_var')
exports.ForeignFunction = require('./foreign_function')
exports.VariadicForeignFunction = require('./foreign_function_var')
exports.DynamicLibrary = require('./dynamic_library')
exports.Library = require('./library')
exports.Callback = require('./callback')
exports.errno = require('./errno')
exports.ffiType = require('./type')

// the shared library extension for this platform
exports.LIB_EXT = exports.Library.EXT

// the FFI_TYPE struct definition
exports.FFI_TYPE = exports.ffiType.FFI_TYPE
<commit_msg>ffi: fix debug() call<commit_after>
/**
 * Module dependencies.
 */

var ref = require('ref')
var assert = require('assert')
var debug = require('debug')('ffi:ffi')
var Struct = require('ref-struct')
var bindings = require('./bindings')

/**
 * Export some of the properties from the "bindings" file.
 */

;['HAS_OBJC', 'FFI_TYPES',
, 'FFI_OK', 'FFI_BAD_TYPEDEF', 'FFI_BAD_ABI'
, 'FFI_DEFAULT_ABI', 'FFI_LAST_ABI', 'FFI_SYSV', 'FFI_UNIX64', 'FFI_WIN64'
, 'FFI_STDCALL', 'FFI_THISCALL', 'FFI_FASTCALL', 'FFI_MS_CDECL'].forEach(function (prop) {
  if (!bindings.hasOwnProperty(prop)) {
    return debug('skipping exporting of non-existant property', prop)
  }
  var desc = Object.getOwnPropertyDescriptor(bindings, prop)
  Object.defineProperty(exports, prop, desc)
})

/**
 * Set the `ffi_type` property on the built-in types.
 */

Object.keys(bindings.FFI_TYPES).forEach(function (name) {
  var type = bindings.FFI_TYPES[name]
  type.name = name
  if (name === 'pointer') return // there is no "pointer" type...
  ref.types[name].ffi_type = type
})

// make `size_t` use the "ffi_type_pointer"
ref.types.size_t.ffi_type = bindings.FFI_TYPES.pointer

// make `Utf8String` use "ffi_type_pointer"
var CString = ref.types.CString || ref.types.Utf8String
CString.ffi_type = bindings.FFI_TYPES.pointer

// make `Object` use the "ffi_type_pointer"
ref.types.Object.ffi_type = bindings.FFI_TYPES.pointer

// libffi is weird when it comes to long data types (defaults to 64-bit),
// so we emulate here, since some platforms have 32-bit longs and some
// platforms have 64-bit longs.
switch (ref.sizeof.long) {
  case 4:
    ref.types.ulong.ffi_type = bindings.FFI_TYPES.uint32
    ref.types.long.ffi_type = bindings.FFI_TYPES.int32
    break;
  case 8:
    ref.types.ulong.ffi_type = bindings.FFI_TYPES.uint64
    ref.types.long.ffi_type = bindings.FFI_TYPES.int64
    break;
  default:
    throw new Error('unsupported "long" size: ' + ref.sizeof.long)
}

/**
 * Alias the "ref" types onto ffi's exports, for convenience...
 */

exports.types = ref.types

// Include our other modules
exports.CIF = require('./cif')
exports.CIF_var = require('./cif_var')
exports.ForeignFunction = require('./foreign_function')
exports.VariadicForeignFunction = require('./foreign_function_var')
exports.DynamicLibrary = require('./dynamic_library')
exports.Library = require('./library')
exports.Callback = require('./callback')
exports.errno = require('./errno')
exports.ffiType = require('./type')

// the shared library extension for this platform
exports.LIB_EXT = exports.Library.EXT

// the FFI_TYPE struct definition
exports.FFI_TYPE = exports.ffiType.FFI_TYPE
<|endoftext|>


<commit_before>'use strict'

var co = require('co')
var path = require('path')
var util = require('util')
var debug = require('debug')
var mkdirp = require('mkdirp')
var chokidar = require('chokidar')

var Cat = require('concat-with-sourcemaps')
var assign = require('object-assign')
var flatten = require('flatten')
var expand = require('globby')
var arrify = require('arrify')
var rimraf = require('rimraf')
// locals
var utils = require('./utils')
var Emitter = require('./emitter')
// shorthands
var sep = path.sep
var _ = debug('fly')

function Fly(options) {
	var self = this

	if (!(self instanceof Fly)) {
		throw new TypeError('Fly cannot be invoked without \'new\'')
	}

	options = assign({
		host: {},
		plugins: []
	}, options || {})

	// shorter aliases
	var host = options.host
	var file = options.file
	var plugins = options.plugins

	// ~ `super()`
	Emitter.call(self)

	// attach files & funcs into the curr instance
	assign(self, {
		alert: utils.alert,
		error: utils.error,
		defer: utils.defer,
		log: utils.log,
		host: (typeof host === 'function') ? assign(host, {default: host}) : host,
		debug: _,
		_: {
			filters: []
		},
		tasks: Object.keys(host).reduce(function (_, key) {
			var obj = {}
			obj[key] = host[key].bind(self)
			return assign(_, obj)
		}, {})
	})

	if (!file) {
		return
	}

	self.file = file
	self.plugins = plugins
	self.root = path.dirname(file)

	plugins.forEach(function (el) {
		if (!el.plugin) {
			throw new Error('Did you forget to `npm i -D ' + el.name + '`?')
		}
		// if (plugin.default) plugin = plugin.default
		el.plugin.call(self, debug(el.name.replace('-', ':')), _('load %o', el.name))
	})

	_('chdir %o', self.root)
	process.chdir(self.root)
}

// `Fly extends Emitter`...
util.inherits(Fly, Emitter)
module.exports = Fly

/**
 * Compose a new, yeildable sequence.
 * Resets instance's glob, filters, and writer.
 *
 * @param  {String|Array} globs   The glob selection(s)
 * @param  {Object}       options Any options to pass as `node-glob` config.
 * @return                        The current Fly instance.
 */
Fly.prototype.source = function (globs, options) {
	globs = flatten(arrify(globs))

	assign(this, {
		_: {
			filters: [],
			globs: globs,
			files: Promise.all(globs.map(function (glob) {
				return expand(glob, options)
			}))
		}
	})

	this._.cat = undefined
	_('source %o', this._.globs)
	return this
}

/**
 * Add filter / transform function.
 * Create a closure bound to the current Fly instance.
 *
 * @param {String|Function} name 		The name of filter || the callback
 * @param {Function}        cb      The function: (cb, options) => {}
*/
Fly.prototype.filter = function (name, cb) {
	var type = typeof name

	if (type === 'function') {
		this.filter({cb: name})
	} else if (type === 'object') {
		this._.filters.push(name)
	} else {
		if (typeof this[name] === 'function') {
			throw new RangeError(name + ' method is already defined!')
		}

		this[name] = function (options) {
			var rest = [].slice.call(arguments)
			rest.shift() // remove `options` argument

			debug('fly')(name + ' %o, %o', options, rest)

			return this.filter({
				cb: cb,
				options: options,
				rest: rest
			})
		}
	}

	return this
}

/**
 * Watch IO events within glob selections & run tasks
 * @param  {String} globs   The glob patterns to observe
 * @param  {String} tasks   The list of tasks to run on file changes
 * @param  {Object} options The options for `Fly.proto.start`
 * @return {void}
 */
Fly.prototype.watch = function (globs, tasks, options) {
	options = options || {}
	globs = arrify(globs)

	_('watch %o', globs)

	var self = this
	return self.emit('fly_watch').start(tasks, options).then(function () {
		return chokidar
			.watch(flatten(globs), {ignoreInitial: true})
			.on('all', function (type, file) {
				options.value = null
				self.emit('fly_watch_event', {type: type, file: file})

				// if a single file was passed, then pass in the file to the tasks
				if (path.extname(file)) {
					options.value = file
				}

				return self.start(tasks, options)
			})
			.on('error', self.error)
	})
}

/**
 * Unwrap/Expand source globs as single files, then run fn.
 * @param  {Function} onResolved  The callback to run on 'success'.
 * @param  {Function} onRejected  The callback to run on 'error'.
 * @return {Promise}
 */
Fly.prototype.unwrap = function (onResolved, onRejected) {
	return this._.files.then(flatten).then(onResolved).catch(onRejected)
}

/**
 * Execute a single task.
 * @param  {String} task     The name of the task
 * @param  {Mixed}  value    The initial value to pass into `task`
 * @param  {Object} instance The Fly instance `task` should be bound to
 * @return {Mixed}           The task's resulting value.
 */
Fly.prototype.exec = function * (task, value, instance) {
	instance = instance || this
	value = arrify(value)
	_('run %o', task)

	try {
		var start = getTime()

		this.emit('task_start', {
			task: task
		})

		value = (yield this.host[task].apply(instance, value)) || value

		this.emit('task_complete', {
			task: task,
			duration: getTime() - start
		})
	} catch (e) {
		this.emit('task_error', {
			task: task,
			error: e
		})
	}

	return value
}

/**
 * Run a task sequence of 1 or more.
 * Each task's return value is piped into the next task of sequence.
 *
 * @param  {Array}  tasks   The list of tasks to start
 * @param  {Object} options The options to begin.
 * @return {Promise}
 */
Fly.prototype.start = function (tasks, options) {
	tasks = arrify(tasks.length ? tasks : 'default')

	options = assign({
		parallel: false,
		value: null
	}, options || {})

	_('start %o in ' + (options.parallel ? 'parallel' : 'sequence'), tasks)

	var self = this
	var value = options.value
	var inst = Object.create(self)

	return co.call(self, function * (tasks) {
		if (options.parallel) {
			yield tasks.map(function * (task) {
				yield self.exec(task, value, inst)
			})
		} else {
			for (var task of tasks) {
				value = yield self.exec(task, value, inst)
			}
		}
		return value
	}, [].concat(tasks).filter(function (task) {
		return Object.keys(self.host).indexOf(task) !== -1 || !self.emit('task_not_found', {task: task})
	}))
}

/**
 * Deferred `rimraf` wrapper
 * @param  {String|Array} globs  The glob selection(s) to delete
 * @return {void}
 */
Fly.prototype.clear = function (globs) {
	globs = flatten(arrify(globs))

	_('clear %o', globs)

	return globs.map(function (p) {
		return utils.defer(rimraf)(p)
	})
}

/**
 * Concatenate active `files` to single file.
 * @param  {String} filename  The single output file
 * @return {Fly}      				The current Fly instance.
 */
Fly.prototype.concat = function (filename) {
	this._.cat = new Cat(false, filename, '\n')
	this._.cat.base = filename
	return this
}

/**
 * Resolve a yieldable sequence.
 * Reduces `source` with filters and invokes writer.
 *
 * @param  {Array}  dirs    The target/destination directories
 * @param  {Object} options Target options. Depth refers to path retention
 * @return {Promise}
 */
Fly.prototype.target = function (dirs, options) {
	dirs = arrify(dirs)
	options = assign({}, {depth: -1}, options || {})

	var self = this
	var _cat = self._.cat
	var _filters = self._.filters

	return co(function * () {
		var globs = self._.globs
		var files = yield self._.files

		for (var i = 0; i < globs.length; i++) {
			var glob = globs[i]
			// run thru all files of each glob
			yield files[i].map(function * (file) {
				// get data & stats
				var f = path.parse(file)
				var data = yield utils.read(file)

				// had no data (empty file || attempted a directory read)
				if (!data) {
					return // exit
				}

				// pass files' data thru attached filters
				for (var filter of _filters) {
					// run the filter's closure fn w/data
					var res = yield Promise.resolve(filter.cb.apply(
						self, [data, assign({file: f}, filter.options)].concat(filter.rest)
					))

					// once done, retrieve the final `data` & `ext` of output
					data = res.code || res.js || res.css || res.data || res || data
					f.ext = res.ext || res.extension || f.ext
				}

				if (_cat) {
					_cat.add(f.base, data)
				} else {
					// get shared dir between glob & current filepath
					var dir = path.join.apply(null, f.dir.split(sep).filter(function (filepath) {
						return glob.split(sep).indexOf(filepath) === -1
					}))

					// complete the promise & write the output
					yield resolve(dirs, {
						data: data,
						base: path.join(dir, f.name + f.ext),
						depth: options.depth
					})
				}
			})
		}

		if (_cat) {
			yield resolve(dirs, {
				data: _cat.content,
				base: _cat.base,
				depth: options.depth
			})
		}
	})
}

/**
 * Write utility to help concat and target.
 * @param {String}   dirs           parent directory
 * @param {String}   options.base   directory/file
 * @param {Mixed}    options.data
 * @param {Integer}  options.depth  number of parent directories to keep
 * @param {Function} options.write  promisified writer function
 */
function * resolve(dirs, options) {
	var opts = options || {}
	var writer = opts.hasOwnProperty('writer') ? opts.writer : utils.write

	if (opts.depth > -1) {
		opts.base = dirpaths(opts.base, opts.depth)
	}

	yield flatten(dirs).map(function * (dir) {
		var file = path.join(dir, opts.base)
		mkdirp.sync(path.dirname(file))
		yield writer(file, opts.data)
	})
}

/**
 * Shorten a directory string to # of parent dirs
 * @param  {String}  	full    The original full path
 * @param  {Integer}  depth   The number of levels to retain
 * @return {String}
 */
function dirpaths(full, depth) {
	var arr = full.split(sep)
	var len = arr.length

	if (depth === 0) {
		return arr[len - 1]
	} else if (depth >= len) {
		return full
	}

	return arr.slice(len - 1 - depth).join(sep)
}

/**
 * Get the current timestamp
 * @return {Integer}
 */
function getTime() {
	return (new Date()).getTime()
}
<commit_msg>fix windows path manipulation (#201)<commit_after>'use strict'

var co = require('co')
var path = require('path')
var util = require('util')
var debug = require('debug')
var mkdirp = require('mkdirp')
var chokidar = require('chokidar')

var Cat = require('concat-with-sourcemaps')
var assign = require('object-assign')
var flatten = require('flatten')
var expand = require('globby')
var arrify = require('arrify')
var rimraf = require('rimraf')
// locals
var utils = require('./utils')
var Emitter = require('./emitter')
// shorthands
var sep = '/'
var _ = debug('fly')

function Fly(options) {
	var self = this

	if (!(self instanceof Fly)) {
		throw new TypeError('Fly cannot be invoked without \'new\'')
	}

	options = assign({
		host: {},
		plugins: []
	}, options || {})

	// shorter aliases
	var host = options.host
	var file = options.file
	var plugins = options.plugins

	// ~ `super()`
	Emitter.call(self)

	// attach files & funcs into the curr instance
	assign(self, {
		alert: utils.alert,
		error: utils.error,
		defer: utils.defer,
		log: utils.log,
		host: (typeof host === 'function') ? assign(host, {default: host}) : host,
		debug: _,
		_: {
			filters: []
		},
		tasks: Object.keys(host).reduce(function (_, key) {
			var obj = {}
			obj[key] = host[key].bind(self)
			return assign(_, obj)
		}, {})
	})

	if (!file) {
		return
	}

	self.file = file
	self.plugins = plugins
	self.root = path.dirname(file)

	plugins.forEach(function (el) {
		if (!el.plugin) {
			throw new Error('Did you forget to `npm i -D ' + el.name + '`?')
		}
		// if (plugin.default) plugin = plugin.default
		el.plugin.call(self, debug(el.name.replace('-', ':')), _('load %o', el.name))
	})

	_('chdir %o', self.root)
	process.chdir(self.root)
}

// `Fly extends Emitter`...
util.inherits(Fly, Emitter)
module.exports = Fly

/**
 * Compose a new, yeildable sequence.
 * Resets instance's glob, filters, and writer.
 *
 * @param  {String|Array} globs   The glob selection(s)
 * @param  {Object}       options Any options to pass as `node-glob` config.
 * @return                        The current Fly instance.
 */
Fly.prototype.source = function (globs, options) {
	globs = flatten(arrify(globs))

	assign(this, {
		_: {
			filters: [],
			globs: globs,
			files: Promise.all(globs.map(function (glob) {
				return expand(glob, options)
			}))
		}
	})

	this._.cat = undefined
	_('source %o', this._.globs)
	return this
}

/**
 * Add filter / transform function.
 * Create a closure bound to the current Fly instance.
 *
 * @param {String|Function} name 		The name of filter || the callback
 * @param {Function}        cb      The function: (cb, options) => {}
*/
Fly.prototype.filter = function (name, cb) {
	var type = typeof name

	if (type === 'function') {
		this.filter({cb: name})
	} else if (type === 'object') {
		this._.filters.push(name)
	} else {
		if (typeof this[name] === 'function') {
			throw new RangeError(name + ' method is already defined!')
		}

		this[name] = function (options) {
			var rest = [].slice.call(arguments)
			rest.shift() // remove `options` argument

			debug('fly')(name + ' %o, %o', options, rest)

			return this.filter({
				cb: cb,
				options: options,
				rest: rest
			})
		}
	}

	return this
}

/**
 * Watch IO events within glob selections & run tasks
 * @param  {String} globs   The glob patterns to observe
 * @param  {String} tasks   The list of tasks to run on file changes
 * @param  {Object} options The options for `Fly.proto.start`
 * @return {void}
 */
Fly.prototype.watch = function (globs, tasks, options) {
	options = options || {}
	globs = arrify(globs)

	_('watch %o', globs)

	var self = this
	return self.emit('fly_watch').start(tasks, options).then(function () {
		return chokidar
			.watch(flatten(globs), {ignoreInitial: true})
			.on('all', function (type, file) {
				options.value = null
				self.emit('fly_watch_event', {type: type, file: file})

				// if a single file was passed, then pass in the file to the tasks
				if (path.extname(file)) {
					options.value = file
				}

				return self.start(tasks, options)
			})
			.on('error', self.error)
	})
}

/**
 * Unwrap/Expand source globs as single files, then run fn.
 * @param  {Function} onResolved  The callback to run on 'success'.
 * @param  {Function} onRejected  The callback to run on 'error'.
 * @return {Promise}
 */
Fly.prototype.unwrap = function (onResolved, onRejected) {
	return this._.files.then(flatten).then(onResolved).catch(onRejected)
}

/**
 * Execute a single task.
 * @param  {String} task     The name of the task
 * @param  {Mixed}  value    The initial value to pass into `task`
 * @param  {Object} instance The Fly instance `task` should be bound to
 * @return {Mixed}           The task's resulting value.
 */
Fly.prototype.exec = function * (task, value, instance) {
	instance = instance || this
	value = arrify(value)
	_('run %o', task)

	try {
		var start = getTime()

		this.emit('task_start', {
			task: task
		})

		value = (yield this.host[task].apply(instance, value)) || value

		this.emit('task_complete', {
			task: task,
			duration: getTime() - start
		})
	} catch (e) {
		this.emit('task_error', {
			task: task,
			error: e
		})
	}

	return value
}

/**
 * Run a task sequence of 1 or more.
 * Each task's return value is piped into the next task of sequence.
 *
 * @param  {Array}  tasks   The list of tasks to start
 * @param  {Object} options The options to begin.
 * @return {Promise}
 */
Fly.prototype.start = function (tasks, options) {
	tasks = arrify(tasks.length ? tasks : 'default')

	options = assign({
		parallel: false,
		value: null
	}, options || {})

	_('start %o in ' + (options.parallel ? 'parallel' : 'sequence'), tasks)

	var self = this
	var value = options.value
	var inst = Object.create(self)

	return co.call(self, function * (tasks) {
		if (options.parallel) {
			yield tasks.map(function * (task) {
				yield self.exec(task, value, inst)
			})
		} else {
			for (var task of tasks) {
				value = yield self.exec(task, value, inst)
			}
		}
		return value
	}, [].concat(tasks).filter(function (task) {
		return Object.keys(self.host).indexOf(task) !== -1 || !self.emit('task_not_found', {task: task})
	}))
}

/**
 * Deferred `rimraf` wrapper
 * @param  {String|Array} globs  The glob selection(s) to delete
 * @return {void}
 */
Fly.prototype.clear = function (globs) {
	globs = flatten(arrify(globs))

	_('clear %o', globs)

	return globs.map(function (p) {
		return utils.defer(rimraf)(p)
	})
}

/**
 * Concatenate active `files` to single file.
 * @param  {String} filename  The single output file
 * @return {Fly}      				The current Fly instance.
 */
Fly.prototype.concat = function (filename) {
	this._.cat = new Cat(false, filename, '\n')
	this._.cat.base = filename
	return this
}

/**
 * Resolve a yieldable sequence.
 * Reduces `source` with filters and invokes writer.
 *
 * @param  {Array}  dirs    The target/destination directories
 * @param  {Object} options Target options. Depth refers to path retention
 * @return {Promise}
 */
Fly.prototype.target = function (dirs, options) {
	dirs = arrify(dirs)
	options = assign({}, {depth: -1}, options || {})

	var self = this
	var _cat = self._.cat
	var _filters = self._.filters

	return co(function * () {
		var globs = self._.globs
		var files = yield self._.files

		for (var i = 0; i < globs.length; i++) {
			var glob = globs[i]
			// run thru all files of each glob
			yield files[i].map(function * (file) {
				// get data & stats
				var f = path.parse(file)
				var data = yield utils.read(file)

				// had no data (empty file || attempted a directory read)
				if (!data) {
					return // exit
				}

				// pass files' data thru attached filters
				for (var filter of _filters) {
					// run the filter's closure fn w/data
					var res = yield Promise.resolve(filter.cb.apply(
						self, [data, assign({file: f}, filter.options)].concat(filter.rest)
					))

					// once done, retrieve the final `data` & `ext` of output
					data = res.code || res.js || res.css || res.data || res || data
					f.ext = res.ext || res.extension || f.ext
				}

				if (_cat) {
					_cat.add(f.base, data)
				} else {
					// complete the promise & write the output
					yield resolve(dirs, {
						data: data,
						depth: options.depth,
						base: f.dir.split(sep).filter(function (filepath) {
							return glob.split(sep).indexOf(filepath) === -1
						}).concat(f.name + f.ext).join(sep)
					})
				}
			})
		}

		if (_cat) {
			yield resolve(dirs, {
				data: _cat.content,
				base: _cat.base,
				depth: options.depth
			})
		}
	})
}

/**
 * Write utility to help concat and target.
 * @param {String}   dirs           parent directory
 * @param {String}   options.base   directory/file
 * @param {Mixed}    options.data
 * @param {Integer}  options.depth  number of parent directories to keep
 * @param {Function} options.write  promisified writer function
 */
function * resolve(dirs, options) {
	var opts = options || {}
	var writer = opts.hasOwnProperty('writer') ? opts.writer : utils.write

	if (opts.depth > -1) {
		opts.base = dirpaths(opts.base, opts.depth)
	}

	yield flatten(dirs).map(function * (dir) {
		var file = path.join(dir, opts.base)
		mkdirp.sync(path.dirname(file))
		yield writer(file, opts.data)
	})
}

/**
 * Shorten a directory string to # of parent dirs
 * @param  {String}  	full    The original full path
 * @param  {Integer}  depth   The number of levels to retain
 * @return {String}
 */
function dirpaths(full, depth) {
	var arr = full.split(sep)
	var len = arr.length

	if (depth === 0) {
		return arr[len - 1]
	} else if (depth >= len) {
		return full
	}

	return arr.slice(len - 1 - depth).join(sep)
}

/**
 * Get the current timestamp
 * @return {Integer}
 */
function getTime() {
	return (new Date()).getTime()
}
<|endoftext|>


<commit_before>/**
 * Get git config values.
 * @function get
 * @param {string} [namespace] - Namespace to get.
 * @param {object} options - Optional settings.
 * @param {string} [options.location] - Config file location. (global, system, or local)
 * @param {function} callback - Callback when done.
 */

"use strict";

var argx = require('argx'),
    async = require('async'),
    childProcess = require('child_process'),
    os = require('os'),
    objnest = require('objnest');

/** @lends get */
function get(namespace, options, callback) {
    var args = argx(arguments);
    callback = args.pop('function') || argx.noop;
    options = args.pop('object') || {};
    namespace = args.shift('string') || null;
    async.waterfall([
        function (callback) {
            var cmd = _getCommand(options.location);
            childProcess.exec(cmd, callback);
        },
        function (stdout, stderr, callback) {
            if (stderr) {
                callback(new Error(stderr));
                return;
            }
            var config = _parseStdout(stdout, namespace);
            callback(null, config);
        }
    ], callback);
}

get.sync = function (namespace, options) {
    var args = argx(arguments);
    options = args.pop('object') || {};
    namespace = args.shift('string') || null;
    var cmd = _getCommand(options.location);
    var stdout = childProcess.execSync(cmd);
    return _parseStdout(stdout, namespace);
};

function _getCommand(location) {
    var cmd = 'git config --list';
    if (location) {
        cmd += (' --' + location);
    }
    return cmd;
}
function _parseStdout(stdout, namespace) {
    var config = {};
    String(stdout).split(os.EOL).forEach(function (line) {
        if (!line) {
            return;
        }
        var keyVal = line.split('=');
        var key = keyVal.shift(),
            val = keyVal.pop();
        if (val === undefined) {
            return;
        }
        config[key] = val;
    });
    config = objnest.expand(config);
    if (namespace) {
        var namespaceSplit = namespace.split('.')
        if (namespaceSplit.length === 1) {
            config = config[namespace];
        } else {
            namespaceSplit.forEach(function (namespace) {
                config = config[namespace]
            })
        }
    }
    return config;
}

module.exports = get;
<commit_msg>Simplifies dot notation parsing<commit_after>/**
 * Get git config values.
 * @function get
 * @param {string} [namespace] - Namespace to get.
 * @param {object} options - Optional settings.
 * @param {string} [options.location] - Config file location. (global, system, or local)
 * @param {function} callback - Callback when done.
 */

"use strict";

var argx = require('argx'),
    async = require('async'),
    childProcess = require('child_process'),
    os = require('os'),
    objnest = require('objnest');

/** @lends get */
function get(namespace, options, callback) {
    var args = argx(arguments);
    callback = args.pop('function') || argx.noop;
    options = args.pop('object') || {};
    namespace = args.shift('string') || null;
    async.waterfall([
        function (callback) {
            var cmd = _getCommand(options.location);
            childProcess.exec(cmd, callback);
        },
        function (stdout, stderr, callback) {
            if (stderr) {
                callback(new Error(stderr));
                return;
            }
            var config = _parseStdout(stdout, namespace);
            callback(null, config);
        }
    ], callback);
}

get.sync = function (namespace, options) {
    var args = argx(arguments);
    options = args.pop('object') || {};
    namespace = args.shift('string') || null;
    var cmd = _getCommand(options.location);
    var stdout = childProcess.execSync(cmd);
    return _parseStdout(stdout, namespace);
};

function _getCommand(location) {
    var cmd = 'git config --list';
    if (location) {
        cmd += (' --' + location);
    }
    return cmd;
}
function _parseStdout(stdout, namespace) {
    var config = {};
    String(stdout).split(os.EOL).forEach(function (line) {
        if (!line) {
            return;
        }
        var keyVal = line.split('=');
        var key = keyVal.shift(),
            val = keyVal.pop();
        if (val === undefined) {
            return;
        }
        config[key] = val;
    });
    config = objnest.expand(config);
    if (namespace) {
        var namespaceSplit = namespace.split('.')

        namespaceSplit.forEach(function (namespace) {
            config = config[namespace]
        })
    }
    return config;
}

module.exports = get;
<|endoftext|>