<commit_before>// var csjs = require('csjs-inject')

module.exports = styleGuide

function styleGuide () {
  /* --------------------------------------------------------------------------
  COLORS
  -------------------------------------------------------------------------- */
  var colors = {
    // BACKGROUND COLORS
    general_BackgroundColor: 'hsl(0, 0%, 100%)',  // white
    highlight_BackgroundColor: 'hsla(229, 100%, 97%, 1)', // backgroundBlue

    // TEXT COLORS
    mainText_Color: 'hsl(0, 0%, 0%)', // black
    normalText_Color: 'hsla(0, 0%, 40%, 1)', // grey

    // ICONS
    icon_Color: 'hsl(0, 0%, 0%)', // black
    icon_HoverColor: 'hsla(44, 100%, 50%, 1)', // orange

    // UI ELEMENTS
    element_TextColor: 'hsl(0, 0%, 0%)', // black ,
    element_BackgroundColor: 'hsl(0, 0%, 100%)', // white
    element_BorderColor: 'hsla(0, 0%, 40%, .2)', // very light grey

/*
1. most css properties can take many or infinite amounf of different values
=> so we define a set of concrete values that we use:
- variable just for plain colors (later also fonts, widths, paddings, border radiuses...)

2. we define certain semantic names that make sense in the context of our app
=> so we can use the values used in (1.) e.g. like 'color_red'  and assign it to e.g.
- highlightColor: color_red
- borderColor: color_white
- ...

3. we define a nested object that represents the component hierarchy that
makes up our app and use semantic names defined under (2.)

*/

    // BASIC COLORS (B&W and transparent)
    transparent: 'transparent',
    white: 'hsl(0, 0%, 100%)',
    black: 'hsl(0, 0%, 0%)',
    opacityBlack: 'hsla(0, 0%, 0%, .4)',
    // BLUE
    blue: 'hsla(229, 75%, 87%, 1)',
    lightBlue: 'hsla(229, 75%, 87%, .5)',
    backgroundBlue: 'hsla(229, 100%, 97%, 1)',
    // GREY
    grey: 'hsla(0, 0%, 40%, 1)',
    lightGrey: 'hsla(0, 0%, 40%, .5)',
    veryLightGrey: 'hsla(0, 0%, 40%, .2)',
    // RED
    red: 'hsla(0, 82%, 82%, 1)',
    lightRed: 'hsla(0, 82%, 82%, .5)',
    // GREEN
    green: 'hsla(141, 75%, 84%, 1)',
    lightGreen: 'hsla(141, 75%, 84%, .5)',
    // PINK
    pink: 'hsla(300, 69%, 76%, 1)',
    lightPink: 'hsla(300, 69%, 76%, .5)',
    // YELLOW
    orange: 'hsla(44, 100%, 50%, 1)',
    lightOrange: 'hsla(44, 100%, 50%, .5)',
    // VIOLET
    violet: 'hsla(240, 64%, 68%, 1)'
  }

var elementColors = {
  /* -----------------------
          BUTTONS
  ----------------------- */
  // DROPDOWN
  dropdown_TextColor: colors.element_TextColor,
  dropdown_BackgroundColor: colors.element_BackgroundColor,
  dropdown_BorderColor: colors.element_BorderColor,

  // BUTTON
  button_TextColor: colors.element_TextColor,
  button_BorderColor: colors.element_BorderColor,
  rightPanel_compileTab_compileButton_BackgroundColor: 'hsla(0, 0%, 40%, .2)',
  rightPanel_compileTab_otherButtons_BackgroundColor: 'hsla(0, 0%, 40%, .2)'

  /* -----------------------
          TEXT BOXES
  ----------------------- */
}
  /* --------------------------------------------------------------------------
                                TEXT-BOXES
  -------------------------------------------------------------------------- */
  var textBoxes = {

    'display-box': `
      font-size             : 12px;
      padding               : 10px 15px;
      line-height           : 20px;
      background            : ${colors.white};
      border-radius         : 3px;
      border                : 1px solid ${colors.veryLightGrey};
      overflow              : hidden;
      word-break            : break-word;
      width                 : 100%;
    `,

    'info-text-box': `
      background-color      : ${colors.white};
      line-height           : 20px;
      border                : .2em dotted ${colors.lightGrey};
      padding               : 8px 15px;
      border-radius         : 5px;
      margin-bottom         : 1em;
      overflow              : hidden;
      word-break            : break-word;
    `,

    'input': `
      border                : 1px solid ${colors.veryLightGrey};
      height                : 25px;
      width                 : 250px;
      border-radius         : 3px;
      padding               : 0 8px;
      overflow              : hidden;
      word-break            : normal;
    `
  }
  /* --------------------------------------------------------------------------
                                    BUTTONS
  -------------------------------------------------------------------------- */
  var buttons = {

    'button': `
      background-color        : ${elementColors.button_BackgroundColor};
      border                  : .3px solid ${elementColors.button_BorderColor};
      color                   : ${elementColors.button_TextColor};
      display                 : flex;
      align-items             : center;
      justify-content         : center;
      border-radius           : 3px;
      cursor                  : pointer;
      min-height              : 25px;
      max-height              : 25px;
      width                   : 70px;
      min-width               : 70px;
      font-size               : 12px;
      overflow                : hidden;
      word-break              : normal;
    `,

    'button:hover': `
      opacity                 : 0.8;
    `,

    'dropdown': `
      color                   : ${elementColors.dropdown_TextColor};
      background-color        : ${elementColors.dropdown_BackgroundColor};
      border                  : 1px solid ${elementColors.dropdown_BorderColor};
      font-size               : 12px;
      font-weight             : bold;
      padding                 : 0 8px;
      text-decoration         : none;
      cursor                  : pointer;
      border-radius           : 3px;
      height                  : 25px;
      width                   : 250px;
      text-align              : center;
      overflow                : hidden;
      word-break              : normal;
    `

  }

  return {
    colors: colors,
    elementColors: elementColors,
    dropdown: buttons['dropdown'],
    button: buttons['button'],
    inputField: textBoxes['input'],
    infoTextBox: textBoxes['info-text-box'],
    displayBox: textBoxes['display-box']
  }
}
<commit_msg>Update style guide<commit_after>// var csjs = require('csjs-inject')

module.exports = styleGuide

