/**
 * This component is used in {@link Ext.navigation.View} to control animations in the toolbar. You should never need to
 * interact with the component directly, unless you are subclassing it.
 * @private
 * @author Robert Dougan <rob@sencha.com>
 */
Ext.define('Ext.navigation.Bar', {
    extend: 'Ext.TitleBar',

    requires: [
        'Ext.Button',
        'Ext.Spacer'
    ],

    // @private
    isToolbar: true,

    config: {
        /**
         * @cfg
         * @inheritdoc
         */
        baseCls: Ext.baseCSSPrefix + 'toolbar',

        /**
         * @cfg
         * @inheritdoc
         */
        cls: Ext.baseCSSPrefix + 'navigation-bar',

        /**
         * @cfg {String} ui
         * Style options for Toolbar. Either 'light' or 'dark'.
         * @accessor
         */
        ui: 'dark',

        /**
         * @cfg {String} title
         * The title of the toolbar. You should NEVER set this, it is used internally. You set the title of the
         * navigation bar by giving a navigation views children a title configuration.
         * @private
         * @accessor
         */
        title: null,

        /**
         * @cfg
         * @hide
         * @accessor
         */
        defaultType: 'button',

        /**
         * @cfg
         * @ignore
         * @accessor
         */
        layout: {
            type: 'hbox'
        },

        /**
         * @cfg {Array/Object} items The child items to add to this NavigationBar. The {@link #cfg-defaultType} of
         * a NavigationBar is {@link Ext.Button}, so you do not need to specify an `xtype` if you are adding
         * buttons.
         *
         * You can also give items a `align` configuration which will align the item to the `left` or `right` of
         * the NavigationBar.
         * @hide
         * @accessor
         */

        /**
         * @cfg {String} defaultBackButtonText
         * The text to be displayed on the back button if:
         * a) The previous view does not have a title
         * b) The {@link #useTitleForBackButtonText} configuration is true.
         * @private
         * @accessor
         */
        defaultBackButtonText: 'Back',

        /**
         * @cfg {Object} animation
         * @private
         * @accessor
         */
        animation: {
            duration: 300
        },

        /**
         * @cfg {Boolean} useTitleForBackButtonText
         * Set to false if you always want to display the {@link #defaultBackButtonText} as the text
         * on the back button. True if you want to use the previous views title.
         * @private
         * @accessor
         */
        useTitleForBackButtonText: null,

        /**
         * @cfg {Ext.navigation.View} view A reference to the navigation view this bar is linked to.
         * @private
         * @accessor
         */
        view: null,

        /**
         * @cfg {Boolean} androidAnimation Optionally enable CSS transforms on Android 2
         * for NavigationBar animations.  Note that this may cause flickering if the
         * NavigationBar is hidden.
         * @accessor
         */
        android2Transforms: false,

        /**
         * @cfg {Ext.Button/Object} backButton The configuration for the back button
         * @private
         * @accessor
         */
        backButton: {
            align: 'left',
            ui: 'back',
            hidden: true
        }
    },

    platformConfig: [{
        theme: ['Blackberry', 'Blackberry103'],
        animation: false
    }],

    /**
     * @event back
     * Fires when the back button was tapped.
     * @param {Ext.navigation.Bar} this This bar
     */

    constructor: function(config) {
        config = config || {};

        if (!config.items) {
            config.items = [];
        }

        this.backButtonStack = [];
        this.activeAnimations = [];

        this.callParent([config]);
    },

    /**
     * @private
     */
    applyBackButton: function(config) {
        return Ext.factory(config, Ext.Button, this.getBackButton());
    },

    /**
     * @private
     */
    updateBackButton: function(newBackButton, oldBackButton) {
        if (oldBackButton) {
            this.remove(oldBackButton);
        }

        if (newBackButton) {
            this.add(newBackButton);

            newBackButton.on({
                scope: this,
                tap: this.onBackButtonTap
            });
        }
    },

    onBackButtonTap: function() {
        this.fireEvent('back', this);
    },

    /**
     * @private
     */
    updateView: function(newView) {
        var me = this,
            backButton = me.getBackButton(),
            innerItems, i, backButtonText, item, title, titleText;

        me.getItems();

        if (newView) {
            //update the back button stack with the current inner items of the view
            innerItems = newView.getInnerItems();
            for (i = 0; i < innerItems.length; i++) {
                item = innerItems[i];
                title = (item.getTitle) ? item.getTitle() : item.config.title;

                me.backButtonStack.push(title || ' ');
            }

            titleText = me.getTitleText();

            if (titleText === undefined) {
                titleText = '';
            }

            me.setTitle(titleText);

            backButtonText = me.getBackButtonText();
            if (backButtonText) {
                backButton.setText(backButtonText);
                backButton.show();
            }
        }
    },

    /**
     * @private
     */
    onViewAdd: function(view, item) {
        var me = this,
            backButtonStack = me.backButtonStack,
            hasPrevious, title;

        me.endAnimation();

        title = (item.getTitle) ? item.getTitle() : item.config.title;

        backButtonStack.push(title || ' ');
        hasPrevious = backButtonStack.length > 1;

        me.doChangeView(view, hasPrevious, false);
    },

    /**
     * @private
     */
    onViewRemove: function(view) {
        var me = this,
            backButtonStack = me.backButtonStack,
            hasPrevious;

        me.endAnimation();
        backButtonStack.pop();
        hasPrevious = backButtonStack.length > 1;

        me.doChangeView(view, hasPrevious, true);
    },

    /**
     * @private
     */
    doChangeView: function(view, hasPrevious, reverse) {
        var me = this,
            leftBox = me.leftBox,
            leftBoxElement = leftBox.element,
            titleComponent = me.titleComponent,
            titleElement = titleComponent.element,
            backButton = me.getBackButton(),
            titleText = me.getTitleText(),
            backButtonText = me.getBackButtonText(),
            animation = me.getAnimation() && view.getLayout().getAnimation(),
            animated = animation && animation.isAnimation && view.isPainted(),
            properties, leftGhost, titleGhost, leftProps, titleProps;

        if (animated) {
            leftGhost = me.createProxy(leftBox.element);
            leftBoxElement.setStyle('opacity', '0');
            backButton.setText(backButtonText);
            backButton[hasPrevious ? 'show' : 'hide']();

            titleGhost = me.createProxy(titleComponent.element.getParent());
            titleElement.setStyle('opacity', '0');
            me.setTitle(titleText);

            properties = me.measureView(leftGhost, titleGhost, reverse);
            leftProps = properties.left;
            titleProps = properties.title;

            me.isAnimating = true;
            me.animate(leftBoxElement, leftProps.element);
            me.animate(titleElement, titleProps.element, function() {
                titleElement.setLeft(properties.titleLeft);
                me.isAnimating = false;
                me.refreshTitlePosition();
            });

            if (Ext.browser.is.AndroidStock2 && !this.getAndroid2Transforms()) {
                leftGhost.ghost.destroy();
                titleGhost.ghost.destroy();
            }
            else {
                me.animate(leftGhost.ghost, leftProps.ghost);
                me.animate(titleGhost.ghost, titleProps.ghost, function() {
                    leftGhost.ghost.destroy();
                    titleGhost.ghost.destroy();
                });
            }
        }
        else {
            if (hasPrevious) {
                backButton.setText(backButtonText);
                backButton.show();
            }
            else {
                backButton.hide();
            }
            me.setTitle(titleText);
        }
    },

    /**
     * Calculates and returns the position values needed for the back button when you are pushing a title.
     * @private
     */
    measureView: function(oldLeft, oldTitle, reverse) {
        var me = this,
            barElement = me.element,
            newLeftElement = me.leftBox.element,
            titleElement = me.titleComponent.element,
            minOffset = Math.min(barElement.getWidth() / 3, 200),
            newLeftWidth = newLeftElement.getWidth(),
            barX = barElement.getX(),
            barWidth = barElement.getWidth(),
            titleX = titleElement.getX(),
            titleLeft = titleElement.getLeft(),
            titleWidth = titleElement.getWidth(),
            oldLeftX = oldLeft.x,
            oldLeftWidth = oldLeft.width,
            oldLeftLeft = oldLeft.left,
            useLeft = Ext.browser.is.AndroidStock2 && !this.getAndroid2Transforms(),
            newOffset, oldOffset, leftAnims, titleAnims, omega, theta;

        theta = barX - oldLeftX - oldLeftWidth;
        if (reverse) {
            newOffset = theta;
            oldOffset = Math.min(titleX - oldLeftWidth, minOffset);
        }
        else {
            oldOffset = theta;
            newOffset = Math.min(titleX - barX, minOffset);
        }

        if (useLeft) {
            leftAnims = {
                element: {
                    from: {
                        left: newOffset,
                        opacity: 1
                    },
                    to: {
                        left: 0,
                        opacity: 1
                    }
                }
            };
        }
        else {
            leftAnims = {
                element: {
                    from: {
                        transform: {
                            translateX: newOffset
                        },
                        opacity: 0
                    },
                    to: {
                        transform: {
                            translateX: 0
                        },
                        opacity: 1
                    }
                },
                ghost: {
                    to: {
                        transform: {
                            translateX: oldOffset
                        },
                        opacity: 0
                    }
                }
            };
        }

        theta = barX - titleX + newLeftWidth;
        if ((oldLeftLeft + titleWidth) > titleX) {
            omega = barX - titleX - titleWidth;
        }

        if (reverse) {
            titleElement.setLeft(0);

            oldOffset = barX + barWidth - titleX - titleWidth;

            if (omega !== undefined) {
                newOffset = omega;
            }
            else {
                newOffset = theta;
            }
        }
        else {
            newOffset = barX + barWidth - titleX - titleWidth;

            if (omega !== undefined) {
                oldOffset = omega;
            }
            else {
                oldOffset = theta;
            }

            newOffset = Math.max(titleLeft, newOffset);
        }

        if (useLeft) {
            titleAnims = {
                element: {
                    from: {
                        left: newOffset,
                        opacity: 1
                    },
                    to: {
                        left: titleLeft,
                        opacity: 1
                    }
                }
            };
        }
        else {
            titleAnims = {
                element: {
                    from: {
                        transform: {
                            translateX: newOffset
                        },
                        opacity: 0
                    },
                    to: {
                        transform: {
                            translateX: titleLeft
                        },
                        opacity: 1
                    }
                },
                ghost: {
                    to: {
                        transform: {
                            translateX: oldOffset
                        },
                        opacity: 0
                    }
                }
            };
        }

        return {
            left: leftAnims,
            title: titleAnims,
            titleLeft: titleLeft
        };
    },

    /**
     * Helper method used to animate elements.
     * You pass it an element, objects for the from and to positions an option onEnd callback called when the animation is over.
     * Normally this method is passed configurations returned from the methods such as #measureTitle(true) etc.
     * It is called from the #pushLeftBoxAnimated, #pushTitleAnimated, #popBackButtonAnimated and #popTitleAnimated
     * methods.
     *
     * If the current device is Android, it will use top/left to animate.
     * If it is anything else, it will use transform.
     * @private
     */
    animate: function(element, config, callback) {
        var me = this,
            animation;

        //reset the left of the element
        element.setLeft(0);

        config = Ext.apply(config, {
            element: element,
            easing: 'ease-in-out',
            duration: me.getAnimation().duration || 250,
            preserveEndState: true
        });

        animation = new Ext.fx.Animation(config);
        animation.on('animationend', function() {
            if (callback) {
                callback.call(me);
            }
        }, me);

        Ext.Animator.run(animation);
        me.activeAnimations.push(animation);
    },

    endAnimation: function() {
        var activeAnimations = this.activeAnimations,
            animation, i, ln;

        if (activeAnimations) {
            ln = activeAnimations.length;
            for (i = 0; i < ln; i++) {
                animation = activeAnimations[i];
                if (animation.isAnimating) {
                    animation.stopAnimation();
                }
                else {
                    animation.destroy();
                }
            }
            this.activeAnimations = [];
        }
    },

    refreshTitlePosition: function() {
        if (!this.isAnimating) {
            this.callParent();
        }
    },

    /**
     * Returns the text needed for the current back button at anytime.
     * @private
     */
    getBackButtonText: function() {
        var text = this.backButtonStack[this.backButtonStack.length - 2],
            useTitleForBackButtonText = this.getUseTitleForBackButtonText();

        if (!useTitleForBackButtonText) {
            if (text) {
                text = this.getDefaultBackButtonText();
            }
        }

        return text;
    },

    /**
     * Returns the text needed for the current title at anytime.
     * @private
     */
    getTitleText: function() {
        return this.backButtonStack[this.backButtonStack.length - 1];
    },

    /**
     * Handles removing back button stacks from this bar
     * @private
     */
    beforePop: function(count) {
        count--;
        for (var i = 0; i < count; i++) {
            this.backButtonStack.pop();
        }
    },

    /**
     * We override the hidden method because we don't want to remove it from the view using display:none. Instead we just position it off
     * the screen, much like the navigation bar proxy. This means that all animations, pushing, popping etc. all still work when if you hide/show
     * this bar at any time.
     * @private
     */
    doSetHidden: function(hidden) {
        if (!hidden) {
            this.element.setStyle({
                position: 'relative',
                top: 'auto',
                left: 'auto',
                width: 'auto'
            });
        } else {
            this.element.setStyle({
                position: 'absolute',
                top: '-1000px',
                left: '-1000px',
                width: this.element.getWidth() + 'px'
            });
        }
    },

    /**
     * Creates a proxy element of the passed element, and positions it in the same position, using absolute positioning.
     * The createNavigationBarProxy method uses this to create proxies of the backButton and the title elements.
     * @private
     */
    createProxy: function(element) {
        var ghost, x, y, left, width;

        ghost = element.dom.cloneNode(true);
        ghost.id = element.id + '-proxy';

        //insert it into the toolbar
        element.getParent().dom.appendChild(ghost);

        //set the x/y
        ghost = Ext.get(ghost);
        x = element.getX();
        y = element.getY();
        left = element.getLeft();
        width = element.getWidth();
        ghost.setStyle('position', 'absolute');
        ghost.setX(x);
        ghost.setY(y);
        ghost.setHeight(element.getHeight());
        ghost.setWidth(width);

        return {
            x: x,
            y: y,
            left: left,
            width: width,
            ghost: ghost
        };
    }
});