function styleGuide () {

  /* --------------------------------------------------------------------------

                              CSS PROPERTIES

  -------------------------------------------------------------------------- */
  var css_properties = {

    /****************************
                COLORS
    ************************** */
    colors: {
      // BASIC COLORS (B&W and transparent)
      transparent: 'transparent',
      white: 'hsl(0, 0%, 100%)',
      black: 'hsl(0, 0%, 0%)',
      opacityBlack: 'hsla(0, 0%, 0%, .4)',
      // BLUE
      blue: 'hsla(229, 75%, 87%, 1)',
      lightBlue: 'hsla(229, 75%, 87%, .5)',
      backgroundBlue: 'hsla(229, 100%, 97%, 1)',
      // GREY
      grey: 'hsla(0, 0%, 40%, 1)',
      lightGrey: 'hsla(0, 0%, 40%, .5)',
      veryLightGrey: 'hsla(0, 0%, 40%, .2)',
      // RED
      red: 'hsla(0, 82%, 82%, 1)',
      lightRed: 'hsla(0, 82%, 82%, .5)',
      // GREEN
      green: 'hsla(141, 75%, 84%, 1)',
      lightGreen: 'hsla(141, 75%, 84%, .5)',
      // PINK
      pink: 'hsla(300, 69%, 76%, 1)',
      lightPink: 'hsla(300, 69%, 76%, .5)',
      // YELLOW
      orange: 'hsla(44, 100%, 50%, 1)',
      lightOrange: 'hsla(44, 100%, 50%, .5)',
      // VIOLET
      violet: 'hsla(240, 64%, 68%, 1)'
    },

    /****************************
                FONT
    ************************** */
    fonts: {
    },

    /****************************
                BORDERS
    ************************** */
    borders: {}
  }

  /* --------------------------------------------------------------------------

                                APP PROPERTIES

  -------------------------------------------------------------------------- */

  var app_properties = {

    // BACKGROUND COLORS
    general_BackgroundColor: css_properties.colors.white,
    support_BackgroundColor: css_properties.colors.backgroundBlue,

    // TEXT COLORS
    mainText_Color: css_properties.colors.black,
    supportText_Color: css_properties.colors.grey,

    // ICONS
    icon_Color: css_properties.colors.black,
    icon_HoverColor: css_properties.colors.orange,

    // UI ELEMENTS
    element_TextColor: css_properties.colors.black,
    element_BackgroundColor: css_properties.colors.white,
    element_BorderColor: css_properties.colors.veryLightGrey

  }

/* --------------------------------------------------------------------------

                              REMIX PROPERTIES

-------------------------------------------------------------------------- */

var remix_properties = {

  /****************************
          REMIX GENERAL
  ************************** */
  remix: {
    fonts: {
      'font': '',
      'font-size': '',
      mainText: {
        'color': ''
      },
      supportText: {
        'color': ''
      }
    },
    dropdown: {
      'background-color': '',
      'color': ''
    },
    textBox: {
      'background-color': '',
      'border': '',
      'color': ''
    },
    infoTextBox: {
      'background-color': '',
      'border': '',
      'color': ''
    },
    inputField: {
      'background-color': '',
      'color': ''
    },
    butons: {
      'background-color': ''
    },
    copyToClipboard: {
      color: app_properties.icon_Color,
      hover: {
        color: app_properties.icon_Color
      }
    }
  },

  /****************************
    LEFT PANEL (FILE PANEL)
  ************************** */
  leftPanel: {
    icons: {
      color: app_properties.icon_Color,
      hover: {
        color: app_properties.icon_Color
      }
    },
    togglePannel: {
      color: app_properties.icon_Color,
      hover: {
        color: app_properties.icon_Color
      }
    },
    treeview: {
      color: app_properties.mainText_Color,
      highlightedLine: {
        background: app_properties.support_BackgroundColor
      }
    }
  },

  /****************************
              EDITOR
  ************************** */
  editor: {
    'background-color': '',  // general_BackgroundColor
    'color': '',  // fonts/color
    gutter: {
      background: app_properties.support_BackgroundColor,
      highlightedNumber: {
        background: app_properties.support_BackgroundColor  // support_BackgroundColor
      },
    },
    navTabs: {
      background: app_properties.support_BackgroundColor,
      'color': ''  // fonts/color
    },
    icons: {
      color: app_properties.icon_Color,
      hover: {
        color: app_properties.icon_Color
      }
    },
    code: {
      // types, comments, parameters...
      highlightedLine: {
        background: app_properties.support_BackgroundColor   //support_BackgroundColor
      },
      debuggerMode: {
        highlightedArea: {
          background: app_properties.support_BackgroundColor   // same as Debug button in Terminal window
        }
      }
    }
  },

  /****************************
            TERMINAL
  ************************** */
  terminal: {
    menu: {
      background: app_properties.support_BackgroundColor,
      'color': '',  // fonts/color
      icons: {
        color: app_properties.icon_Color,
        hover: {
          color: app_properties.icon_Color
        }
      },
      dropdown: {  // dropdown
        'background-color': '',
        'color': ''
      },
      togglePannel: {
        color: app_properties.icon_Color,
        hover: {
          color: app_properties.icon_Color
        }
      },
    },
    terminalWindow: {
      'background-color': '',
      'color': '',
      logo: {
        'url': '',
      },
      infoLog: {
        'color': ''  // fonts/color
      },
      errorLog: {
        'color': ''  // same as border in errorMessage in rightPanel/compileTab  @TODO
      },
      transactionLog: {
        title: {
          'color': ''
        },
        text: {
          'color': ''
        },
        detailsButton: {
          'background-color': '',
          'color': ''
        },
        debugButton: {
          background: app_properties.support_BackgroundColor,
          'color': ''
        }
      }
    }
  },

  /****************************
          RIGHT PANEL
  ************************** */
  rightPanel: {
    'background-color': '',  // already defined in Remix general
    'color': '', // already defined in Remix general
    textBox: {        // already defined in Remix general
      'background-color': '',
      'border': '',
      'color': ''
    },
    infoTextBox: {     // already defined in Remix general
      'background-color': '',
      'border': '',
      'color': ''
    },
    togglePannel: {
      color: app_properties.icon_Color,
      hover: {
        color: app_properties.icon_Color
      }
    },
    logo: {
      'url': ''
    },
    warningMessage: {
      'border': '',
      'background-color': '',
      'color': ''
    },
    errorMessage: {
      'border': '',   // same as font color in terminal error  @TODO
      'background-color': '',
      'color': ''
    },
    successMessage: {
      'border': '',
      'background-color': '',
      'color': ''
    },
    dropdown: {
      'background-color': '',  // dropdown
      'color': ''
    },
    inputField: {   // inputField
      'background-color': '',
      'color': ''
    },

    compileTab: {
      compileButton: {
        'background-color': '', // or import a special image 'url': ''
        'color': ''
      },
      buttons: {
        'background-color': '',  // general buttons background color
        'color': ''
      },
      details: {
        'background-color': '',  // already defined in Remix general
        header: {
          background: app_properties.support_BackgroundColor,
          'color': ''
        },
        infoTextBox: {     // already in rightPanel general theme
          'background-color': '',
          'border': '',
          'color': '',
          copyToClipboard: {
            color: app_properties.icon_Color,
            hover: {
              color: app_properties.icon_Color
            }
          },
          icons: {
            color: app_properties.icon_Color,
            hover: {
              color: app_properties.icon_Color
            }
          },
          title: {
            'color': ''
          }
        }
      }
    },

    runTab: {
      compileButton: {
        'background-color': '', // or import new 'url': ''
        'color': ''
      },
      atAddressButton: {
        'background-color': '',
        'color': ''
      },
      createButton: {
        'background-color': '',
        'color': ''
      },
      instance_callButton: {
        'background-color': '',
        'color': ''
      },
      instance_transactButton: {
        'background-color': '',
        'color': ''
      },
      instance_transactPayableButton: {
        'background-color': '',
        'color': ''
      },
      copyToClipboard: {
        color: app_properties.icon_Color,
        hover: {
          color: app_properties.icon_Color
        }
      }
    },

    settingsTab: {
      infoTextBox: {     // already in rightPanel general theme
        'background-color': '',
        'border': '',
        'color': ''
      }
    },

    debuggerTab: {
      buttons: {
        'background-color': '',  // including eye button (needs to get ${styles.button} applied)
        'color': '',
        icons: {
          color: app_properties.icon_Color,
          hover: {
            color: app_properties.icon_Color
          }
        }
      },
      dropdowns: {  // dropdown
        'background-color': '',  // see if ${styles.dropdown} is applied
        'color': '',
        instructions: {
          highlightedKey: {
            background: app_properties.support_BackgroundColor
          }
        },
        solidityState: {
          label: {
            'color': ''  // supportText
          }
        }
      }
    },

    analysisTab: {
      textBox: {   // already in rightPanel general theme
        'background-color': '',
        'color': ''
      },
      warningMessage: {  // already in rightPanel general theme
        'border': '',
        'background-color': '',
        'color': ''
      }
    },

    supportTab: {
      textBox: {   // already in rightPanel general theme
        'background-color': '',
        'color': ''
      },
      infoTextBox: {     // already in rightPanel general theme
        'background-color': '',
        'border': '',
        'color': ''
      }
    }
  }

}

var elementColors = {
  /* -----------------------
          BUTTONS
  ----------------------- */
  // DROPDOWN
  dropdown_TextColor: app_properties.element_TextColor,
  dropdown_BackgroundColor: app_properties.element_BackgroundColor,
  dropdown_BorderColor: app_properties.element_BorderColor,

  // BUTTON
  button_TextColor: app_properties.element_TextColor,
  button_BorderColor: app_properties.element_BorderColor,
  rightPanel_compileTab_compileButton_BackgroundColor: 'hsla(0, 0%, 40%, .2)',
  rightPanel_compileTab_otherButtons_BackgroundColor: 'hsla(0, 0%, 40%, .2)'

  /* -----------------------
          TEXT BOXES
  ----------------------- */
}
  /* --------------------------------------------------------------------------
                                TEXT-BOXES
  -------------------------------------------------------------------------- */
  var textBoxes = {

    'display-box': `
      font-size             : 12px;
      padding               : 10px 15px;
      line-height           : 20px;
      background            : ${css_properties.colors.white};
      border-radius         : 3px;
      border                : 1px solid ${css_properties.colors.veryLightGrey};
      overflow              : hidden;
      word-break            : break-word;
      width                 : 100%;
    `,

    'info-text-box': `
      background-color      : ${css_properties.colors.white};
      line-height           : 20px;
      border                : .2em dotted ${css_properties.colors.lightGrey};
      padding               : 8px 15px;
      border-radius         : 5px;
      margin-bottom         : 1em;
      overflow              : hidden;
      word-break            : break-word;
    `,

    'input': `
      border                : 1px solid ${css_properties.colors.veryLightGrey};
      height                : 25px;
      width                 : 250px;
      border-radius         : 3px;
      padding               : 0 8px;
      overflow              : hidden;
      word-break            : normal;
    `
  }
  /* --------------------------------------------------------------------------
                                    BUTTONS
  -------------------------------------------------------------------------- */
  var buttons = {

    'button': `
      background-color        : ${elementColors.button_BackgroundColor};
      border                  : .3px solid ${elementColors.button_BorderColor};
      color                   : ${elementColors.button_TextColor};
      display                 : flex;
      align-items             : center;
      justify-content         : center;
      border-radius           : 3px;
      cursor                  : pointer;
      min-height              : 25px;
      max-height              : 25px;
      width                   : 70px;
      min-width               : 70px;
      font-size               : 12px;
      overflow                : hidden;
      word-break              : normal;
    `,

    'button:hover': `
      opacity                 : 0.8;
    `,

    'dropdown': `
      color                   : ${elementColors.dropdown_TextColor};
      background-color        : ${elementColors.dropdown_BackgroundColor};
      border                  : 1px solid ${elementColors.dropdown_BorderColor};
      font-size               : 12px;
      font-weight             : bold;
      padding                 : 0 8px;
      text-decoration         : none;
      cursor                  : pointer;
      border-radius           : 3px;
      height                  : 25px;
      width                   : 250px;
      text-align              : center;
      overflow                : hidden;
      word-break              : normal;
    `

  }

  return {
    colors: css_properties.colors,
    elementColors: elementColors,
    dropdown: buttons['dropdown'],
    button: buttons['button'],
    inputField: textBoxes['input'],
    infoTextBox: textBoxes['info-text-box'],
    displayBox: textBoxes['display-box']
  }
}