'use strict';

var debug = require('debug')('metalsmith-untemplatize');

/**
 * Expose `plugin`.
 */
module.exports = plugin;

/**
 * A Metalsmith plugin to extract untemplatized file contents.
 *
 * @param  {Object} options
 * @return {Function}
 */
function plugin(options) {
  options = options || {};
  options.key = options.key || 'untemplatized';
  return function(files, metalsmith, done){
    setImmediate(done);
    Object.keys(files).forEach(function(file){
      debug('checking file: %s', file);
      var data = files[file];
      var contents = data.contents.toString().replace(/^\n+/g, '');
      debug('storing untemplatized content: %s', file);
      data[options.key] = new Buffer(contents);
    });
  };
}


/**
 * @class kad-telemetry/metrics/latency
 */

'use strict'

var Message = require('../../kad/index.js').Message
var inherits = require('util').inherits
var Metric = require('../metric')

/**
 * Defines a metric that measures latency by last req/res
 * @constructor
 */
function LatencyMetric () {
  if (!(this instanceof LatencyMetric)) {
    return new LatencyMetric()
  }

  Metric.call(this)

  this.key = 'latency'
  this.default = [0]
  this.hooks = [{
    trigger: 'before',
    event: 'send',
    handler: this._start
  }, {
    trigger: 'before',
    event: 'receive',
    handler: this._stop
  }]

  this._tests = {}

  setInterval(this._expireTimeouts.bind(this), LatencyMetric.TEST_TIMEOUT)
}

inherits(LatencyMetric, Metric)

LatencyMetric.TEST_TIMEOUT = 5000 // 5 seconds

/**
 * Begins the latency test
 * #_start
 * @param {telemetry.metrics.LatencyMetric} self
 * @param {telemetry.Persistence} profiles
 * @returns {Function}
 */
LatencyMetric.prototype._start = function (self) {
  return function (buffer, contact, next) {
    var message = Message.fromBuffer(buffer)

    if (Message.isRequest(message)) {
      self._tests[message.id] = {
        started: Date.now()
      }
    }

    next()
  }
}

/**
 * Ends the latency test
 * #_stop
 * @param {telemetry.metrics.LatencyMetric} self
 * @param {telemetry.Persistence} profiles
 * @returns {Function}
 */
LatencyMetric.prototype._stop = function (self, profiles) {
  return function (message, contact, next) {
    var cb = function (err, profile) {
      if (Message.isRequest(message)) {
        return next()
      }

      var test = self._tests[message.id]

      if (test) {
        self.setMetric(profile, Date.now() - test.started)
        profiles.setProfile(contact, profile, function () {
          next()
        })
      } else {
        next()
      }
    }
    profiles.getProfile(contact, cb)
  }
}

/**
 * Starts an interval of checking for expired tests and cleaning up
 * #_startTestExpiration
 */
LatencyMetric.prototype._expireTimeouts = function () {
  for (var id in this._tests) {
    if (Date.now() > this._tests[id].started + LatencyMetric.TEST_TIMEOUT) {
      delete this._tests[id]
    }
  }
}

/**
 * Returns the score for a given metric value
 * #score
 * @param {Array} value
 * @returns {Number}
 */
LatencyMetric.score = function (value) {
  return (LatencyMetric.TEST_TIMEOUT - value[0]) / LatencyMetric.TEST_TIMEOUT
}

module.exports = LatencyMetric


var http = require('http');
var https = require('https');
var defer = require('node-promise').defer;
var parseURL = require('url').parse;
var querystring = require('querystring');