/*

COMMENTS

1. most css properties can take many or infinite amounf of different values
=> so we define a set of concrete values that we use:
- variable just for plain colors (later also fonts, widths, paddings, border radiuses...)

2. we define certain semantic names that make sense in the context of our app
=> so we can use the values used in (1.) e.g. like 'color_red'  and assign it to e.g.
- highlightColor: color_red
- borderColor: color_white
- ...

3. we define a nested object that represents the component hierarchy that
makes up our app and use semantic names defined under (2.)

*/
<|endoftext|>


<commit_before><commit_msg>Updated HTTP headers in index<commit_after><|endoftext|>


<commit_before><commit_msg>meta: Danger should only check for PR Number, link not needed (#1227)<commit_after><|endoftext|>


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


<commit_before><commit_msg>chore: build dist deploy-cloud-functions (#84)<commit_after><|endoftext|>


<commit_before><commit_msg>fix error caused by navigating the field by keyboard then button<commit_after><|endoftext|>


<commit_before><commit_msg>add missing getFilter<commit_after><|endoftext|>


<commit_before><commit_msg>Add breadth-first search simulation<commit_after><|endoftext|>


<commit_before><commit_msg>took out errors in the JS file<commit_after><|endoftext|>


<commit_before><commit_msg>Add usage statistics<commit_after><|endoftext|>


<commit_before><commit_msg>Fixes issue with duplicate non-anonymous structs (#49)<commit_after><|endoftext|>


<commit_before><commit_msg>Added custom browser for travis<commit_after><|endoftext|>


<commit_before><commit_msg>load local storage into tests<commit_after><|endoftext|>


<commit_before><commit_msg>chore: try fix chrome headless on travis<commit_after><|endoftext|>


<commit_before><commit_msg>Add Karma configuration<commit_after><|endoftext|>


<commit_before><commit_msg>karma.conf: Load all scripts in lib<commit_after><|endoftext|>


<commit_before><commit_msg>updated karma.conf.js<commit_after><|endoftext|>


<commit_before><commit_msg>Update Jailer.js<commit_after><|endoftext|>


<commit_before><commit_msg>Minor style fix<commit_after><|endoftext|>


<commit_before><commit_msg>SPV -> RPV<commit_after><|endoftext|>


<commit_before><commit_msg>Modify key parser<commit_after><|endoftext|>


<commit_before><commit_msg>Changed "unsatisfied" to "out of range"<commit_after><|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var uuid = require('node-uuid');
var ObjectStream = require('./object_stream');
var BinaryStream = require('./binary_stream')
var Logger = require('./logger');
var PubSub = require('./pubsub_service');

var Device = module.exports = function() {
  this.id = uuid.v4();

  this.allowed = {};
  this.transitions = {};
  this.emitter = new EventEmitter();
  this.monitors = [];
  this.streams = {};
  this.properties = {};
  this._devices = [];
  this._pubsub = new PubSub();
  this._log = new Logger({ pubsub: this._pubsub });

  var reserved = ['properties', 'allowed', 'transitions', '_devices', 'streams', 'emitter', 'monitors'];

  var self = this;

  this.on = function(type, handler) {
    self.emitter.on(type, handler);
  }.bind(this);

  this.update = function() {
    var properties = {};
    var self = this;
    Object.keys(self).forEach(function(key) {
      if (reserved.indexOf(key) === -1 && typeof self[key] !== 'function' && key[0] !== '_') {
        properties[key] = self[key];
      }
    });

    this.properties = properties;
  }.bind(this);

  this.update();

  // TODO: Namespace this as something weird so there's no accidental override.

  this.call = this.call.bind(this);
  this.emit = this.emitter.emit.bind(this.emitter);
};

Device.prototype.stream = function(queueName, handler, options) {
  if (!options) {
    options = {};
  }

  var queue = this.type + '/' + this.id + '/' + queueName;

  var stream = null;
  if (options.binary) {
    var stream = new BinaryStream(queue, {}, this._pubsub);
  } else {
    var stream = new ObjectStream(queue, {}, this._pubsub);
  }

  this.streams[queueName] = stream;
  handler.call(this, stream);
  return this;
};

Device.prototype.map = function(type, handler, fields) {
  this.transitions[type] = { handler: handler, fields: fields };
  return this;
};

Device.prototype.devices = function(subdevices) {
  this._devices = this._devices.concat(subdevices);
  this._devices = this._devices;
  return this;
};

Device.prototype.when = function(state, options) {
  var allow = options.allow;
  if (!allow) {
    return this;
  }

  this.allowed[state] = allow;

  return this;
};

Device.prototype.call = function(/* type, ...args */) {
  var args = Array.prototype.slice.call(arguments);
  var type = args[0];
  var next = args[args.length-1];

  var rest = null;
  if(typeof next !== 'function') {
    next = function(err){};
    rest = args.slice(1, args.length);
  } else {
    rest = args.slice(1, args.length - 1);
  }

  var self = this;
  var cb = function callback() {

    self.update();

    var cbArgs = Array.prototype.slice.call(arguments);
    if (cbArgs.length && cbArgs[0] instanceof Error) {
      self.emitter.emit('error', cbArgs[0]);
    } else {
      cbArgs.unshift(type);
      self.emitter.emit.apply(self.emitter, cbArgs);
      var d = { name: self.name, transition: type, properties: self.properties };
      self._pubsub.publish(self.type + '/_transitions', d);
      self._log.emit('log', 'fog-runtime', 'MachineConfig ' + self.type + ' transititon ' + type, d);
    }

    next.apply(arguments);
  };
  var handlerArgs = rest.concat([cb]);

  if (this.transitions[type]) {
    if(this.transitions[type].handler === undefined){
      throw new Error('Machine does not implement transition '+type);
      return;
    }
    var state = self.properties.state;
    var allowed = this.allowed[state];
    if (allowed.indexOf(type) > -1) {
      this.transitions[type].handler.apply(this, handlerArgs);
    } else {
      throw new Error('Machine cannot use transition ' + type + ' while in ' + state);
    }
  }
};

Device.prototype.monitor = function(queueName) {
  var queue = this.type + '/' + this.id + '/' + queueName;

  var stream = new ObjectStream(queue, {}, this._pubsub);
  this.streams[queueName] = stream;
  this.monitors.push(stream);

  var self = this;

  Object.defineProperty(this, queueName, {
    get: function(){
      if(self.properties.hasOwnProperty(queueName)) {
        return self.properties[queueName];
      } else {
        return self[queueName];
      }
    },
    set: function(newValue){
      stream.write(newValue);
      self.properties[queueName] = newValue;
    }
  });

  return this;
};

Device.prototype.name = function(name) {
  this.name = name;
  this.update();
  return this;
};

Device.prototype.type = function(type) {
  this.type = type;
  this.update();
  return this;
};

Device.prototype.state = function(name) {
  this.state = name;
  this.update();
  return this;
};

Device.prototype.update = function() {
  var properties = {};
  var self = this;
  Object.keys(self).forEach(function(key) {
    if (reserved.indexOf(key) === -1 && typeof self[key] !== 'function' && key[0] !== '_') {
      properties[key] = self[key];
    }
  });

  this.properties = properties;
};
<commit_msg>Fixing typo in log.<commit_after>var EventEmitter = require('events').EventEmitter;
var uuid = require('node-uuid');
var ObjectStream = require('./object_stream');
var BinaryStream = require('./binary_stream')
var Logger = require('./logger');
var PubSub = require('./pubsub_service');

var Device = module.exports = function() {
  this.id = uuid.v4();

  this.allowed = {};
  this.transitions = {};
  this.emitter = new EventEmitter();
  this.monitors = [];
  this.streams = {};
  this.properties = {};
  this._devices = [];
  this._pubsub = new PubSub();
  this._log = new Logger({ pubsub: this._pubsub });

  var reserved = ['properties', 'allowed', 'transitions', '_devices', 'streams', 'emitter', 'monitors'];

  var self = this;

  this.on = function(type, handler) {
    self.emitter.on(type, handler);
  }.bind(this);

  this.update = function() {
    var properties = {};
    var self = this;
    Object.keys(self).forEach(function(key) {
      if (reserved.indexOf(key) === -1 && typeof self[key] !== 'function' && key[0] !== '_') {
        properties[key] = self[key];
      }
    });

    this.properties = properties;
  }.bind(this);

  this.update();

  // TODO: Namespace this as something weird so there's no accidental override.

  this.call = this.call.bind(this);
  this.emit = this.emitter.emit.bind(this.emitter);
};

Device.prototype.stream = function(queueName, handler, options) {
  if (!options) {
    options = {};
  }

  var queue = this.type + '/' + this.id + '/' + queueName;

  var stream = null;
  if (options.binary) {
    var stream = new BinaryStream(queue, {}, this._pubsub);
  } else {
    var stream = new ObjectStream(queue, {}, this._pubsub);
  }

  this.streams[queueName] = stream;
  handler.call(this, stream);
  return this;
};

Device.prototype.map = function(type, handler, fields) {
  this.transitions[type] = { handler: handler, fields: fields };
  return this;
};

Device.prototype.devices = function(subdevices) {
  this._devices = this._devices.concat(subdevices);
  this._devices = this._devices;
  return this;
};

Device.prototype.when = function(state, options) {
  var allow = options.allow;
  if (!allow) {
    return this;
  }

  this.allowed[state] = allow;

  return this;
};

Device.prototype.call = function(/* type, ...args */) {
  var args = Array.prototype.slice.call(arguments);
  var type = args[0];
  var next = args[args.length-1];

  var rest = null;
  if(typeof next !== 'function') {
    next = function(err){};
    rest = args.slice(1, args.length);
  } else {
    rest = args.slice(1, args.length - 1);
  }

  var self = this;
  var cb = function callback() {

    self.update();

    var cbArgs = Array.prototype.slice.call(arguments);
    if (cbArgs.length && cbArgs[0] instanceof Error) {
      self.emitter.emit('error', cbArgs[0]);
    } else {
      cbArgs.unshift(type);
      self.emitter.emit.apply(self.emitter, cbArgs);
      var d = { name: self.name, transition: type, properties: self.properties };
      self._pubsub.publish(self.type + '/_transitions', d);
      self._log.emit('log', 'device', self.type + ' transition ' + type, d);
    }

    next.apply(arguments);
  };
  var handlerArgs = rest.concat([cb]);

  if (this.transitions[type]) {
    if(this.transitions[type].handler === undefined){
      throw new Error('Machine does not implement transition '+type);
      return;
    }
    var state = self.properties.state;
    var allowed = this.allowed[state];
    if (allowed.indexOf(type) > -1) {
      this.transitions[type].handler.apply(this, handlerArgs);
    } else {
      throw new Error('Machine cannot use transition ' + type + ' while in ' + state);
    }
  }
};

Device.prototype.monitor = function(queueName) {
  var queue = this.type + '/' + this.id + '/' + queueName;

  var stream = new ObjectStream(queue, {}, this._pubsub);
  this.streams[queueName] = stream;
  this.monitors.push(stream);

  var self = this;

  Object.defineProperty(this, queueName, {
    get: function(){
      if(self.properties.hasOwnProperty(queueName)) {
        return self.properties[queueName];
      } else {
        return self[queueName];
      }
    },
    set: function(newValue){
      stream.write(newValue);
      self.properties[queueName] = newValue;
    }
  });

  return this;
};

Device.prototype.name = function(name) {
  this.name = name;
  this.update();
  return this;
};

Device.prototype.type = function(type) {
  this.type = type;
  this.update();
  return this;
};

Device.prototype.state = function(name) {
  this.state = name;
  this.update();
  return this;
};

Device.prototype.update = function() {
  var properties = {};
  var self = this;
  Object.keys(self).forEach(function(key) {
    if (reserved.indexOf(key) === -1 && typeof self[key] !== 'function' && key[0] !== '_') {
      properties[key] = self[key];
    }
  });

  this.properties = properties;
};
<|endoftext|>


<commit_before><commit_msg>Add inPipe method<commit_after><|endoftext|>


<commit_before>const fs = require('fs');
const assert = require('assert');
const common = require('../prelude/common.js');
const log = require('./log.js').log;
const pkgVersion = require('../package.json').version;

const STORE_CODE = common.STORE_CODE;
const STORE_CONTENT = common.STORE_CONTENT;
const STORE_LINKS = common.STORE_LINKS;
const STORE_STAT = common.STORE_STAT;

const isDotJS = common.isDotJS;
const isDotJSON = common.isDotJSON;
const snapshotify = common.snapshotify;

const bootstrapText = fs.readFileSync(
  require.resolve('../prelude/bootstrap.js'), 'utf8'
).replace('%PKG_VERSION%', pkgVersion);

const commonText = fs.readFileSync(
  require.resolve('../prelude/common.js'), 'utf8'
);

function itemsToText (items) {
  const len = items.length;
  return len.toString() +
    (len % 10 === 1 ? ' item' : ' items');
}

function reduceRecords (records) {
  assert(Array.isArray(records), 'packer: bad records to reduce');
  const result = {};

  records.some(function (record) {
    if (record.discard) return;
    const file = record.file;
    if (!result[file]) result[file] = {};
    result[file][record.store] = record.body;
  });

  return result;
}

function packer (opts, cb) {
  const stripe = [];

  function write (x) {
    assert(typeof x === 'string', 'packer: can write only strings');
    stripe.push(x);
  }

  const records = reduceRecords(opts.records);

  write('(function(REQUIRE_COMMON, VIRTUAL_FILESYSTEM, DEFAULT_ENTRYPOINT) {');
  write(bootstrapText);
  write('})(function(exports) {');
  write(commonText);
  write('}, {\n');

  let first1 = true;

  Object.keys(records).some(function (file) {
    if (!first1) write(',');
    first1 = false;

    write(JSON.stringify(snapshotify(file, opts.slash)));
    write(':[\n');

    const record = records[file];
    assert(record[STORE_STAT], 'packer: no STORE_STAT');

    if ((typeof record[STORE_CODE] !== 'undefined') &&
        (typeof record[STORE_CONTENT] !== 'undefined')) {
      delete record[STORE_CODE];
    }

    let first2 = true;

    [ STORE_CODE, STORE_CONTENT, STORE_LINKS, STORE_STAT
    ].some(function (store, index) {
      assert(store === index, 'packer: stores misordered');
      if (!first2) write(',');
      first2 = false;

      const value = record[store];

      if (typeof value === 'undefined') {
        write('null');
        return;
      }

      if (store === STORE_CODE) {
        assert(typeof value === 'string', 'packer: bad STORE_CODE');

        write('function(exports, require, module, __filename, __dirname) {\n');
        write(value);
        write('\n}'); // dont remove \n, otherwise last comment will cover right brace

        log.debug('The file was included as compiled code (no sources)', file);
      } else
      if (store === STORE_CONTENT) {
        if (Buffer.isBuffer(value)) {
          write('new Buffer(\'');
          write(value.toString('base64'));
          write('\',\'base64\')');
        } else
        if (typeof value === 'string') {
          write('new Buffer(\'');
          write((new Buffer(value)).toString('base64'));
          write('\',\'base64\')');
        } else {
          assert(false, 'packer: bad STORE_CONTENT');
        }

        const disclosed = isDotJS(file) || isDotJSON(file);
        log.debug(disclosed ? 'The file was included as DISCLOSED code (with sources)'
                            : 'The file was included as asset content', file);
      } else
      if (store === STORE_LINKS) {
        assert(Array.isArray(value), 'packer: bad STORE_LINKS');
        write(JSON.stringify(value));
        log.debug('The directory files list was included (' + itemsToText(value) + ')', file);
      } else
      if (store === STORE_STAT) {
        assert(typeof value === 'object', 'packer: bad STORE_STAT');
        const newValue = Object.assign({}, value);
        newValue.atime = value.atime.getTime();
        newValue.mtime = value.mtime.getTime();
        newValue.ctime = value.ctime.getTime();
        newValue.birthtime = value.birthtime.getTime();
        newValue.isFileValue = value.isFile();
        newValue.isDirectoryValue = value.isDirectory();
        write(JSON.stringify(newValue));
      } else {
        assert(false, 'packer: unknown store');
      }
    });

    write('\n]');
  });

  write('\n},');

  opts.records.some(function (record) {
    if (record.entrypoint) {
      write(JSON.stringify(snapshotify(record.file, opts.slash)));
      return true;
    }
  });

  write('\n)');

  cb(null, stripe);
}

module.exports = function (opts) {
  return new Promise((resolve, reject) => {
    packer(opts, (error, stripe) => {
      if (error) return reject(error);
      resolve(stripe);
    });
  });
};
<commit_msg>no need in callback in packer<commit_after>const fs = require('fs');
const assert = require('assert');
const common = require('../prelude/common.js');
const log = require('./log.js').log;
const pkgVersion = require('../package.json').version;

const STORE_CODE = common.STORE_CODE;
const STORE_CONTENT = common.STORE_CONTENT;
const STORE_LINKS = common.STORE_LINKS;
const STORE_STAT = common.STORE_STAT;

const isDotJS = common.isDotJS;
const isDotJSON = common.isDotJSON;
const snapshotify = common.snapshotify;

const bootstrapText = fs.readFileSync(
  require.resolve('../prelude/bootstrap.js'), 'utf8'
).replace('%PKG_VERSION%', pkgVersion);

const commonText = fs.readFileSync(
  require.resolve('../prelude/common.js'), 'utf8'
);

function itemsToText (items) {
  const len = items.length;
  return len.toString() +
    (len % 10 === 1 ? ' item' : ' items');
}

function reduceRecords (records) {
  assert(Array.isArray(records), 'packer: bad records to reduce');
  const result = {};

  records.some(function (record) {
    if (record.discard) return;
    const file = record.file;
    if (!result[file]) result[file] = {};
    result[file][record.store] = record.body;
  });

  return result;
}

module.exports = function packer (opts) {
  const stripe = [];

  function write (x) {
    assert(typeof x === 'string', 'packer: can write only strings');
    stripe.push(x);
  }

  const records = reduceRecords(opts.records);

  write('(function(REQUIRE_COMMON, VIRTUAL_FILESYSTEM, DEFAULT_ENTRYPOINT) {');
  write(bootstrapText);
  write('})(function(exports) {');
  write(commonText);
  write('}, {\n');

  let first1 = true;

  Object.keys(records).some(function (file) {
    if (!first1) write(',');
    first1 = false;

    write(JSON.stringify(snapshotify(file, opts.slash)));
    write(':[\n');

    const record = records[file];
    assert(record[STORE_STAT], 'packer: no STORE_STAT');

    if ((typeof record[STORE_CODE] !== 'undefined') &&
        (typeof record[STORE_CONTENT] !== 'undefined')) {
      delete record[STORE_CODE];
    }

    let first2 = true;

    [ STORE_CODE, STORE_CONTENT, STORE_LINKS, STORE_STAT
    ].some(function (store, index) {
      assert(store === index, 'packer: stores misordered');
      if (!first2) write(',');
      first2 = false;

      const value = record[store];

      if (typeof value === 'undefined') {
        write('null');
        return;
      }

      if (store === STORE_CODE) {
        assert(typeof value === 'string', 'packer: bad STORE_CODE');

        write('function(exports, require, module, __filename, __dirname) {\n');
        write(value);
        write('\n}'); // dont remove \n, otherwise last comment will cover right brace

        log.debug('The file was included as compiled code (no sources)', file);
      } else
      if (store === STORE_CONTENT) {
        if (Buffer.isBuffer(value)) {
          write('new Buffer(\'');
          write(value.toString('base64'));
          write('\',\'base64\')');
        } else
        if (typeof value === 'string') {
          write('new Buffer(\'');
          write((new Buffer(value)).toString('base64'));
          write('\',\'base64\')');
        } else {
          assert(false, 'packer: bad STORE_CONTENT');
        }

        const disclosed = isDotJS(file) || isDotJSON(file);
        log.debug(disclosed ? 'The file was included as DISCLOSED code (with sources)'
                            : 'The file was included as asset content', file);
      } else
      if (store === STORE_LINKS) {
        assert(Array.isArray(value), 'packer: bad STORE_LINKS');
        write(JSON.stringify(value));
        log.debug('The directory files list was included (' + itemsToText(value) + ')', file);
      } else
      if (store === STORE_STAT) {
        assert(typeof value === 'object', 'packer: bad STORE_STAT');
        const newValue = Object.assign({}, value);
        newValue.atime = value.atime.getTime();
        newValue.mtime = value.mtime.getTime();
        newValue.ctime = value.ctime.getTime();
        newValue.birthtime = value.birthtime.getTime();
        newValue.isFileValue = value.isFile();
        newValue.isDirectoryValue = value.isDirectory();
        write(JSON.stringify(newValue));
      } else {
        assert(false, 'packer: unknown store');
      }
    });

    write('\n]');
  });

  write('\n},');

  opts.records.some(function (record) {
    if (record.entrypoint) {
      write(JSON.stringify(snapshotify(record.file, opts.slash)));
      return true;
    }
  });

  write('\n)');

  return stripe;
};
<|endoftext|>


<commit_before><commit_msg>version 2.4.4<commit_after><|endoftext|>


<commit_before>'use strict';
var _ = require('lodash');
var BBPromise = require('bluebird');
var Model = require('hoist-model');
var logger = require('hoist-logger');
var config = require('config');
var fs = require('fs');
var path = require('path');
var SubscriptionController = require('./subscription_controller');
var EventListener =  require('./event_listener');

function Poller() {
  this.stopped = false;
}

Poller.prototype = {
  start: function () {
    // var _timer;
    logger.info('starting poller');
    /* istanbul ignore else */
    if (Model._mongoose.connection.readyState !== 1) {
      logger.info('mongo connected');
      Model._mongoose.connect(config.get('Hoist.mongo.db'));
    }
    return Model.Subscription.findAsync({})
      .bind(this)
      .then(function (subscriptions) {
        return BBPromise.settle(_.map(subscriptions, _.bind(this.hydrateSubscription, this)));
      }).then(function (promises) {
        // wait two minutes until next poll
        if (!this.stopped) {
          return BBPromise.delay(120000).bind(this).then(function () {
            return this.start();
          });
        }
        return promises;
      }).catch(function (err) {
        logger.info('error:', err, err.stack);
        console.log('error:', err, err.stack);
      });
  },
  hydrateSubscription: function (subscription) {
    var self = this;
    return Model.ConnectorSetting.findOneAsync({
        key: subscription.connector,
        environment: subscription.environment,
        application: subscription.application
      })
      .then(function (connector) {
        /* istanbul ignore else */
        return Model.Application.findOneAsync({
            _id: connector.application
          })
          .then(function (app) {
            var query = {
              application: app._id,
              environment: subscription.environment,
              connectorKey: connector.key,
              connectorType: connector.connectorType
            };
            return Model.BouncerToken.findOneAsync(query)
              .then(function (bouncer) {
                var query = {
                  application: app._id,
                  environment: subscription.environment
                };
                query['meta.authToken.' + connector.key] = {
                  $exists: true
                };
                return Model.Bucket.findAsync(query)
                  .then(function (buckets) {
                    var info = {
                      connector: connector._id,
                      application: app._id,
                      bouncer: bouncer._id
                    };
                    logger.info('inside poller#hydrateSubscription', info);
                    return BBPromise.settle(_.map(buckets, function (bucket) {
                      return self.pollModule(app, bucket, subscription, connector, bouncer);
                    }));
                  });
              });
          });
      }).catch(function (err) {
        logger.info('error', err, err.stack);
        console.log('err', err);
      });
  },
  pollModule: function (app, bucket, subscription, connector, bouncer) {
    // add listeners
    var _subscription = new SubscriptionController(subscription);
    new EventListener(_subscription, connector, bucket).listen();
    _subscription.eventEmitter.on('done', function () {
      console.log('poll listener done');
      _subscription.eventEmitter.removeAllListeners();
    });
    var connectorsPath = path.resolve(config.get('Hoist.connectors.path'));
    var connectorPath = path.join(connectorsPath, connector.connectorType, config.get('Hoist.connectors.currentDirectoryName'), 'lib/poll.js');
    connectorPath = fs.realpathSync(connectorPath);
    logger.info('connectorPath', connectorPath);
    return require(connectorPath)(app.toObject(), bucket.toObject(), _subscription, bouncer.toObject(), connector.toObject());
  },
  stop: /* istanbul ignore next */ function () {
    this.stopped = true;
  },
  restart: function () {
    this.stopped = false;
    return this.start();
  }
};

module.exports = new Poller();<commit_msg>only log bouncer if there is a bouncer token<commit_after>'use strict';
var _ = require('lodash');
var BBPromise = require('bluebird');
var Model = require('hoist-model');
var logger = require('hoist-logger');
var config = require('config');
var fs = require('fs');
var path = require('path');
var SubscriptionController = require('./subscription_controller');
var EventListener = require('./event_listener');

function Poller() {
  this.stopped = false;
}

Poller.prototype = {
  start: function () {
    // var _timer;
    logger.info('starting poller');
    /* istanbul ignore else */
    if (Model._mongoose.connection.readyState !== 1) {
      logger.info('mongo connected');
      Model._mongoose.connect(config.get('Hoist.mongo.db'));
    }
    return Model.Subscription.findAsync({})
      .bind(this)
      .then(function (subscriptions) {
        return BBPromise.settle(_.map(subscriptions, _.bind(this.hydrateSubscription, this)));
      }).then(function (promises) {
        // wait two minutes until next poll
        if (!this.stopped) {
          return BBPromise.delay(120000).bind(this).then(function () {
            return this.start();
          });
        }
        return promises;
      }).catch(function (err) {
        logger.info('error:', err, err.stack);
        console.log('error:', err, err.stack);
      });
  },
  hydrateSubscription: function (subscription) {
    var self = this;
    return Model.ConnectorSetting.findOneAsync({
        key: subscription.connector,
        environment: subscription.environment,
        application: subscription.application
      })
      .then(function (connector) {
        /* istanbul ignore else */
        return Model.Application.findOneAsync({
            _id: connector.application
          })
          .then(function (app) {
            var query = {
              application: app._id,
              environment: subscription.environment,
              connectorKey: connector.key,
              connectorType: connector.connectorType
            };
            return Model.BouncerToken.findOneAsync(query)
              .then(function (bouncer) {
                var query = {
                  application: app._id,
                  environment: subscription.environment
                };
                query['meta.authToken.' + connector.key] = {
                  $exists: true
                };
                return Model.Bucket.findAsync(query)
                  .then(function (buckets) {
                    var info = {
                      connector: connector._id,
                      application: app._id,
                      info.bouncer: bouncer ? bouncer._id : null
                    };
                    logger.info('inside poller#hydrateSubscription', info);
                    return BBPromise.settle(_.map(buckets, function (bucket) {
                      return self.pollModule(app, bucket, subscription, connector, bouncer);
                    }));
                  });
              });
          });
      }).catch(function (err) {
        logger.info('error', err, err.stack);
        console.log('err', err);
      });
  },
  pollModule: function (app, bucket, subscription, connector, bouncer) {
    // add listeners
    var _subscription = new SubscriptionController(subscription);
    new EventListener(_subscription, connector, bucket).listen();
    _subscription.eventEmitter.on('done', function () {
      console.log('poll listener done');
      _subscription.eventEmitter.removeAllListeners();
    });
    var connectorsPath = path.resolve(config.get('Hoist.connectors.path'));
    var connectorPath = path.join(connectorsPath, connector.connectorType, config.get('Hoist.connectors.currentDirectoryName'), 'lib/poll.js');
    connectorPath = fs.realpathSync(connectorPath);
    logger.info('connectorPath', connectorPath);
    return require(connectorPath)(app.toObject(), bucket.toObject(), _subscription, bouncer.toObject(), connector.toObject());
  },
  stop: /* istanbul ignore next */ function () {
    this.stopped = true;
  },
  restart: function () {
    this.stopped = false;
    return this.start();
  }
};

module.exports = new Poller();<|endoftext|>


<commit_before><commit_msg>* fixed process msg bug<commit_after><|endoftext|>


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

    var DIR_ROOT            = __dirname + '/..',

        path                = require('path'),

        join                = require('join-io'),
        mollify             = require('mollify'),

        remove              = require('./remove'),

        minifyFunc          = mollify({
            dir     : DIR_ROOT
        });

    module.exports          = function(options) {
        return serve.bind(null, options);
    };

    module.exports.listen   = function(socket, options) {
        var ret;

        if (!options)
            options = {};

        if (!options.prefix)
            options.prefix = 'spero';

        if (!options.root)
            options.root = '/';

        remove(socket, options);

        return ret;
    };

    function checkOption(isOption) {
        var is,
            type    = typeof isOption;

        switch(type) {
        case 'function':
            is = isOption();
            break;

        case 'undefined':
            is = true;
            break;

        default:
            is = isOption;
        }

        return is;
    }

    function serve(options, req, res, next) {
        var joinFunc, isJoin, isConfig,

            o           = options || {},

            isMin       = checkOption(o.minify),
            isOnline    = checkOption(o.online),

            url         = req.url,
            prefix      = o.prefix || '/remedy',

            isSpero    = !url.indexOf(prefix),

            URL         = prefix + '/remedy.js',
            CONFIG      = prefix + '/options.json',

            PATH        = '/js/remedy.js',
            sendFile    = function() {
                url = path.normalize(DIR_ROOT + url);
                res.sendFile(url);
            };

        if (!isSpero) {
            next();
        } else {
            isJoin      = !url.indexOf(prefix + '/join');
            isConfig    = url === CONFIG;

            if (url === URL)
                url = PATH;
            else
                url = url.replace(prefix, '');

            req.url = url;

            if (isConfig) {
                res .type('json')
                    .send({
                        online: isOnline
                    });
            } else if (isMin) {
                minifyFunc(req, res, sendFile);
            } else if (!isJoin) {
                sendFile();
            } else {
                joinFunc = join({
                    dir     : DIR_ROOT,
                    minify  : isMin
                });

                joinFunc(req, res, next);
            }
        }
    }
})();
<commit_msg>fix(remedy) spero -> /remedy<commit_after>(function() {
    'use strict';

    var DIR_ROOT            = __dirname + '/..',

        path                = require('path'),

        join                = require('join-io'),
        mollify             = require('mollify'),

        remove              = require('./remove'),

        minifyFunc          = mollify({
            dir     : DIR_ROOT
        });

    module.exports          = function(options) {
        return serve.bind(null, options);
    };

    module.exports.listen   = function(socket, options) {
        var ret;

        if (!options)
            options = {};

        if (!options.prefix)
            options.prefix = '/remedy';

        if (!options.root)
            options.root = '/';

        remove(socket, options);

        return ret;
    };

    function checkOption(isOption) {
        var is,
            type    = typeof isOption;

        switch(type) {
        case 'function':
            is = isOption();
            break;

        case 'undefined':
            is = true;
            break;

        default:
            is = isOption;
        }

        return is;
    }

    function serve(options, req, res, next) {
        var joinFunc, isJoin, isConfig,

            o           = options || {},

            isMin       = checkOption(o.minify),
            isOnline    = checkOption(o.online),

            url         = req.url,
            prefix      = o.prefix || '/remedy',

            isSpero    = !url.indexOf(prefix),

            URL         = prefix + '/remedy.js',
            CONFIG      = prefix + '/options.json',

            PATH        = '/js/remedy.js',
            sendFile    = function() {
                url = path.normalize(DIR_ROOT + url);
                res.sendFile(url);
            };

        if (!isSpero) {
            next();
        } else {
            isJoin      = !url.indexOf(prefix + '/join');
            isConfig    = url === CONFIG;

            if (url === URL)
                url = PATH;
            else
                url = url.replace(prefix, '');

            req.url = url;

            if (isConfig) {
                res .type('json')
                    .send({
                        online: isOnline
                    });
            } else if (isMin) {
                minifyFunc(req, res, sendFile);
            } else if (!isJoin) {
                sendFile();
            } else {
                joinFunc = join({
                    dir     : DIR_ROOT,
                    minify  : isMin
                });

                joinFunc(req, res, next);
            }
        }
    }
})();
<|endoftext|>


<commit_before><commit_msg>add missing ctx in constructor (#23)<commit_after><|endoftext|>


<commit_before><commit_msg>Improve origin-creating function to detect and report incorrect invocation.<commit_after><|endoftext|>


<commit_before>/*!
 * react-native-multi-select
 * Copyright(c) 2017 Mustapha Babatunde Oluwaleke
 * MIT Licensed
 */

export const colorPack = {
  primary: '#00A5FF',
  primaryDark: '#215191',
  light: '#FFF',
  textPrimary: '#525966',
  placeholderTextColor: '#A9A9A9',
  danger: '#C62828',
  borderColor: '#e9e9e9',
  backgroundColor: '#b1b1b1'
};

export default {
  footerWrapper: {
    flexWrap: 'wrap',
    alignItems: 'flex-start',
    flexDirection: 'row'
  },
  footerWrapperNC: {
    width: 320,
    flexDirection: 'column'
  },
  subSection: {
    backgroundColor: colorPack.light,
    borderBottomWidth: 1,
    borderColor: colorPack.borderColor,
    paddingLeft: 0,
    paddingRight: 20,
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center'
  },
  greyButton: {
    height: 40,
    borderRadius: 5,
    elevation: 0,
    backgroundColor: colorPack.backgroundColor
  },
  indicator: {
    fontSize: 30,
    color: colorPack.placeholderTextColor
  },
  selectedItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 15,
    paddingTop: 3,
    paddingRight: 3,
    paddingBottom: 3,
    margin: 3,
    borderRadius: 20,
    borderWidth: 2
  },
  button: {
    height: 40,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  },
  buttonText: {
    color: colorPack.light,
    fontSize: 14
  },
  selectorView: fixedHeight => {
    const style = {
      flexDirection: 'column',
      marginBottom: 10,
      elevation: 2
    };
    if (fixedHeight) {
      style.height = 250;
    }
    return style;
  },
  inputGroup: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 16,
    backgroundColor: colorPack.light
  },
  dropdownView: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 40,
    marginBottom: 10
  }
};
<commit_msg>Fix lint issues in styles<commit_after>/*!
 * react-native-multi-select
 * Copyright(c) 2017 Mustapha Babatunde Oluwaleke
 * MIT Licensed
 */