module.exports = {
  request: request,
  ajax: request,
  get: function(url, opt, fn, dataType){
    return reqWithMethod('GET', url, opt, fn, dataType);
  },
  post: function(url, opt, fn, dataType){
    return reqWithMethod('POST', url, opt, fn, dataType);
  },
  delete: function(url, opt, fn, dataType){
    return reqWithMethod('DELETE', url, opt,fn,dataType);
  },
  put: function(url, opt, fn, dataType){
    return reqWithMethod('PUT', url, opt, fn,dataType);
  },
  head: function(url, opt, fn){
    return reqWithMethod('HEAD', url, opt,fn);
  }
};

var defaultOpt = {
  // type: 'GET',
  // method: 'GET',
  url: '',
  dataType:null, //json or others
  //contentType: 'application/x-www-form-urlencoded',
  data: null,
  timeout: 100000,
  headers: {},
  success: function() {},
  error: function() {},
  complete: function() {}
};

function reqWithMethod(method, url, data, fn, dataType) {

  var opt= {};
  if (typeof(data) == 'function') {
    opt = {
      method: method,
      dataType: dataType,
      success: data
    }
  }
  else if (typeof(fn) == 'function') {

    opt = {
      method: method,
      data: data,
      dataType: dataType,
      success: fn
    }
  }
  else {
    opt = {
      method: method||'GET',
      url: url,
      dataType: dataType,
      data: data
    }
  }
  return request(url, opt);

}

function request(url, opt) {

  var deferred = defer();

  if (typeof(url) == 'string') {
    if(typeof(opt)=='undefined') opt = {};
    opt.url = url;
  } else if (typeof(url) == 'object' && typeof(opt) == 'undefined') {
    opt = url;
    url = null;
  } else {
    throw new Error('Please check the args');
  }

  opt = wrapDefault(opt, defaultOpt);

  //method
  var method = (opt.method||'GET').toUpperCase();
  opt.method = method;

  //headers, key tolowercase
  var hd = {};
  Object.keys(opt.headers).forEach(function(k) {
    hd[k] = opt.headers[k];
  });
  opt.headers = hd;

  var bodyString = null;
  if(method=='GET'||method=='HEAD'||method=='DELETE'){
    if(opt.data){
      var qstr = querystring.stringify(opt.data);

      if(opt.url.indexOf('?')!=-1){
        opt.url+='&'+qstr;
      }else{
        opt.url+='?'+qstr;
      }
    }
  }else if(method=='PUT' || method == 'POST'){

    var reqContentType = opt.contentType || opt.headers['content-type'];

    if(!reqContentType){
      reqContentType = opt.headers['content-type'] = (opt.method == "PUT" && typeof(opt.data) == 'object')
      ? 'application/json'
      : 'application/x-www-form-urlencoded';
    }

    if (reqContentType.indexOf('application/x-www-form-urlencoded') == 0 ){
      if(typeof(opt.data) == 'object'){
        bodyString = querystring.stringify(opt.data);
      }
      else{
        bodyString = opt.data + '';
      }
    }
    else{
      if(typeof(opt.data) == 'object'){
        bodyString = JSON.stringify(opt.data);
      }
      else{
        bodyString = opt.data+'';
      }

    }
    opt.headers['content-length']= Buffer.byteLength(bodyString);
  }

  var pathInfo = parseURL(opt.url);

  var client = http;
  if(pathInfo.protocol == 'https:'){
     pathInfo.rejectUnauthorized = false;
     client = https;
  }

  pathInfo.headers = opt.headers;
  pathInfo.method = opt.method;
  var aborted = false;
  var tid = null;

  var req = client.request(pathInfo, function(res) {

    var bf = new Buffer([]);
    var contentType = res.headers['content-type'];
    var status = res.statusCode;

    res.on('data', function(chunck) {
      bf = Buffer.concat([bf, chunck], bf.length + chunck.length);
    });

    res.on('end', function() {
      if(aborted)return;
      aborted = true;
      clearTimeout(tid);

      var result = decodeResult(contentType, opt.dataType, bf.toString());
      opt.complete(result, status,res.headers);
      if (status < 400) {
        //success
        opt.success(result, status,res.headers);
        deferred.resolve({data:result,status:status,headers: res.headers});

      } else {
        //error
        opt.error(result, status,res.headers);
        deferred.reject({data:result,error:result,status:status,headers: res.headers});
      }

    });

    res.on('error', function(err) {
      if(aborted)return;
      aborted = true;

      err = decodeResult(contentType, opt.dataType, err);
      opt.complete(err, status,res.headers);

      //error
      opt.error(err, status,res.headers);
      deferred.reject({data:err,error:err,status:status,headers: res.headers});

      clearTimeout(tid);
    });

  });

  req.on('error', function(err){
     //error
     if(aborted)return;
      aborted = true;
      clearTimeout(tid);

      opt.complete(err, 500, {});

      opt.error(err, 500, {});
      deferred.reject({data:err,error:err,status:500,headers: {}});
  });

  if (opt.timeout) {
    tid = setTimeout(function() {
      aborted = true;

      var msg = 'timeout';

      opt.complete(msg, 502,{});

      //error
      opt.error(msg, 502,{});

      deferred.reject({data:msg,error:msg,status:502,headers:{}});
      req.abort();
    }, opt.timeout);
  }

  if (bodyString) {
    req.write(bodyString);
  }

  req.end();

  //extends promise,  add success,error stuff
  var keep_success=[];
  var keep_error = [];
  deferred.promise.done =
  deferred.promise.success = function(fn){
    keep_success.push(fn);
    return this;
  }
  deferred.promise.fail =
  deferred.promise.error = function(fn){
    keep_error.push(fn);
    return this;
  }

  deferred.promise.then(function success(){
    var arr = Array.prototype.slice.call(arguments,0);
    keep_success.forEach(function(n){
      n.apply(deferred.promise, arr);
    });
  }, function error(){
    var arr = Array.prototype.slice.call(arguments,0);
    keep_error.forEach(function(n){
      n.apply(deferred.promise, arr);
    });
  });

  return deferred.promise;
}

function wrapDefault(opt, defaultOpt) {
  opt = opt || {};
  for (var k in defaultOpt) {
    if (typeof(opt[k]) == 'undefined') {
      opt[k] = defaultOpt[k];
    }
  }

  opt.method = opt.method || opt.type;
  opt.content = opt.content || opt.data;

  return opt;
}

//dataType: json , others
function decodeResult(contentType, dataType, result) {
  if(dataType=='json'){
    try {
      result = JSON.parse(result);
      return result;
    } catch (e) {}
  }

  if (contentType && contentType.indexOf('application/json')==0) {
    try {
      result = JSON.parse(result);
    } catch (e) {}
  }
  //todo: xml result
  return result;
}


module.exports = ObjectToCsvStream

var TransformStream = require('stream').Transform
  , extend = require('lodash.assign')

/**
 * Default map will take the first this.header.length items from the object as
 * the row values
 */
function defaultMapFn(data) {
  return Object.keys(data).slice(0, this.headers.length).map(function(key) {
    return data[key]
  })
}

function ObjectToCsvStream(headers, options) {
  if (!Array.isArray(headers)) throw new TypeError('Headers must be an array')
  this.headers = headers

  this.options = extend(
    { quote: '"'
    , mapFn: defaultMapFn.bind(this)
    , eol: '\n' }, options)

  TransformStream.call(this)
  this._writableState.objectMode = true
  this._readableState.objectMode = false
  this._headersSent = false

  // Send the headers out first
  this.push(headers.map(this.stringEscape.bind(this)).join(',') + this.options.eol)

}

ObjectToCsvStream.prototype = Object.create(TransformStream.prototype)

ObjectToCsvStream.prototype.stringEscape = function(s) {
  return this.options.quote + s + this.options.quote
}

ObjectToCsvStream.prototype._transform = function (data, encoding, callback) {
  var rowData = this.options.mapFn(data)
    , error
  if (!Array.isArray(rowData)) {
    error = new TypeError('Mapped data is not an Array as expected')
    this.emit('error', error)
    return callback(error)
  }
  this.push(rowData.map(this.stringEscape.bind(this)).join(',') + this.options.eol)
  callback()

}


/**
 * The main class and interface of the schedule module
 */
const PriorityQueue = require('./priorityQueue');
const Job = require('./job.js');

const map = {};

function comparator(e1, e2) {
    return e1.time > e2.time;
}
const queue = PriorityQueue.createPriorityQueue(comparator);

let timer;

// The accuracy of the scheduler, it will affect the performance when the schedule tasks are
// crowded together
const accuracy = 10;

/**
 * Clear last timeout and schedule the next job, it will automaticly run the job that
 * need to run now
 * @param job The job need to schedule
 * @return void
 */
function setTimer(job) {
    clearTimeout(timer);

    timer = setTimeout(excuteJob, job.excuteTime() - Date.now());    // eslint-disable-line
}
/**
 * Return, but not remove the next valid job
 * @return Next valid job
 */
function peekNextJob() {
    if (queue.size() <= 0) { return null; }

    let job = null;

    do {
        job = map[queue.peek().id];
        if (!job) queue.pop();
    } while (!job && queue.size() > 0);

    return (job) || null;
}

/**
 * The function used to ran the schedule job, and setTimeout for next running job
 */
function excuteJob() {
    let job = peekNextJob();
    while (!!job && (job.excuteTime() - Date.now()) < accuracy) {
        job.run();
        queue.pop();

        const nextTime = job.nextTime();

        if (nextTime === null) {
            delete map[job.id];
        } else {
            queue.offer({ id: job.id, time: nextTime });
        }
        job = peekNextJob();
    }

    // If all the job have been canceled
    if (!job) { return; }

    // Run next schedule
    setTimer(job);
}

/**
 * Schedule a new Job
 */
function scheduleJob(trigger, jobFunc, jobData) {
    const job = Job.createJob(trigger, jobFunc, jobData);
    const excuteTime = job.excuteTime();
    const id = job.id;

    map[id] = job;
    const element = {
        id: id,
        time: excuteTime
    };

    const curJob = queue.peek();
    if (!curJob || excuteTime < curJob.time) {
        queue.offer(element);
        setTimer(job);

        return job.id;
    }

    queue.offer(element);
    return job.id;
}

/**
 * Cancel Job
 */
function cancelJob(id) {
    const curJob = queue.peek();
    if (curJob && id === curJob.id) { // to avoid queue.peek() is null
        queue.pop();
        delete map[id];

        clearTimeout(timer);
        excuteJob();
    }
    delete map[id];
    return true;
}

/**
 * Return and remove the next valid job
 * @return Next valid job
 */
function getNextJob() {
    let job = null;

    while (!job && queue.size() > 0) {
        const id = queue.pop().id;
        job = map[id];
    }

    return (job) || null;
}

module.exports.scheduleJob = scheduleJob;
module.exports.cancelJob = cancelJob;


//@tag foundation,core
//@define Ext.Base
//@require Ext.Date

/**
 * @class Ext.Base
 * @author Jacky Nguyen <jacky@sencha.com>
 *
 * The root of all classes created with {@link Ext#define}.
 *
 * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base. All prototype and static
 * members of this class are inherited by all other classes.
 *
 * See the [Class System Guide](../../../core_concepts/class_system.html) for more.
 *
 */