export const colorPack = {
  primary: '#00A5FF',
  primaryDark: '#215191',
  light: '#FFF',
  textPrimary: '#525966',
  placeholderTextColor: '#A9A9A9',
  danger: '#C62828',
  borderColor: '#e9e9e9',
  backgroundColor: '#b1b1b1',
};

export default {
  footerWrapper: {
    flexWrap: 'wrap',
    alignItems: 'flex-start',
    flexDirection: 'row',
  },
  footerWrapperNC: {
    width: 320,
    flexDirection: 'column',
  },
  subSection: {
    backgroundColor: colorPack.light,
    borderBottomWidth: 1,
    borderColor: colorPack.borderColor,
    paddingLeft: 0,
    paddingRight: 20,
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  greyButton: {
    height: 40,
    borderRadius: 5,
    elevation: 0,
    backgroundColor: colorPack.backgroundColor,
  },
  indicator: {
    fontSize: 30,
    color: colorPack.placeholderTextColor,
  },
  selectedItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 15,
    paddingTop: 3,
    paddingRight: 3,
    paddingBottom: 3,
    margin: 3,
    borderRadius: 20,
    borderWidth: 2,
  },
  button: {
    height: 40,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonText: {
    color: colorPack.light,
    fontSize: 14,
  },
  selectorView: (fixedHeight) => {
    const style = {
      flexDirection: 'column',
      marginBottom: 10,
      elevation: 2,
    };
    if (fixedHeight) {
      style.height = 250;
    }
    return style;
  },
  inputGroup: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 16,
    backgroundColor: colorPack.light,
  },
  dropdownView: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 40,
    marginBottom: 10,
  },
};
<|endoftext|>