(function(flexSetter) {

var noArgs = [],
    Base = function(){};

    // These static properties will be copied to every newly created class with {@link Ext#define}
    Ext.apply(Base, {
        $className: 'Ext.Base',

        $isClass: true,

        /**
         * Create a new instance of this Class.
         *
         *     Ext.define('My.cool.Class', {
         *         // ...
         *     });
         *
         *     My.cool.Class.create({
         *         someConfig: true
         *     });
         *
         * All parameters are passed to the constructor of the class.
         *
         * @return {Object} the created instance.
         * @static
         * @inheritable
         */
        create: function() {
            return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
        },

        /**
         * @private
         * @static
         * @inheritable
         */
        extend: function(parent) {
            var parentPrototype = parent.prototype,
                prototype, i, ln, name, statics;

            prototype = this.prototype = Ext.Object.chain(parentPrototype);
            prototype.self = this;

            this.superclass = prototype.superclass = parentPrototype;

            if (!parent.$isClass) {
                Ext.apply(prototype, Ext.Base.prototype);
                prototype.constructor = function() {
                    parentPrototype.constructor.apply(this, arguments);
                };
            }

            //<feature classSystem.inheritableStatics>
            // Statics inheritance
            statics = parentPrototype.$inheritableStatics;

            if (statics) {
                for (i = 0,ln = statics.length; i < ln; i++) {
                    name = statics[i];

                    if (!this.hasOwnProperty(name)) {
                        this[name] = parent[name];
                    }
                }
            }
            //</feature>

            if (parent.$onExtended) {
                this.$onExtended = parent.$onExtended.slice();
            }

            //<feature classSystem.config>
            prototype.config = prototype.defaultConfig = new prototype.configClass;
            prototype.initConfigList = prototype.initConfigList.slice();
            prototype.initConfigMap = Ext.Object.chain(prototype.initConfigMap);
            //</feature>
        },

        /**
         * @private
         * @static
         * @inheritable
         */
        '$onExtended': [],

        /**
         * @private
         * @static
         * @inheritable
         */
        triggerExtended: function() {
            var callbacks = this.$onExtended,
                ln = callbacks.length,
                i, callback;

            if (ln > 0) {
                for (i = 0; i < ln; i++) {
                    callback = callbacks[i];
                    callback.fn.apply(callback.scope || this, arguments);
                }
            }
        },

        /**
         * @private
         * @static
         * @inheritable
         */
        onExtended: function(fn, scope) {
            this.$onExtended.push({
                fn: fn,
                scope: scope
            });

            return this;
        },

        /**
         * @private
         * @static
         * @inheritable
         */
        addConfig: function(config, fullMerge) {
            var prototype = this.prototype,
                initConfigList = prototype.initConfigList,
                initConfigMap = prototype.initConfigMap,
                defaultConfig = prototype.defaultConfig,
                hasInitConfigItem, name, value;

            fullMerge = Boolean(fullMerge);

            for (name in config) {
                if (config.hasOwnProperty(name) && (fullMerge || !(name in defaultConfig))) {
                    value = config[name];
                    hasInitConfigItem = initConfigMap[name];

                    if (value !== null) {
                        if (!hasInitConfigItem) {
                            initConfigMap[name] = true;
                            initConfigList.push(name);
                        }
                    }
                    else if (hasInitConfigItem) {
                        initConfigMap[name] = false;
                        Ext.Array.remove(initConfigList, name);
                    }
                }
            }

            if (fullMerge) {
                Ext.merge(defaultConfig, config);
            }
            else {
                Ext.mergeIf(defaultConfig, config);
            }

            prototype.configClass = Ext.Object.classify(defaultConfig);
        },

        /**
         * Add / override static properties of this class.
         *
         *     Ext.define('My.cool.Class', {
         *         // this.se
         *     });
         *
         *     My.cool.Class.addStatics({
         *         someProperty: 'someValue',      // My.cool.Class.someProperty = 'someValue'
         *         method1: function() {  },    // My.cool.Class.method1 = function() { ... };
         *         method2: function() {  }     // My.cool.Class.method2 = function() { ... };
         *     });
         *
         * @param {Object} members
         * @return {Ext.Base} this
         * @static
         * @inheritable
         */
        addStatics: function(members) {
            var member, name;
            //<debug>
            var className = Ext.getClassName(this);
            //</debug>

            for (name in members) {
                if (members.hasOwnProperty(name)) {
                    member = members[name];
                    //<debug>
                    if (typeof member == 'function') {
                        member.displayName = className + '.' + name;
                    }
                    //</debug>
                    this[name] = member;
                }
            }

            return this;
        },

        /**
         * @private
         * @static
         * @inheritable
         */
        addInheritableStatics: function(members) {
            var inheritableStatics,
                hasInheritableStatics,
                prototype = this.prototype,
                name, member;

            inheritableStatics = prototype.$inheritableStatics;
            hasInheritableStatics = prototype.$hasInheritableStatics;

            if (!inheritableStatics) {
                inheritableStatics = prototype.$inheritableStatics = [];
                hasInheritableStatics = prototype.$hasInheritableStatics = {};
            }

            //<debug>
            var className = Ext.getClassName(this);
            //</debug>

            for (name in members) {
                if (members.hasOwnProperty(name)) {
                    member = members[name];
                    if (typeof member == 'function') {
                        member.$owner = this;
                        member.$name = name;
                        //<debug>
                        member.displayName = className + '.' + name;
                        //</debug>
                    }
                    this[name] = member;

                    if (!hasInheritableStatics[name]) {
                        hasInheritableStatics[name] = true;
                        inheritableStatics.push(name);
                    }
                }
            }

            return this;
        },

        /**
         * Add methods / properties to the prototype of this class.
         *
         *     @example
         *     Ext.define('My.awesome.Cat', {
         *         constructor: function() {
         *             // ...
         *         }
         *     });
         *
         *      My.awesome.Cat.addMembers({
         *          meow: function() {
         *             alert('Meowww...');
         *          }
         *      });
         *
         *      var kitty = new My.awesome.Cat();
         *      kitty.meow();
         *
         * @param {Object} members
         * @static
         * @inheritable
         */
        addMembers: function(members) {
            var prototype = this.prototype,
                names = [],
                name, member;

            //<debug>
            var className = this.$className || '';
            //</debug>

            for (name in members) {
                if (members.hasOwnProperty(name)) {
                    member = members[name];

                    if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
                        member.$owner = this;
                        member.$name = name;
                        //<debug>
                        member.displayName = className + '#' + name;
                        //</debug>
                    }

                    prototype[name] = member;
                }
            }

            return this;
        },

        /**
         * @private
         * @static
         * @inheritable
         */
        addMember: function(name, member) {
            if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) {
                member.$owner = this;
                member.$name = name;
                //<debug>
                member.displayName = (this.$className || '') + '#' + name;
                //</debug>
            }

            this.prototype[name] = member;

            return this;
        },

        /**
         * @private
         * @static
         * @inheritable
         */
        implement: function() {
            this.addMembers.apply(this, arguments);
        },

        /**
         * Borrow another class' members to the prototype of this class.
         *
         *     Ext.define('Bank', {
         *         money: '$$$',
         *         printMoney: function() {
         *             alert('$$$$$$$');
         *         }
         *     });
         *
         *     Ext.define('Thief', {
         *         // ...
         *     });
         *
         *     Thief.borrow(Bank, ['money', 'printMoney']);
         *
         *     var steve = new Thief();
         *
         *     alert(steve.money); // alerts '$$$'
         *     steve.printMoney(); // alerts '$$$$$$$'
         *
         * @param {Ext.Base} fromClass The class to borrow members from
         * @param {Array/String} members The names of the members to borrow
         * @return {Ext.Base} this
         * @static
         * @inheritable
         * @private
         */
        borrow: function(fromClass, members) {
            var prototype = this.prototype,
                fromPrototype = fromClass.prototype,
                //<debug>
                className = Ext.getClassName(this),
                //</debug>
                i, ln, name, fn, toBorrow;

            members = Ext.Array.from(members);

            for (i = 0,ln = members.length; i < ln; i++) {
                name = members[i];

                toBorrow = fromPrototype[name];

                if (typeof toBorrow == 'function') {
                    fn = function() {
                        return toBorrow.apply(this, arguments);
                    };

                    //<debug>
                    if (className) {
                        fn.displayName = className + '#' + name;
                    }
                    //</debug>

                    fn.$owner = this;
                    fn.$name = name;

                    prototype[name] = fn;
                }
                else {
                    prototype[name] = toBorrow;
                }
            }

            return this;
        },

        /**
         * Override members of this class. Overridden methods can be invoked via
         * {@link Ext.Base#callParent}.
         *
         *     Ext.define('My.Cat', {
         *         constructor: function() {
         *             alert("I'm a cat!");
         *         }
         *     });
         *
         *     My.Cat.override({
         *         constructor: function() {
         *             alert("I'm going to be a cat!");
         *
         *             var instance = this.callParent(arguments);
         *
         *             alert("Meeeeoooowwww");
         *
         *             return instance;
         *         }
         *     });
         *
         *     var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
         *                               // alerts "I'm a cat!"
         *                               // alerts "Meeeeoooowwww"
         *
         * As of 2.1, direct use of this method is deprecated. Use {@link Ext#define Ext.define}
         * instead:
         *
         *     Ext.define('My.CatOverride', {
         *         override: 'My.Cat',
         *
         *         constructor: function() {
         *             alert("I'm going to be a cat!");
         *
         *             var instance = this.callParent(arguments);
         *
         *             alert("Meeeeoooowwww");
         *
         *             return instance;
         *         }
         *     });
         *
         * The above accomplishes the same result but can be managed by the {@link Ext.Loader}
         * which can properly order the override and its target class and the build process
         * can determine whether the override is needed based on the required state of the
         * target class (My.Cat).
         *
         * @param {Object} members The properties to add to this class. This should be
         * specified as an object literal containing one or more properties.
         * @return {Ext.Base} this class
         * @static
         * @inheritable
         * @deprecated 2.1.0 Please use {@link Ext#define Ext.define} instead
         */
        override: function(members) {
            var me = this,
                enumerables = Ext.enumerables,
                target = me.prototype,
                cloneFunction = Ext.Function.clone,
                currentConfig = target.config,
                name, index, member, statics, names, previous, newConfig, prop;

            if (arguments.length === 2) {
                name = members;
                members = {};
                members[name] = arguments[1];
                enumerables = null;
            }

            do {
                names = []; // clean slate for prototype (1st pass) and static (2nd pass)
                statics = null; // not needed 1st pass, but needs to be cleared for 2nd pass

                for (name in members) { // hasOwnProperty is checked in the next loop...
                    if (name == 'statics') {
                        statics = members[name];
                    }
                    else if (name == 'config') {
                        newConfig = members[name];
                        //<debug error>
                        for (prop in newConfig) {
                            if (!(prop in currentConfig)) {
                                throw new Error("Attempting to override a non-existant config property. This is not " +
                                    "supported, you must extend the Class.");
                            }
                        }
                        //</debug>
                        me.addConfig(newConfig, true);
                    }
                    else {
                        names.push(name);
                    }
                }

                if (enumerables) {
                    names.push.apply(names, enumerables);
                }

                for (index = names.length; index--; ) {
                    name = names[index];

                    if (members.hasOwnProperty(name)) {
                        var inherited = false;
                        member = members[name];

                        if (typeof member == 'function' && !member.$className && member !== Ext.emptyFn) {
                            if (typeof member.$owner != 'undefined') {
                                member = cloneFunction(member);
                            }

                            //<debug>
                            var className = me.$className;
                            if (className) {
                                member.displayName = className + '#' + name;
                            }
                            //</debug>

                            member.$owner = me;
                            member.$name = name;

                            previous = target[name];
                            if (previous == null) {
                                previous = this[name];
                                if (previous) {
                                    inherited = true;
                                }
                            }
                            if (previous) {
                                member.$previous = previous;
                            }
                        }

                        if (!inherited) {
                            target[name] = member;
                        } else {
                            this[name] = member;
                        }
                    }
                }

                target = me; // 2nd pass is for statics
                members = statics; // statics will be null on 2nd pass
            } while (members);

            return this;
        },

        /**
         * @protected
         * @static
         * @inheritable
         */
        callParent: function(args) {
            var method;

            // This code is intentionally inlined for the least amount of debugger stepping
            return (method = this.callParent.caller) && (method.$previous ||
                  ((method = method.$owner ? method : method.caller) &&
                      method.$owner.superclass.self[method.$name])).apply(this, args || noArgs);
        },

        //<feature classSystem.mixins>
        /**
         * Used internally by the mixins pre-processor
         * @private
         * @static
         * @inheritable
         */
        mixin: function(name, mixinClass) {
            var mixin = mixinClass.prototype,
                prototype = this.prototype,
                key;

            if (typeof mixin.onClassMixedIn != 'undefined') {
                mixin.onClassMixedIn.call(mixinClass, this);
            }

            if (!prototype.hasOwnProperty('mixins')) {
                if ('mixins' in prototype) {
                    prototype.mixins = Ext.Object.chain(prototype.mixins);
                }
                else {
                    prototype.mixins = {};
                }
            }

            for (key in mixin) {
                if (key === 'mixins') {
                    Ext.merge(prototype.mixins, mixin[key]);
                }
                else if (typeof prototype[key] == 'undefined' && key != 'mixinId' && key != 'config') {
                    prototype[key] = mixin[key];
                }
            }

            //<feature classSystem.config>
            if ('config' in mixin) {
                this.addConfig(mixin.config, false);
            }
            //</feature>

            prototype.mixins[name] = mixin;
        },
        //</feature>

        /**
         * Get the current class' name in string format.
         *
         *     Ext.define('My.cool.Class', {
         *         constructor: function() {
         *             alert(this.self.getName()); // alerts 'My.cool.Class'
         *         }
         *     });
         *
         *     My.cool.Class.getName(); // 'My.cool.Class'
         *
         * @return {String} className
         * @static
         * @inheritable
         */
        getName: function() {
            return Ext.getClassName(this);
        },

        /**
         * Create aliases for existing prototype methods. Example:
         *
         *     Ext.define('My.cool.Class', {
         *         method1: function() {  },
         *         method2: function() {  }
         *     });
         *
         *     var test = new My.cool.Class();
         *
         *     My.cool.Class.createAlias({
         *         method3: 'method1',
         *         method4: 'method2'
         *     });
         *
         *     test.method3(); // test.method1()
         *
         *     My.cool.Class.createAlias('method5', 'method3');
         *
         *     test.method5(); // test.method3() -> test.method1()
         *
         * @param {String/Object} alias The new method name, or an object to set multiple aliases. See
         * {@link Ext.Function#flexSetter flexSetter}
         * @param {String/Object} origin The original method name
         * @static
         * @inheritable
         * @method
         */
        createAlias: flexSetter(function(alias, origin) {
            this.override(alias, function() {
                return this[origin].apply(this, arguments);
            });
        }),

        /**
         * @private
         * @static
         * @inheritable
         */
        addXtype: function(xtype) {
            var prototype = this.prototype,
                xtypesMap = prototype.xtypesMap,
                xtypes = prototype.xtypes,
                xtypesChain = prototype.xtypesChain;

            if (!prototype.hasOwnProperty('xtypesMap')) {
                xtypesMap = prototype.xtypesMap = Ext.merge({}, prototype.xtypesMap || {});
                xtypes = prototype.xtypes = prototype.xtypes ? [].concat(prototype.xtypes) : [];
                xtypesChain = prototype.xtypesChain = prototype.xtypesChain ? [].concat(prototype.xtypesChain) : [];
                prototype.xtype = xtype;
            }

            if (!xtypesMap[xtype]) {
                xtypesMap[xtype] = true;
                xtypes.push(xtype);
                xtypesChain.push(xtype);
                Ext.ClassManager.setAlias(this, 'widget.' + xtype);
            }

            return this;
        }
    });

    Base.implement({
        isInstance: true,

        $className: 'Ext.Base',

        configClass: Ext.emptyFn,

        initConfigList: [],

        initConfigMap: {},

        /**
         * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
         * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
         * `this` points to during run-time
         *
         *     Ext.define('My.Cat', {
         *         statics: {
         *             totalCreated: 0,
         *             speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
         *         },
         *
         *         constructor: function() {
         *             var statics = this.statics();
         *
         *             alert(statics.speciesName);     // always equals to 'Cat' no matter what 'this' refers to
         *                                             // equivalent to: My.Cat.speciesName
         *
         *             alert(this.self.speciesName);   // dependent on 'this'
         *
         *             statics.totalCreated++;
         *         },
         *
         *         clone: function() {
         *             var cloned = new this.self();                    // dependent on 'this'
         *
         *             cloned.groupName = this.statics().speciesName;   // equivalent to: My.Cat.speciesName
         *
         *             return cloned;
         *         }
         *     });
         *
         *
         *     Ext.define('My.SnowLeopard', {
         *         extend: 'My.Cat',
         *
         *         statics: {
         *             speciesName: 'Snow Leopard'     // My.SnowLeopard.speciesName = 'Snow Leopard'
         *         },
         *
         *         constructor: function() {
         *             this.callParent();
         *         }
         *     });
         *
         *     var cat = new My.Cat();                 // alerts 'Cat', then alerts 'Cat'
         *
         *     var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
         *
         *     var clone = snowLeopard.clone();
         *     alert(Ext.getClassName(clone));         // alerts 'My.SnowLeopard'
         *     alert(clone.groupName);                 // alerts 'Cat'
         *
         *     alert(My.Cat.totalCreated);             // alerts 3
         *
         * @protected
         * @return {Ext.Class}
         */
        statics: function() {
            var method = this.statics.caller,
                self = this.self;

            if (!method) {
                return self;
            }

            return method.$owner;
        },

        /**
         * Call the "parent" method of the current method. That is the method previously
         * overridden by derivation or by an override (see {@link Ext#define}).
         *
         *      Ext.define('My.Base', {
         *          constructor: function (x) {
         *              this.x = x;
         *          },
         *
         *          statics: {
         *              method: function (x) {
         *                  return x;
         *              }
         *          }
         *      });
         *
         *      Ext.define('My.Derived', {
         *          extend: 'My.Base',
         *
         *          constructor: function () {
         *              this.callParent([21]);
         *          }
         *      });
         *
         *      var obj = new My.Derived();
         *
         *      alert(obj.x);  // alerts 21
         *
         * This can be used with an override as follows:
         *
         *      Ext.define('My.DerivedOverride', {
         *          override: 'My.Derived',
         *
         *          constructor: function (x) {
         *              this.callParent([x*2]); // calls original My.Derived constructor
         *          }
         *      });
         *
         *      var obj = new My.Derived();
         *
         *      alert(obj.x);  // now alerts 42
         *
         * This also works with static methods.
         *
         *      Ext.define('My.Derived2', {
         *          extend: 'My.Base',
         *
         *          statics: {
         *              method: function (x) {
         *                  return this.callParent([x*2]); // calls My.Base.method
         *              }
         *          }
         *      });
         *
         *      alert(My.Base.method(10));     // alerts 10
         *      alert(My.Derived2.method(10)); // alerts 20
         *
         * Lastly, it also works with overridden static methods.
         *
         *      Ext.define('My.Derived2Override', {
         *          override: 'My.Derived2',
         *
         *          statics: {
         *              method: function (x) {
         *                  return this.callParent([x*2]); // calls My.Derived2.method
         *              }
         *          }
         *      });
         *
         *      alert(My.Derived2.method(10)); // now alerts 40
         *
         * To override a method and replace it and also call the superclass method, use
         * {@link #callSuper}. This is often done to patch a method to fix a bug.
         *
         * @protected
         * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
         * from the current method, for example: `this.callParent(arguments)`
         * @return {Object} Returns the result of calling the parent method
         */
        callParent: function(args) {
            // NOTE: this code is deliberately as few expressions (and no function calls)
            // as possible so that a debugger can skip over this noise with the minimum number
            // of steps. Basically, just hit Step Into until you are where you really wanted
            // to be.
            var method,
                superMethod = (method = this.callParent.caller) && (method.$previous ||
                        ((method = method.$owner ? method : method.caller) &&
                                method.$owner.superclass[method.$name]));

            //<debug error>
            if (!superMethod) {
                method = this.callParent.caller;
                var parentClass, methodName;

                if (!method.$owner) {
                    if (!method.caller) {
                        throw new Error("Attempting to call a protected method from the public scope, which is not allowed");
                    }

                    method = method.caller;
                }

                parentClass = method.$owner.superclass;
                methodName = method.$name;

                if (!(methodName in parentClass)) {
                    throw new Error("this.callParent() was called but there's no such method (" + methodName +
                                ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")");
                }
            }
            //</debug>

            return superMethod.apply(this, args || noArgs);
        },

        /**
         * This method is used by an override to call the superclass method but bypass any
         * overridden method. This is often done to "patch" a method that contains a bug
         * but for whatever reason cannot be fixed directly.
         *
         * Consider:
         *
         *      Ext.define('Ext.some.Class', {
         *          method: function () {
         *              console.log('Good');
         *          }
         *      });
         *
         *      Ext.define('Ext.some.DerivedClass', {
         *          method: function () {
         *              console.log('Bad');
         *
         *              // ... logic but with a bug ...
         *
         *              this.callParent();
         *          }
         *      });
         *
         * To patch the bug in `DerivedClass.method`, the typical solution is to create an
         * override:
         *
         *      Ext.define('App.paches.DerivedClass', {
         *          override: 'Ext.some.DerivedClass',
         *
         *          method: function () {
         *              console.log('Fixed');
         *
         *              // ... logic but with bug fixed ...
         *
         *              this.callSuper();
         *          }
         *      });
         *
         * The patch method cannot use `callParent` to call the superclass `method` since
         * that would call the overridden method containing the bug. In other words, the
         * above patch would only produce "Fixed" then "Good" in the console log, whereas,
         * using `callParent` would produce "Fixed" then "Bad" then "Good".
         *
         * @protected
         * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
         * from the current method, for example: `this.callSuper(arguments)`
         * @return {Object} Returns the result of calling the superclass method
         */
        callSuper: function(args) {
            var method,
                superMethod = (method = this.callSuper.caller) && ((method = method.$owner ? method : method.caller) &&
                                method.$owner.superclass[method.$name]);

            //<debug error>
            if (!superMethod) {
                method = this.callSuper.caller;
                var parentClass, methodName;

                if (!method.$owner) {
                    if (!method.caller) {
                        throw new Error("Attempting to call a protected method from the public scope, which is not allowed");
                    }

                    method = method.caller;
                }

                parentClass = method.$owner.superclass;
                methodName = method.$name;

                if (!(methodName in parentClass)) {
                    throw new Error("this.callSuper() was called but there's no such method (" + methodName +
                                ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")");
                }
            }
            //</debug>

            return superMethod.apply(this, args || noArgs);
        },

        /**
         * Call the original method that was previously overridden with {@link Ext.Base#override},
         *
         * This method is deprecated as {@link #callParent} does the same thing.
         *
         *     Ext.define('My.Cat', {
         *         constructor: function() {
         *             alert("I'm a cat!");
         *         }
         *     });
         *
         *     My.Cat.override({
         *         constructor: function() {
         *             alert("I'm going to be a cat!");
         *
         *             var instance = this.callOverridden();
         *
         *             alert("Meeeeoooowwww");
         *
         *             return instance;
         *         }
         *     });
         *
         *     var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
         *                               // alerts "I'm a cat!"
         *                               // alerts "Meeeeoooowwww"
         *
         * @param {Array/Arguments} args The arguments, either an array or the `arguments` object
         * from the current method, for example: `this.callOverridden(arguments)`
         * @return {Object} Returns the result of calling the overridden method
         * @protected
         */
        callOverridden: function(args) {
            var callOverriddenFn = this.callOverridden || this.prototype.callOverridden,
                method = callOverriddenFn.caller,
                previousMethod = method && method.$previous;

            if (!previousMethod) {
                return method.$return;
            }
            return previousMethod.apply(this, args || noArgs);
        },

        /**
         * @property {Ext.Class} self
         *
         * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
         * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
         * for a detailed comparison
         *
         *     Ext.define('My.Cat', {
         *         statics: {
         *             speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
         *         },
         *
         *         constructor: function() {
         *             alert(this.self.speciesName); // dependent on 'this'
         *         },
         *
         *         clone: function() {
         *             return new this.self();
         *         }
         *     });
         *
         *
         *     Ext.define('My.SnowLeopard', {
         *         extend: 'My.Cat',
         *         statics: {
         *             speciesName: 'Snow Leopard'         // My.SnowLeopard.speciesName = 'Snow Leopard'
         *         }
         *     });
         *
         *     var cat = new My.Cat();                     // alerts 'Cat'
         *     var snowLeopard = new My.SnowLeopard();     // alerts 'Snow Leopard'
         *
         *     var clone = snowLeopard.clone();
         *     alert(Ext.getClassName(clone));             // alerts 'My.SnowLeopard'
         *
         * @protected
         */
        self: Base,

        // Default constructor, simply returns `this`
        constructor: function() {
            return this;
        },

        //<feature classSystem.config>

        wasInstantiated: false,

        /**
         * Initialize configuration for this class. a typical example:
         *
         *     Ext.define('My.awesome.Class', {
         *         // The default config
         *         config: {
         *             name: 'Awesome',
         *             isAwesome: true
         *         },
         *
         *         constructor: function(config) {
         *             this.initConfig(config);
         *         }
         *     });
         *
         *     var awesome = new My.awesome.Class({
         *         name: 'Super Awesome'
         *     });
         *
         *     alert(awesome.getName()); // 'Super Awesome'
         *
         * @protected
         * @param {Object} instanceConfig
         * @return {Object} mixins The mixin prototypes as key - value pairs
         */
        initConfig: function(instanceConfig) {
            //<debug>
//            if (instanceConfig && instanceConfig.breakOnInitConfig) {
//                debugger;
//            }
            //</debug>
            var configNameCache = Ext.Class.configNameCache,
                prototype = this.self.prototype,
                initConfigList = this.initConfigList,
                initConfigMap = this.initConfigMap,
                config = new this.configClass,
                defaultConfig = this.defaultConfig,
                i, ln, name, value, nameMap, getName;

            this.initConfig = Ext.emptyFn;

            this.initialConfig = instanceConfig || {};

            if (instanceConfig) {
                Ext.merge(config, instanceConfig);
            }

            this.config = config;

            // Optimize initConfigList *once* per class based on the existence of apply* and update* methods
            // Happens only once during the first instantiation
            if (!prototype.hasOwnProperty('wasInstantiated')) {
                prototype.wasInstantiated = true;

                for (i = 0,ln = initConfigList.length; i < ln; i++) {
                    name = initConfigList[i];
                    nameMap = configNameCache[name];
                    value = defaultConfig[name];

                    if (!(nameMap.apply in prototype)
                        && !(nameMap.update in prototype)
                        && prototype[nameMap.set].$isDefault
                        && typeof value != 'object') {
                        prototype[nameMap.internal] = defaultConfig[name];
                        initConfigMap[name] = false;
                        Ext.Array.remove(initConfigList, name);
                        i--;
                        ln--;
                    }
                }
            }

            if (instanceConfig) {
                initConfigList = initConfigList.slice();

                for (name in instanceConfig) {
                    if (name in defaultConfig && !initConfigMap[name]) {
                        initConfigList.push(name);
                    }
                }
            }

            // Point all getters to the initGetters
            for (i = 0,ln = initConfigList.length; i < ln; i++) {
                name = initConfigList[i];
                nameMap = configNameCache[name];
                this[nameMap.get] = this[nameMap.initGet];
            }

            this.beforeInitConfig(config);

            for (i = 0,ln = initConfigList.length; i < ln; i++) {
                name = initConfigList[i];
                nameMap = configNameCache[name];
                getName = nameMap.get;

                if (this.hasOwnProperty(getName)) {
                    this[nameMap.set].call(this, config[name]);
                    delete this[getName];
                }
            }

            return this;
        },

        beforeInitConfig: Ext.emptyFn,

        /**
         * @private
         */
        getCurrentConfig: function() {
            var defaultConfig = this.defaultConfig,
                configNameCache = Ext.Class.configNameCache,
                config = {},
                name, nameMap;

            for (name in defaultConfig) {
                nameMap = configNameCache[name];
                config[name] = this[nameMap.get].call(this);
            }

            return config;
        },

        /**
         * @private
         */
        setConfig: function(config, applyIfNotSet) {
            if (!config) {
                return this;
            }

            var configNameCache = Ext.Class.configNameCache,
                currentConfig = this.config,
                defaultConfig = this.defaultConfig,
                initialConfig = this.initialConfig,
                configList = [],
                name, i, ln, nameMap;

            applyIfNotSet = Boolean(applyIfNotSet);

            for (name in config) {
                if ((applyIfNotSet && (name in initialConfig))) {
                    continue;
                }

                currentConfig[name] = config[name];

                if (name in defaultConfig) {
                    configList.push(name);
                    nameMap = configNameCache[name];
                    this[nameMap.get] = this[nameMap.initGet];
                }
            }

            for (i = 0,ln = configList.length; i < ln; i++) {
                name = configList[i];
                nameMap = configNameCache[name];
                this[nameMap.set].call(this, config[name]);
                delete this[nameMap.get];
            }

            return this;
        },

        set: function(name, value) {
            return this[Ext.Class.configNameCache[name].set].call(this, value);
        },

        get: function(name) {
            return this[Ext.Class.configNameCache[name].get].call(this);
        },

        /**
         * @private
         */
        getConfig: function(name) {
            return this[Ext.Class.configNameCache[name].get].call(this);
        },

        /**
         * @private
         */
        hasConfig: function(name) {
            return (name in this.defaultConfig);
        },

        /**
         * Returns the initial configuration passed to constructor.
         *
         * @param {String} [name] When supplied, value for particular configuration
         * option is returned, otherwise the full config object is returned.
         * @return {Object/Mixed}
         */
        getInitialConfig: function(name) {
            var config = this.config;

            if (!name) {
                return config;
            }
            else {
                return config[name];
            }
        },

        /**
         * @private
         */
        onConfigUpdate: function(names, callback, scope) {
            var self = this.self,
                //<debug>
                className = self.$className,
                //</debug>
                i, ln, name,
                updaterName, updater, newUpdater;

            names = Ext.Array.from(names);

            scope = scope || this;

            for (i = 0,ln = names.length; i < ln; i++) {
                name = names[i];
                updaterName = 'update' + Ext.String.capitalize(name);
                updater = this[updaterName] || Ext.emptyFn;
                newUpdater = function() {
                    updater.apply(this, arguments);
                    scope[callback].apply(scope, arguments);
                };
                newUpdater.$name = updaterName;
                newUpdater.$owner = self;
                //<debug>
                newUpdater.displayName = className + '#' + updaterName;
                //</debug>

                this[updaterName] = newUpdater;
            }
        },
        //</feature>

        /**
         * @private
         * @param {String} name
         * @param {Mixed} value
         * @return {Mixed}
         */
        link: function(name, value) {
            this.$links = {};
            this.link = this.doLink;
            return this.link.apply(this, arguments);
        },

        doLink: function(name, value) {
            this.$links[name] = true;

            this[name] = value;

            return value;
        },

        /**
         * @private
         */
        unlink: function() {
            var i, ln, link, value;

            for (i = 0, ln = arguments.length; i < ln; i++) {
                link = arguments[i];
                if (this.hasOwnProperty(link)) {
                    value = this[link];
                    if (value) {
                        if (value.isInstance && !value.isDestroyed) {
                            value.destroy();
                        }
                        else if (value.parentNode && 'nodeType' in value) {
                            value.parentNode.removeChild(value);
                        }
                    }
                    delete this[link];
                }
            }

            return this;
        },

        /**
         * @protected
         */
        destroy: function() {
            this.destroy = Ext.emptyFn;
            this.isDestroyed = true;

            if (this.hasOwnProperty('$links')) {
                this.unlink.apply(this, Ext.Object.getKeys(this.$links));
                delete this.$links;
            }
        }
    });

    Ext.Base = Base;

})(Ext.Function.flexSetter);


#!/usr/bin/env node

const fs = require("fs");
const program = require("commander");
const path = require("path");
const chalk = require("chalk");
const tempy = require("tempy");
const download = require("./download");
const rollup = require("rollup");
const minify = require("babel-minify");

program
  .version(require("./package.json").version, "-v, --version")
  .usage("[options] <source>")
  .option("-d, --destination <directory>", "directory to download to")
  .option("-b, --bundle <file>", "bundle and minify into one file")
  .action(async (source, options) => {
    try {
      if (source == null || options == null) {
        program.outputHelp();
        return;
      }

      const localDirectory = options.bundle
        ? tempy.directory()
        : path.resolve(
            process.cwd(),
            typeof options.destination === "string" ? options.destination : ""
          );
      await download(
        localDirectory,
        source,
        options.bundle && localDirectory /* tmpDirectory */
      );

      if (options.bundle) {
        const filename = path.basename(source);
        const inputOptions = {
          input: path.join(localDirectory, filename)
        };
        const outputOptions = {
          format: "esm"
        };
        const _bundle = await rollup.rollup(inputOptions);
        const rollupResult = await _bundle.generate(outputOptions);
        let lastLicense = null;
        const { code } = minify(
          rollupResult.code,
          {},
          {
            sourceType: "module",
            // don't include redundant license or copyright notice
            comments: function(comment) {
              const isLicense =
                comment.toLowerCase().includes("license") ||
                comment.toLowerCase().includes("copyright");
              if (isLicense === false) {
                return false;
              }
              if (lastLicense !== comment) {
                lastLicense = comment;
                return true;
              } else {
                return false;
              }
            }
          }
        );
        fs.writeFileSync(path.resolve(process.cwd(), options.bundle), code);
        console.log("→ " + chalk.green(options.bundle));
      }
    } catch (error) {
      console.log(error);
    }
  })
  .parse(process.argv);