<commit_before><commit_msg>Fix token types import<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: linting error<commit_after><|endoftext|>


<commit_before>var util = require('util');

function _has(obj, propName) {
    return Object.prototype.hasOwnProperty.call(obj, propName);
}

function copyPlainObject(src) {
    var o = {};
    Object.getOwnPropertyNames(src).forEach(function(key) {
        o[key] = src[key];
    });
    return o;
}

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

    this.message = '$$MESSAGE$$';
    Error.captureStackTrace(this, this.constructor);
    this._stackTemplate = this.stack;

    this.code = typeof code === 'undefined' || code === null ? Terror.CODES.UNKNOWN_ERROR : code;
    this.setMessage(message || this.constructor.MESSAGES[this.code]);
    this.data = {};
}
util.inherits(Terror, Error);

Terror.prototype.name = 'Terror';

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

    Inheritor.prototype.name = name;

    // link contructors methods
    Inheritor.create = Super.create;
    Inheritor.extendCodes = Super.extendCodes;
    Inheritor.setLogger = Super.setLogger;
    Inheritor.createError = Super.createError;
    Inheritor.ensureError = Super.ensureError;
    // copy static fields
    Inheritor.CODES = copyPlainObject(Super.CODES);
    Inheritor.MESSAGES = copyPlainObject(Super.MESSAGES);
    Inheritor.DEFAULT_ERROR_LEVEL = Super.DEFAULT_ERROR_LEVEL;

    if (typeof codes === 'object' && codes !== null) {
        Inheritor.extendCodes(codes);
    }

    return Inheritor;
};