/**
 * Settings -> merge(os, env, globals, .folders, .files, config)
 */
'use strict'

const _ = require('lodash')
const path = require('path')

// all setting defaults
let _SETTINGS = {
  "env": require('./env'),
  "account": require('./account'),
  "json": require('./json'),
  "js": require('./js'),
  "proc": require('./proc'),
  "os": require('./os'),
  "paths": require('./paths'),
  "require": require('./require'),
  "launch": require('./launch'),
  "modules": require('./modules'),
  "sites": require('./sites'),
  "apps": require('./apps'),
  "trons": require('./trons'),
  "docs": require('./docs')
}

exports = module.exports = ctor

// load cwd .ninjs settings
load(path.join(process.cwd(), '.ninjs', 'settings.js'))
load(path.join(process.cwd(), '.ninjs', 'settings.json'))

// assign exports and global lodash (_) object
_.assign(exports, _SETTINGS)
_.assign(_, { "$": ctor, "$load": load })

//getter/setter
function ctor(k, v) {
  if(k && _.isString(k) && k.indexOf('paths.') === 0) return get.apply(null, _.toArray(arguments))
  return v ? set(k, v) : get(k)
}

//get setting key
function get(k) {
  if(!k) return _SETTINGS
  let v = _.get(_SETTINGS, k)
  if(!v) return
  if(_.isString(k) && k.indexOf('paths.') !== 0) return v
  let args = _.drop(_.toArray(arguments))
  let argsLength = args.unshift(v)
  return path.join.apply(path, args)
}