/**
 * Extends existing CODE and MESSAGE hashes.
 * @param {Object} codes { CODE_NAME: 'error message', … }
 * @returns {Function} constructor
 * @throws TerrorError if collisions detected.
 */
Terror.extendCodes = function(codes) {
    var ctor = this;

    Object.keys(codes).forEach(function(code) {
        if (_has(ctor.CODES, code)) {
            throw new Error('Terror codes collision detected in the ' +
                ctor.prototype.name + '.extendCodes call for code "' + code + '"');
        }

        ctor.CODES[code] = code;
        ctor.MESSAGES[code] = codes[code];
    });

    return this;
};

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

Terror.DEFAULT_ERROR_LEVEL = 'ERROR';

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

    if (typeof _log !== 'function') {
        _log = function() {
            console.log.apply(console, arguments);
        };
    }

    msgRows.forEach(function(row, idx) {
        _log((idx ? _arrows : _level) + ' ' + row);
    });
};

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

    return this;
};

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

    this.logger(this.code + ' ' + this.stack, level);
    this._isLogged = true;

    return this;
};

/**
 * @param {Object} data
 * @returns {Terror} self
 */
Terror.prototype.bind = function(data) {
    if (this.message.indexOf('%') > -1) {
        this.setMessage(this.message.replace(/%([^%\s]+)%/g, function(match, name) {
            return _has(data, name) ? data[name] : match;
        }));
    }

    Object.keys(data)
        .forEach(function(propName) {
            this.data[propName] = data[propName];
        }, this);

    return this;
};

Terror.CODES = {
    UNKNOWN_ERROR : 'UNKNOWN_ERROR'
};

Terror.MESSAGES = {
    UNKNOWN_ERROR : 'Unknown error'
};

Terror.prototype.setMessage = function(message) {
    this.message = message;
    // patch stacktrace
    this.stack = this._stackTemplate.replace('$$MESSAGE$$', message);
    return this;
};

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

    // patch stacktrace to avoid meaningless entry of createError call
    error.message = '$$MESSAGE$$';
    Error.captureStackTrace(error, this.createError);
    error._stackTemplate = error.stack;
    error.setMessage(_msg);

    if (message instanceof Error || typeof message === 'string') {
        error.originalError = message;
        error.setMessage(error.message + ' (' + message.toString() + ')');
    } else if (typeof message === 'object' && message !== null) {
        error.bind(message);
    }

    return error;
};

/**
 * @param {Error|Terror} error
 * @param {Number} [code]
 * @returns {Terror}
 */
Terror.ensureError = function(error, code) {
    if ( ! (error instanceof this)) {
        if (typeof code !== 'string') {
            code = this.CODES.UNKNOWN_ERROR;
        }
        error = this.createError(code, error);
    }

    return error;
};

module.exports = Terror;
<commit_msg>avoid default logger construction on every Terror#logMultilineError call<commit_after>var util = require('util');