//set setting key with val (merged if already exists and is plain object {})
function set(k, v) {
  let curr = get(k)
  if(curr && _.isPlainObject(curr) && _.isPlainObject(v)) v = _.mcopy(curr, v)
  if(k) _.set(_SETTINGS, k, v)
  if(!k) _SETTINGS = v
  return get(k)
}

// require src and merge with SETTINGS if exists
function load(src) {
  if(!src || !_.isString(src)) return
  let file = _.attempt(require, src)
  if(!file || _.isError(file) || !_.isPlainObject(file)) return
  return _.merge(_SETTINGS, file)
}


/*
  Copyright Jesús Pérez <jesusprubio@gmail.com>

  This code may only be used under the MIT license found at
  https://opensource.org/licenses/MIT.
*/

'use strict';

// Private stuff
var net = require('net'),
    randomPort = require('random-port'),

    utils = require('./utils'),
    SteroidsSocket = require('./steroidsSocket'),
    sipParser = require('./parser');

// Constructor

function SipFakeStack(config) {

    if (!config.server) {
        throw '(SipFakeStack) You need at least to specify a valid IPv4/6 target';
    }

    this.server = config.server || null;
    this.port = config.port || 5060;
    this.transport = config.transport || 'UDP';
//    this.lport = config.lport || utils.randomPort();
    this.lport = config.lport || null;
    this.srcHost = config.srcHost;
    this.timeout = config.timeout || 8000;
    this.wsPath = config.wsPath || null;
    this.domain = config.domain || null;
    this.onlyFirst = config.onlyFirst || true;

    if (net.isIPv6(config.server) && !config.srcHost) {
        this.srcHost = utils.randomIP6();
    } else if (!config.srcHost) {
        this.srcHost = utils.randomIP();
    }
}

// Public functions

SipFakeStack.prototype.send = function (cfg, callback) {
    var self = this;

    function sendLport() {
        var socketCfg = {
                target: self.server,
                port: self.port,
                transport: self.transport.toUpperCase(),
                lport: self.lport,
                timeout: self.timeout,
                wsProto: 'sip',
                wsPath: self.wsPath
            },
            msgOptions = cfg,
            allRes = [],
            returned = false;

        // Reusing options object
        msgOptions.lport = self.lport;
        msgOptions.server = self.server;
        msgOptions.srcHost = self.srcHost;
        msgOptions.domain = self.domain;
        msgOptions.transport = self.transport.toUpperCase();

        self.metaSocket = new SteroidsSocket(socketCfg);

        self.metaSocket.on('error', function (err) {
            callback({
                message: 'Generic socket error',
                error: err
            });
        });

        self.metaSocket.on('message', function (msg) {

            if (!self.onlyFirst) {
                self.metaSocket.close();
                callback(null, {
                    msg : msg
                });

                return;
            }
            if (!returned) {
                returned = true;
                // We wait for a while for more responses
                setTimeout(function () {
                    self.metaSocket.close();
                    callback(null, {
                        message : 'Received responses:',
                        data: allRes
                    });
                }, Math.round(self.timeout / 3));
            }

            // SIP can be a binary or text protocol, but text widely used
            allRes.push(msg.data.toString());
        });

        self.metaSocket.send(utils.createMessage(msgOptions));
    }

    // Trick needed to avoid problem with bussy ports in UDP (EADDINUSE)
    if (!this.lport) {
        randomPort(function (port) {
            self.lport = port;
            sendLport();
        });
    } else {
        sendLport();
    }
};

SipFakeStack.prototype.authenticate = function (config, callback) {
    var self = this;

    function authenticateLport() {
        var msgOptions = config,
            firstTime = true,
            valid = false,
            // We need to know this values in advance to continue the transaction
            cseq = 1,
            callId = utils.randomString(16),
            toExt = utils.randomString(3),
            // in case of webscokets
            gruuInstance = 'urn:uuid:' + utils.randomString(3) + '-' +
                            utils.randomString(4) + '-' + utils.randomString(8),
            socketCfg = {
                target: self.server,
                port: self.port,
                transport: self.transport.toUpperCase(),
                lport: self.lport,
                timeout: self.timeout,
                wsProto: 'sip',
                wsPath: self.wsPath
            };

        // Reusing options object
        msgOptions.lport = self.lport;
        msgOptions.server = self.server;
        msgOptions.srcHost = self.srcHost;
        msgOptions.domain = self.domain;
        msgOptions.cseq = cseq;
        msgOptions.callId = callId;
        msgOptions.toExt = toExt;
        msgOptions.gruuInstance = gruuInstance;
        msgOptions.transport = self.transport.toUpperCase();

        self.metaSocket = new SteroidsSocket(socketCfg);

        self.metaSocket.on('error', function (err) {
            console.log('ERR');
            console.log(err);
            callback({
                message: 'Generic socket error, second time: ' + !firstTime,
                error: err
            });
        });

        self.metaSocket.on('message', function (msg) {
            var lastMessage = 'Not accepted',
                response, resCode, parsedAuth;

            // TODO: We need to be more polite at the end of this function
            // (send ACKs, etc.) to avoid retryings
            self.metaSocket.close();

            if (!(msg && msg.data)) {
                callback({
                    message: 'Empty message, firstTime: ' + firstTime,
                    error: null
                });

                return;
            }
            // SIP can be a binary or text protocol, but text widely used
            response = msg.data.toString();
            resCode = sipParser.code(response);

            if (firstTime) {
                firstTime = false;
                if (['401', '407', '200'].indexOf(resCode) === -1) {
                    callback(null, {
                        message: 'Not expected SIP code (1st res.)',
                        data: {
                            valid: false,
                            response: response
                        }
                    });

                    self.metaSocket.close(); // just in case

                    return;
                } else if (resCode === '200') {
                    callback(null, {
                        message: 'User without authentication',
                        data: {
                            valid: true,
                            response: response
                        }
                    });
                    self.metaSocket.close();

                    return;
                }
                // Upgrading SIP fields
                parsedAuth = sipParser.realmNonce(response);
                if (!parsedAuth) {
                    callback(null, {
                        message: 'Not expected SIP code (2nd res.)',
                        data: {
                            valid: false,
                            response: response
                        }
                    });

                    return;
                }
                msgOptions.isProxy = parsedAuth.isProxy;
                msgOptions.realm = parsedAuth.realm;
                msgOptions.nonce = parsedAuth.nonce;
                msgOptions.pass = config.pass;
                msgOptions.cseq = cseq + 1;

                self.metaSocket.send(utils.createMessage(msgOptions));
            } else { // second time
                if (['REGISTER', 'PUBLISH'].indexOf(config.meth) !== -1) {
                    if (resCode === '200') {
                        valid = true;
                        lastMessage = 'Accepted';
                    }
                } else if (['401', '407'].indexOf(resCode) === -1) {
                    valid = true;
                    lastMessage = 'Accepted';
                }
                callback(null, {
                    message: lastMessage,
                    data: {
                        valid: valid,
                        response: response
                    }
                });
            }
        });

        self.metaSocket.send(utils.createMessage(msgOptions));
    }

    // TODO: Error: address in use if a huge actives.
    // if (!this.lport) {
    //     randomPort(function (port) {
    //         self.lport = port;
    //         authenticateLport();
    //     });
    // } else {
    authenticateLport();
    // }

};

module.exports = SipFakeStack;
// We expose also the rest of the stuff just in case
module.exports.parser = sipParser;
module.exports.utils = utils;
module.exports.SteroidsSocket = SteroidsSocket;