function _has(obj, propName) {
    return Object.prototype.hasOwnProperty.call(obj, propName);
}

function copyPlainObject(src) {
    var o = {};
    Object.getOwnPropertyNames(src).forEach(function(key) {
        o[key] = src[key];
    });
    return o;
}

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

    this.message = '$$MESSAGE$$';
    Error.captureStackTrace(this, this.constructor);
    this._stackTemplate = this.stack;

    this.code = typeof code === 'undefined' || code === null ? Terror.CODES.UNKNOWN_ERROR : code;
    this.setMessage(message || this.constructor.MESSAGES[this.code]);
    this.data = {};
}
util.inherits(Terror, Error);

Terror.prototype.name = 'Terror';

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

    Inheritor.prototype.name = name;

    // link contructors methods
    Inheritor.create = Super.create;
    Inheritor.extendCodes = Super.extendCodes;
    Inheritor.setLogger = Super.setLogger;
    Inheritor.createError = Super.createError;
    Inheritor.ensureError = Super.ensureError;
    // copy static fields
    Inheritor.CODES = copyPlainObject(Super.CODES);
    Inheritor.MESSAGES = copyPlainObject(Super.MESSAGES);
    Inheritor.DEFAULT_ERROR_LEVEL = Super.DEFAULT_ERROR_LEVEL;

    if (typeof codes === 'object' && codes !== null) {
        Inheritor.extendCodes(codes);
    }

    return Inheritor;
};

/**
 * Extends existing CODE and MESSAGE hashes.
 * @param {Object} codes { CODE_NAME: 'error message', … }
 * @returns {Function} constructor
 * @throws TerrorError if collisions detected.
 */
Terror.extendCodes = function(codes) {
    var ctor = this;

    Object.keys(codes).forEach(function(code) {
        if (_has(ctor.CODES, code)) {
            throw new Error('Terror codes collision detected in the ' +
                ctor.prototype.name + '.extendCodes call for code "' + code + '"');
        }

        ctor.CODES[code] = code;
        ctor.MESSAGES[code] = codes[code];
    });

    return this;
};

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

Terror.DEFAULT_ERROR_LEVEL = 'ERROR';

function _defaultLog(msg) {
    console.log(msg);
}

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

    if (typeof _log !== 'function') {
        _log = _defaultLog;
    }

    msgRows.forEach(function(row, idx) {
        _log((idx ? _arrows : _level) + ' ' + row);
    });
};

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

    return this;
};

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

    this.logger(this.code + ' ' + this.stack, level);
    this._isLogged = true;

    return this;
};

/**
 * @param {Object} data
 * @returns {Terror} self
 */
Terror.prototype.bind = function(data) {
    if (this.message.indexOf('%') > -1) {
        this.setMessage(this.message.replace(/%([^%\s]+)%/g, function(match, name) {
            return _has(data, name) ? data[name] : match;
        }));
    }

    Object.keys(data)
        .forEach(function(propName) {
            this.data[propName] = data[propName];
        }, this);

    return this;
};

Terror.CODES = {
    UNKNOWN_ERROR : 'UNKNOWN_ERROR'
};

Terror.MESSAGES = {
    UNKNOWN_ERROR : 'Unknown error'
};

Terror.prototype.setMessage = function(message) {
    this.message = message;
    // patch stacktrace
    this.stack = this._stackTemplate.replace('$$MESSAGE$$', message);
    return this;
};

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

    // patch stacktrace to avoid meaningless entry of createError call
    error.message = '$$MESSAGE$$';
    Error.captureStackTrace(error, this.createError);
    error._stackTemplate = error.stack;
    error.setMessage(_msg);

    if (message instanceof Error || typeof message === 'string') {
        error.originalError = message;
        error.setMessage(error.message + ' (' + message.toString() + ')');
    } else if (typeof message === 'object' && message !== null) {
        error.bind(message);
    }

    return error;
};

/**
 * @param {Error|Terror} error
 * @param {Number} [code]
 * @returns {Terror}
 */
Terror.ensureError = function(error, code) {
    if ( ! (error instanceof this)) {
        if (typeof code !== 'string') {
            code = this.CODES.UNKNOWN_ERROR;
        }
        error = this.createError(code, error);
    }

    return error;
};

module.exports = Terror;
<|endoftext|>


<commit_before>var _ = require('./icebreaker')
var stream = require('stream')
var to = require('stream-to-pull-stream')
var Source = _.source
var Through = _.through
var Sink = _.sink
var Pair = _.pair

function done(cb){
  return cb?function(end){
    if(cb){ cb(end); cb=null }
  }:cb
}

_.mixin({
  source: function (s) {
    if (s instanceof stream.Stream) {
      if (s.readable) return to.source(s)
      throw Error('source: node.js stream must be readable')
    }
    return Source.apply(this, arguments)
  },
  through: function (s,cb) {
    if (s instanceof stream.Stream) {
      if (s.readable && s.writable) return Through(to(s,done(cb)))()
      throw Error('through: node.js stream must be readable and writable')
    }
    return Through.apply(this, arguments)
  },
  sink: function (s,cb) {
    if (s instanceof stream.Stream) {
      if (s.writable) return to.sink(s, done(cb))
      throw Error('sink: node.js stream must be writable')
    }
    return Sink.apply(this, arguments)
  },
  pair: function (s,cb) {
    if (s instanceof stream.Stream) {
      return to.duplex(s,done(cb))
    }
    return Pair.apply(this, arguments)
  }
})
<commit_msg>Added function toPull for node streams<commit_after>var _ = require('./icebreaker')
var stream = require('stream')
var to = require('stream-to-pull-stream')

_.mixin({
  toPull: to,
})
<|endoftext|>