<commit_before>import EntryBtn from './EntryBtn/EntryBtn'
import DevTools from './DevTools/DevTools'
import Tool from './DevTools/Tool'
import Console from './Console/Console'
import Network from './Network/Network'
import Elements from './Elements/Elements'
import Snippets from './Snippets/Snippets'
import Resources from './Resources/Resources'
import Info from './Info/Info'
import Sources from './Sources/Sources'
import Settings from './Settings/Settings'
import emitter from './lib/emitter'
import logger from './lib/logger'
import extraUtil from './lib/extraUtil'
import util from './lib/util'
import {
  isFn,
  evalCss,
  isNum,
  isObj,
  isMobile,
  viewportScale,
  detectBrowser,
  $,
  toArr,
  upperFirst,
  nextTick,
  last
} from './lib/util'

module.exports = {
  init({ container, tool, autoScale = true, useShadowDom = true } = {}) {
    if (this._isInit) return

    this._isInit = true
    this._scale = 1

    this._initContainer(container, useShadowDom)
    this._initStyle()
    this._initDevTools()
    this._initEntryBtn()
    this._initSettings()
    this._initTools(tool)
    this._registerListener()

    if (autoScale) this._autoScale()
  },
  _isInit: false,
  version: VERSION,
  util,
  Tool,
  Console,
  Elements,
  Network,
  Sources,
  Resources,
  Info,
  Snippets,
  Settings,
  get(name) {
    if (!this._checkInit()) return

    if (name === 'entryBtn') return this._entryBtn

    const devTools = this._devTools

    return name ? devTools.get(name) : devTools
  },
  add(tool) {
    if (!this._checkInit()) return

    if (isFn(tool)) tool = tool(this)

    this._devTools.add(tool)

    return this
  },
  remove(name) {
    this._devTools.remove(name)

    return this
  },
  show(name) {
    if (!this._checkInit()) return

    const devTools = this._devTools

    name ? devTools.showTool(name) : devTools.show()

    return this
  },
  hide() {
    if (!this._checkInit()) return

    this._devTools.hide()

    return this
  },
  destroy() {
    this._devTools.destroy()
    delete this._devTools
    this._entryBtn.destroy()
    delete this._entryBtn
    this._unregisterListener()
    this._$el.remove()
    evalCss.clear()
    this._isInit = false
  },
  scale(s) {
    if (isNum(s)) {
      this._scale = s
      emitter.emit(emitter.SCALE, s)
      return this
    }

    return this._scale
  },
  position(p) {
    const entryBtn = this._entryBtn

    if (isObj(p)) {
      entryBtn.setPos(p)
      return this
    }

    return entryBtn.getPos()
  },
  _autoScale() {
    if (!isMobile()) return

    this.scale(1 / viewportScale())
  },
  _registerListener() {
    this._addListener = (...args) => this.add(...args)
    this._showListener = (...args) => this.show(...args)

    emitter.on(emitter.ADD, this._addListener)
    emitter.on(emitter.SHOW, this._showListener)
    emitter.on(emitter.SCALE, evalCss.setScale)
  },
  _unregisterListener() {
    emitter.off(emitter.ADD, this._addListener)
    emitter.off(emitter.SHOW, this._showListener)
    emitter.off(emitter.SCALE, evalCss.setScale)
  },
  _checkInit() {
    if (!this._isInit) logger.error('Please call "eruda.init()" first')
    return this._isInit
  },
  _initContainer(el, useShadowDom) {
    if (!el) {
      el = document.createElement('div')
      document.documentElement.appendChild(el)
    }

    let shadowRoot
    if (useShadowDom) {
      if (el.attachShadow) {
        shadowRoot = el.attachShadow({ mode: 'open' })
      } else if (el.createShadowRoot) {
        shadowRoot = el.createShadowRoot()
      }
      if (shadowRoot) {
        // font-face doesn't work inside shadow dom.
        evalCss.container = document.head
        evalCss(require('./style/icon.css'))

        el = document.createElement('div')
        shadowRoot.appendChild(el)
        this._shadowRoot = shadowRoot
      }
    }

    Object.assign(el, {
      id: 'eruda',
      className: 'eruda-container',
      contentEditable: false
    })

    // http://stackoverflow.com/questions/3885018/active-pseudo-class-doesnt-work-in-mobile-safari
    if (detectBrowser().name === 'ios') el.setAttribute('ontouchstart', '')

    this._$el = $(el)
  },
  _initDevTools() {
    this._devTools = new DevTools(this._$el)
  },
  _initStyle() {
    const className = 'eruda-style-container'
    const $el = this._$el

    if (this._shadowRoot) {
      evalCss.container = this._shadowRoot
      evalCss(':host { all: initial }')
    } else {
      $el.append(`<div class="${className}"></div>`)
      evalCss.container = $el.find(`.${className}`).get(0)
    }

    evalCss(
      require('./style/style.scss') +
        require('./style/reset.scss') +
        require('./style/icon.css')
    )
  },
  _initEntryBtn() {
    this._entryBtn = new EntryBtn(this._$el)
    this._entryBtn.on('click', () => this._devTools.toggle())
  },
  _initSettings() {
    const devTools = this._devTools
    const settings = new Settings()

    devTools.add(settings)

    this._entryBtn.initCfg(settings)
    devTools.initCfg(settings)
  },
  _initTools(
    tool = [
      'console',
      'elements',
      'network',
      'resources',
      'sources',
      'info',
      'snippets'
    ]
  ) {
    tool = toArr(tool).reverse()

    const devTools = this._devTools

    tool.forEach(name => {
      const Tool = this[upperFirst(name)]
      try {
        if (Tool) devTools.add(new Tool())
      } catch (e) {
        // Use nextTick to make sure it is possible to be caught by console panel.
        nextTick(() => {
          logger.error(
            `Something wrong when initializing tool ${name}:`,
            e.message
          )
        })
      }
    })

    devTools.showTool(last(tool) || 'settings')
  }
}

extraUtil(util)

//# sourceMappingURL=index.js.map
<commit_msg>fix: container style affected #119<commit_after>import EntryBtn from './EntryBtn/EntryBtn'
import DevTools from './DevTools/DevTools'
import Tool from './DevTools/Tool'
import Console from './Console/Console'
import Network from './Network/Network'
import Elements from './Elements/Elements'
import Snippets from './Snippets/Snippets'
import Resources from './Resources/Resources'
import Info from './Info/Info'
import Sources from './Sources/Sources'
import Settings from './Settings/Settings'
import emitter from './lib/emitter'
import logger from './lib/logger'
import extraUtil from './lib/extraUtil'
import util from './lib/util'
import {
  isFn,
  evalCss,
  isNum,
  isObj,
  isMobile,
  viewportScale,
  detectBrowser,
  $,
  toArr,
  upperFirst,
  nextTick,
  last
} from './lib/util'

module.exports = {
  init({ container, tool, autoScale = true, useShadowDom = true } = {}) {
    if (this._isInit) return

    this._isInit = true
    this._scale = 1

    this._initContainer(container, useShadowDom)
    this._initStyle()
    this._initDevTools()
    this._initEntryBtn()
    this._initSettings()
    this._initTools(tool)
    this._registerListener()

    if (autoScale) this._autoScale()
  },
  _isInit: false,
  version: VERSION,
  util,
  Tool,
  Console,
  Elements,
  Network,
  Sources,
  Resources,
  Info,
  Snippets,
  Settings,
  get(name) {
    if (!this._checkInit()) return

    if (name === 'entryBtn') return this._entryBtn

    const devTools = this._devTools

    return name ? devTools.get(name) : devTools
  },
  add(tool) {
    if (!this._checkInit()) return

    if (isFn(tool)) tool = tool(this)

    this._devTools.add(tool)

    return this
  },
  remove(name) {
    this._devTools.remove(name)

    return this
  },
  show(name) {
    if (!this._checkInit()) return

    const devTools = this._devTools

    name ? devTools.showTool(name) : devTools.show()

    return this
  },
  hide() {
    if (!this._checkInit()) return

    this._devTools.hide()

    return this
  },
  destroy() {
    this._devTools.destroy()
    delete this._devTools
    this._entryBtn.destroy()
    delete this._entryBtn
    this._unregisterListener()
    this._$el.remove()
    evalCss.clear()
    this._isInit = false
  },
  scale(s) {
    if (isNum(s)) {
      this._scale = s
      emitter.emit(emitter.SCALE, s)
      return this
    }

    return this._scale
  },
  position(p) {
    const entryBtn = this._entryBtn

    if (isObj(p)) {
      entryBtn.setPos(p)
      return this
    }

    return entryBtn.getPos()
  },
  _autoScale() {
    if (!isMobile()) return

    this.scale(1 / viewportScale())
  },
  _registerListener() {
    this._addListener = (...args) => this.add(...args)
    this._showListener = (...args) => this.show(...args)

    emitter.on(emitter.ADD, this._addListener)
    emitter.on(emitter.SHOW, this._showListener)
    emitter.on(emitter.SCALE, evalCss.setScale)
  },
  _unregisterListener() {
    emitter.off(emitter.ADD, this._addListener)
    emitter.off(emitter.SHOW, this._showListener)
    emitter.off(emitter.SCALE, evalCss.setScale)
  },
  _checkInit() {
    if (!this._isInit) logger.error('Please call "eruda.init()" first')
    return this._isInit
  },
  _initContainer(el, useShadowDom) {
    if (!el) {
      el = document.createElement('div')
      document.documentElement.appendChild(el)
      el.style.all = 'initial'
    }

    let shadowRoot
    if (useShadowDom) {
      if (el.attachShadow) {
        shadowRoot = el.attachShadow({ mode: 'open' })
      } else if (el.createShadowRoot) {
        shadowRoot = el.createShadowRoot()
      }
      if (shadowRoot) {
        // font-face doesn't work inside shadow dom.
        evalCss.container = document.head
        evalCss(require('./style/icon.css'))

        el = document.createElement('div')
        shadowRoot.appendChild(el)
        this._shadowRoot = shadowRoot
      }
    }

    Object.assign(el, {
      id: 'eruda',
      className: 'eruda-container',
      contentEditable: false
    })

    // http://stackoverflow.com/questions/3885018/active-pseudo-class-doesnt-work-in-mobile-safari
    if (detectBrowser().name === 'ios') el.setAttribute('ontouchstart', '')

    this._$el = $(el)
  },
  _initDevTools() {
    this._devTools = new DevTools(this._$el)
  },
  _initStyle() {
    const className = 'eruda-style-container'
    const $el = this._$el

    if (this._shadowRoot) {
      evalCss.container = this._shadowRoot
      evalCss(':host { all: initial }')
    } else {
      $el.append(`<div class="${className}"></div>`)
      evalCss.container = $el.find(`.${className}`).get(0)
    }

    evalCss(
      require('./style/style.scss') +
        require('./style/reset.scss') +
        require('./style/icon.css')
    )
  },
  _initEntryBtn() {
    this._entryBtn = new EntryBtn(this._$el)
    this._entryBtn.on('click', () => this._devTools.toggle())
  },
  _initSettings() {
    const devTools = this._devTools
    const settings = new Settings()

    devTools.add(settings)

    this._entryBtn.initCfg(settings)
    devTools.initCfg(settings)
  },
  _initTools(
    tool = [
      'console',
      'elements',
      'network',
      'resources',
      'sources',
      'info',
      'snippets'
    ]
  ) {
    tool = toArr(tool).reverse()

    const devTools = this._devTools

    tool.forEach(name => {
      const Tool = this[upperFirst(name)]
      try {
        if (Tool) devTools.add(new Tool())
      } catch (e) {
        // Use nextTick to make sure it is possible to be caught by console panel.
        nextTick(() => {
          logger.error(
            `Something wrong when initializing tool ${name}:`,
            e.message
          )
        })
      }
    })

    devTools.showTool(last(tool) || 'settings')
  }
}

extraUtil(util)

//# sourceMappingURL=index.js.map
<|endoftext|>


<commit_before>var fs = require('fs');
var express = require('express');
var app = express();

var Canvas = require('canvas');
var Image = Canvas.Image;

fs.readFile(__dirname + '/images/bg.jpg', function(err, data){
    if (err) throw err;

    // データをcanvasのcontextに設定
    var img = new Image;
    img.src = data;
    var canvas = new Canvas(img.width, img.height);
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, img.width, img.height);

    var text = 'Hello World!!';
    var textMeasure = ctx.measureText(text);

    ctx.font = '30px Impact';
    ctx.textAlign = 'center';

	ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
	ctx.fillText(text, textMeasure.width / 2, 100);

    app.set('port', (process.env.PORT || 5000));
	app.use(express.static(__dirname + '/public'));

	app.get('/', function(request, response) {
	    response.send('');
	});

	app.listen(app.get('port'), function() {
	  console.log("Node app is running at localhost:" + app.get('port'));
	});
});<commit_msg>set text align test<commit_after>var fs = require('fs');
var express = require('express');
var app = express();

var Canvas = require('canvas');
var Image = Canvas.Image;

fs.readFile(__dirname + '/images/bg.jpg', function(err, data){
    if (err) throw err;

    // データをcanvasのcontextに設定
    var img = new Image;
    img.src = data;
    var canvas = new Canvas(img.width, img.height);
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, img.width, img.height);

    var text = 'Hello World!!';
    var textMeasure = ctx.measureText(text);

    ctx.font = '30px Impact';
    ctx.textAlign = 'center';

	ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
	ctx.fillText(text, canvas.width / 2 - textMeasure.width / 2, 100);

    app.set('port', (process.env.PORT || 5000));
	app.use(express.static(__dirname + '/public'));

	app.get('/', function(request, response) {
	    response.send('');
	});

	app.listen(app.get('port'), function() {
	  console.log("Node app is running at localhost:" + app.get('port'));
	});
});<|endoftext|>


<commit_before>/**
 * react-lazyload
 */
import React, { Component, PropTypes } from 'react';
import ReactDom from 'react-dom';
import { on, off } from './utils/event';
import scrollParent from './utils/scrollParent';
import debounce from './utils/debounce';
import throttle from './utils/throttle';

const LISTEN_FLAG = 'data-lazyload-listened';
const listeners = [];
let pending = [];

/**
 * Check if `component` is visible in overflow container `parent`
 * @param  {node} component React component
 * @param  {node} parent    component's scroll parent
 * @return {bool}
 */
const checkOverflowVisible = function checkOverflowVisible(component, parent) {
  const node = ReactDom.findDOMNode(component);

  const scrollTop = parent.scrollTop;
  const parentBottom = scrollTop + parent.offsetHeight;
  const { height: elementHeight } = node.getBoundingClientRect();

  const offsets = Array.isArray(component.props.offset) ?
                component.props.offset :
                [component.props.offset, component.props.offset]; // Be compatible with previous API

  const elementTop = node.offsetTop;
  const elementBottom = elementTop + elementHeight;

  return (elementTop - offsets[0] <= parentBottom) &&
         (elementBottom + offsets[1] >= scrollTop);
};

/**
 * Check if `component` is visible in document
 * @param  {node} component React component
 * @return {bool}
 */
const checkNormalVisible = function checkNormalVisible(component) {
  const node = ReactDom.findDOMNode(component);

  const supportPageOffset = window.pageXOffset !== undefined;
  const isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat');
  const scrollTop = supportPageOffset ? window.pageYOffset :
                                        isCSS1Compat ?
                                        document.documentElement.scrollTop :
                                        document.body.scrollTop;

  const { top, height: elementHeight } = node.getBoundingClientRect();
  const elementTop = top + scrollTop; // element top relative to document
  const elementBottom = elementTop + elementHeight;

  const windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
  const documentBottom = scrollTop + windowInnerHeight;

  const offsets = Array.isArray(component.props.offset) ?
                component.props.offset :
                [component.props.offset, component.props.offset]; // Be compatible with previous API

  return (elementTop - offsets[0] <= documentBottom) &&
         (elementBottom + offsets[1] >= scrollTop);
};

/**
 * Detect if element is visible in viewport, if so, set `visible` state to true.
 * If `once` prop is provided true, remove component as listener after checkVisible
 *
 * @param  {React} component   React component that respond to scroll and resize
 */
const checkVisible = function checkVisible(component) {
  const node = ReactDom.findDOMNode(component);
  if (!node) {
    return;
  }

  const parent = scrollParent(node);
  const isOverflow = parent !== (node.ownerDocument || document);

  const visible = isOverflow ?
                  checkOverflowVisible(component, parent) :
                  checkNormalVisible(component);

  if (visible) {
    // Avoid extra render if previously is visible, yeah I mean `render` call,
    // not actual DOM render
    if (!component.visible) {
      if (component.props.once) {
        pending.push(component);
      }

      component.visible = true;
      component.forceUpdate();
    }
  } else {
    component.visible = false;
  }
};

const purgePending = function purgePending() {
  pending.forEach(component => {
    const index = listeners.indexOf(component);
    if (index !== -1) {
      listeners.splice(index, 1);
    }
  });

  pending = [];
};

const lazyLoadHandler = () => {
  for (let i = 0; i < listeners.length; ++i) {
    const listener = listeners[i];
    checkVisible(listener);
  }

  // Remove `once` component in listeners
  purgePending();
};

// Depending on component's props
let finalLazyLoadHandler = null;

class LazyLoad extends Component {
  constructor(props) {
    super(props);

    this.visible = false;

    if (React.Children.count(this.props.children) > 1) {
      console.warn('[react-lazyload] Only one child is allowed to be passed to `LazyLoad`.');
    }

    if (typeof this.props.height !== 'number') {
      console.warn('[react-lazyload] Please add `height` props to <LazyLoad> for better performance.');
    }

    if (this.props.wheel) { // eslint-disable-line
      console.warn('[react-lazyload] Props `wheel` is not supported anymore, try set `overflow` for lazy loading in overflow containers.');
    }
  }

  componentDidMount() {
    if (!finalLazyLoadHandler) {
      if (this.props.debounce !== undefined) {
        finalLazyLoadHandler = debounce(lazyLoadHandler, typeof this.props.throttle === 'number' ?
                                                         this.props.throttle :
                                                         300);
      } else {
        finalLazyLoadHandler = throttle(lazyLoadHandler, typeof this.props.debounce === 'number' ?
                                                         this.props.debounce :
                                                         300);
      }
    }

    if (this.props.overflow) {
      const parent = scrollParent(ReactDom.findDOMNode(this));
      if (parent && parent.getAttribute(LISTEN_FLAG) === null) {
        parent.addEventListener('scroll', finalLazyLoadHandler);
        parent.setAttribute(LISTEN_FLAG, 1);
      }
    } else if (listeners.length === 0) {
      const { scroll, resize } = this.props;

      if (scroll) {
        on(window, 'scroll', finalLazyLoadHandler);
      }

      if (resize) {
        on(window, 'resize', finalLazyLoadHandler);
      }
    }

    listeners.push(this);
    checkVisible(this);
  }

  shouldComponentUpdate() {
    return this.visible;
  }

  componentWillUnmount() {
    if (this.props.overflow) {
      const parent = scrollParent(ReactDom.findDOMNode(this));
      if (parent) {
        parent.removeEventListener('scroll', finalLazyLoadHandler);
        parent.removeAttribute(LISTEN_FLAG);
      }
    }

    const index = listeners.indexOf(this);
    if (index !== -1) {
      listeners.splice(index, 1);
    }

    if (listeners.length === 0) {
      off(window, 'resize', finalLazyLoadHandler);
      off(window, 'scroll', finalLazyLoadHandler);
    }
  }

  render() {
    return this.visible ?
           this.props.children :

;
  }
}

LazyLoad.propTypes = {
  once: PropTypes.bool,
  height: PropTypes.number.isRequired,
  offset: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),
  overflow: PropTypes.bool,
  resize: PropTypes.bool,
  scroll: PropTypes.bool,
  children: PropTypes.node,
  throttle: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
  debounce: PropTypes.oneOfType([PropTypes.number, PropTypes.bool])
};

LazyLoad.defaultProps = {
  once: false,
  height: 100,
  offset: 0,
  overflow: false,
  resize: false,
  scroll: true
};

export default LazyLoad;

export lazyload from './decorator';
<commit_msg>fix: add handy delay type change warning<commit_after>/**
 * react-lazyload
 */
import React, { Component, PropTypes } from 'react';
import ReactDom from 'react-dom';
import { on, off } from './utils/event';
import scrollParent from './utils/scrollParent';
import debounce from './utils/debounce';
import throttle from './utils/throttle';

const LISTEN_FLAG = 'data-lazyload-listened';
const listeners = [];
let pending = [];

/**
 * Check if `component` is visible in overflow container `parent`
 * @param  {node} component React component
 * @param  {node} parent    component's scroll parent
 * @return {bool}
 */
const checkOverflowVisible = function checkOverflowVisible(component, parent) {
  const node = ReactDom.findDOMNode(component);

  const scrollTop = parent.scrollTop;
  const parentBottom = scrollTop + parent.offsetHeight;
  const { height: elementHeight } = node.getBoundingClientRect();

  const offsets = Array.isArray(component.props.offset) ?
                component.props.offset :
                [component.props.offset, component.props.offset]; // Be compatible with previous API

  const elementTop = node.offsetTop;
  const elementBottom = elementTop + elementHeight;

  return (elementTop - offsets[0] <= parentBottom) &&
         (elementBottom + offsets[1] >= scrollTop);
};

/**
 * Check if `component` is visible in document
 * @param  {node} component React component
 * @return {bool}
 */
const checkNormalVisible = function checkNormalVisible(component) {
  const node = ReactDom.findDOMNode(component);

  const supportPageOffset = window.pageXOffset !== undefined;
  const isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat');
  const scrollTop = supportPageOffset ? window.pageYOffset :
                                        isCSS1Compat ?
                                        document.documentElement.scrollTop :
                                        document.body.scrollTop;

  const { top, height: elementHeight } = node.getBoundingClientRect();
  const elementTop = top + scrollTop; // element top relative to document
  const elementBottom = elementTop + elementHeight;

  const windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
  const documentBottom = scrollTop + windowInnerHeight;

  const offsets = Array.isArray(component.props.offset) ?
                component.props.offset :
                [component.props.offset, component.props.offset]; // Be compatible with previous API

  return (elementTop - offsets[0] <= documentBottom) &&
         (elementBottom + offsets[1] >= scrollTop);
};

/**
 * Detect if element is visible in viewport, if so, set `visible` state to true.
 * If `once` prop is provided true, remove component as listener after checkVisible
 *
 * @param  {React} component   React component that respond to scroll and resize
 */
const checkVisible = function checkVisible(component) {
  const node = ReactDom.findDOMNode(component);
  if (!node) {
    return;
  }

  const parent = scrollParent(node);
  const isOverflow = parent !== (node.ownerDocument || document);

  const visible = isOverflow ?
                  checkOverflowVisible(component, parent) :
                  checkNormalVisible(component);

  if (visible) {
    // Avoid extra render if previously is visible, yeah I mean `render` call,
    // not actual DOM render
    if (!component.visible) {
      if (component.props.once) {
        pending.push(component);
      }

      component.visible = true;
      component.forceUpdate();
    }
  } else if (!(component.props.once && component.visible)) {
    component.visible = false;
  }
};

const purgePending = function purgePending() {
  pending.forEach(component => {
    const index = listeners.indexOf(component);
    if (index !== -1) {
      listeners.splice(index, 1);
    }
  });

  pending = [];
};

const lazyLoadHandler = () => {
  for (let i = 0; i < listeners.length; ++i) {
    const listener = listeners[i];
    checkVisible(listener);
  }

  // Remove `once` component in listeners
  purgePending();
};

// Depending on component's props
let delayType;
let finalLazyLoadHandler = null;

class LazyLoad extends Component {
  constructor(props) {
    super(props);

    this.visible = false;

    if (React.Children.count(this.props.children) > 1) {
      console.warn('[react-lazyload] Only one child is allowed to be passed to `LazyLoad`.');
    }

    if (typeof this.props.height !== 'number') {
      console.warn('[react-lazyload] Please add `height` props to <LazyLoad> for better performance.');
    }

    if (this.props.wheel) { // eslint-disable-line
      console.warn('[react-lazyload] Props `wheel` is not supported anymore, try set `overflow` for lazy loading in overflow containers.');
    }
  }

  componentDidMount() {
    // It's unlikely to change delay type for an application, this is mainly
    // designed for tests
    let needResetFinalLazyLoadHandler = false;
    if (this.props.debounce !== undefined && delayType === 'throttle') {
      console.warn('[react-lazyload] Previous delay function is `throttle`, now switching to `debounce`, try set them unanimously');
      needResetFinalLazyLoadHandler = true;
    } else if (delayType === 'debounce' && this.props.debounce === undefined) {
      console.warn('[react-lazyload] Previous delay function is `debounce`, now switching to `throttle`, try set them unanimously');
      needResetFinalLazyLoadHandler = true;
    }

    if (needResetFinalLazyLoadHandler) {
      off(window, 'scroll', finalLazyLoadHandler);
      off(window, 'resize', finalLazyLoadHandler);
      finalLazyLoadHandler = null;
    }

    if (!finalLazyLoadHandler) {
      if (this.props.debounce !== undefined) {
        finalLazyLoadHandler = debounce(lazyLoadHandler, typeof this.props.throttle === 'number' ?
                                                         this.props.throttle :
                                                         300);
        delayType = 'debounce';
      } else {
        finalLazyLoadHandler = throttle(lazyLoadHandler, typeof this.props.debounce === 'number' ?
                                                         this.props.debounce :
                                                         300);
        delayType = 'throttle';
      }
    }

    if (this.props.overflow) {
      const parent = scrollParent(ReactDom.findDOMNode(this));
      if (parent && parent.getAttribute(LISTEN_FLAG) === null) {
        parent.addEventListener('scroll', finalLazyLoadHandler);
        parent.setAttribute(LISTEN_FLAG, 1);
      }
    } else if (listeners.length === 0 || needResetFinalLazyLoadHandler) {
      const { scroll, resize } = this.props;

      if (scroll) {
        on(window, 'scroll', finalLazyLoadHandler);
      }

      if (resize) {
        on(window, 'resize', finalLazyLoadHandler);
      }
    }

    listeners.push(this);
    checkVisible(this);
  }

  shouldComponentUpdate() {
    return this.visible;
  }

  componentWillUnmount() {
    if (this.props.overflow) {
      const parent = scrollParent(ReactDom.findDOMNode(this));
      if (parent) {
        parent.removeEventListener('scroll', finalLazyLoadHandler);
        parent.removeAttribute(LISTEN_FLAG);
      }
    }

    const index = listeners.indexOf(this);
    if (index !== -1) {
      listeners.splice(index, 1);
    }

    if (listeners.length === 0) {
      off(window, 'resize', finalLazyLoadHandler);
      off(window, 'scroll', finalLazyLoadHandler);
    }
  }

  render() {
    return this.visible ?
           this.props.children :

;
  }
}

LazyLoad.propTypes = {
  once: PropTypes.bool,
  height: PropTypes.number.isRequired,
  offset: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),
  overflow: PropTypes.bool,
  resize: PropTypes.bool,
  scroll: PropTypes.bool,
  children: PropTypes.node,
  throttle: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
  debounce: PropTypes.oneOfType([PropTypes.number, PropTypes.bool])
};

LazyLoad.defaultProps = {
  once: false,
  height: 100,
  offset: 0,
  overflow: false,
  resize: false,
  scroll: true
};

export default LazyLoad;

export lazyload from './decorator';
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import { join } from 'path-extra'
import { Provider } from 'react-redux'

import 'rc-slider/assets/index.css'
import 'font-awesome/css/font-awesome.css'
import './assets/index.css'

import { KanceptsMain } from './ui'
import { register } from './registerServiceWorker'

import { store } from './store'

/*

   TODO

   - planner

     - tooltip on expeditions

   - table

     - impl numeric view: the idea is to force general cost view
     - tooltips

   - ship list

     - sorting
     - find a way to allow list modification

   - settings (TODO)

     - i18n
     - autoconfig table
     - data import / export

 */

ReactDOM.render(
  (

      <link
        rel="stylesheet"
        href={join(__dirname,'..','assets','index.css')}
      />
      <Provider store={store}>
        <KanceptsMain />
      </Provider>

  ),
  document.getElementById('root'))
register()
<commit_msg>table batch plan & remove duplicated css import<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'

import 'rc-slider/assets/index.css'
import 'font-awesome/css/font-awesome.css'
import './assets/index.css'

import { KanceptsMain } from './ui'
import { register } from './registerServiceWorker'

import { store } from './store'

/*

   TODO

   - planner

     - tooltip on expeditions

   - table

     - impl numeric view: the idea is to force general cost view
     - hourly view for items
     - hide gs item for non-great success?
     - tooltips

   - ship list

     - sorting
     - find a way to allow list modification

   - settings (TODO)

     - i18n
     - autoconfig table
     - data import / export
     - table batch:

       - reset all
       - apply great success for
           - expeditions that

               - longer than ? mins
               - resource sum >= ?

           - dlc: require 0(*)/1/2/3/4
           - fleet count: 6(*)/5/4

 */

ReactDOM.render(
  (

      <Provider store={store}>
        <KanceptsMain />
      </Provider>

  ),
  document.getElementById('root'))
register()
<|endoftext|>


<commit_before>// @flow
import * as React from 'react'
import { useEffect, useState } from 'react'
import defaultFormatter from './defaultFormatter'
import dateParser from './dateParser'

const { Component } = React

export type Unit =
  | 'second'
  | 'minute'
  | 'hour'
  | 'day'
  | 'week'
  | 'month'
  | 'year'
export type Suffix = 'ago' | 'from now'
export type Formatter = (
  value: number,
  unit: Unit,
  suffix: Suffix,
  epochMiliseconds: number,
  nextFormatter: () => React.Node,
  now: () => number,
) => React.Node

export type Props = $ReadOnly<{
  /** If the component should update itself over time */
  live?: boolean,
  /** minimum amount of time in seconds between re-renders */
  minPeriod?: number,
  /** Maximum time between re-renders in seconds. The component should update at least once every `x` seconds */
  maxPeriod?: number,
  /** The container to render the string into. You could use a string like `span` or a custom component */
  component?: string | React.ComponentType<mixed>,
  /**
   * A title used for setting the title attribute if a <time> HTML Element is used.
   */
  title?: string,
  /** A function to decide how to format the date.
   * If you use this, react-timeago is basically acting like a glorified setInterval for you.
   */
  formatter?: Formatter,
  /** The Date to display. An actual Date object or something that can be fed to new Date */
  date: string | number | Date,
  /** A function that returns what Date.now would return. Primarily for server
   * date: string | number | Date		 +   * rendering.
   */
  now?: () => number,
  ...
}>;

// Just some simple constants for readability
const MINUTE = 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const WEEK = DAY * 7
const MONTH = DAY * 30
const YEAR = DAY * 365

export default function TimeAgo({
  date,
  formatter = defaultFormatter,
  component = 'time',
  live = true,
  minPeriod = 0,
  maxPeriod = Infinity,
  title,
  now = () => Date.now(),
  ...passDownProps
}: Props) {
  const [_, setCount] = useState(0);
  useEffect(() => {
    if (!live) {
      return undefined;
    }
    let timeoutId;
    const tick = (refresh: ?boolean): void => {
      const then = dateParser(date).valueOf()
      if (!then) {
        console.warn('[react-timeago] Invalid Date provided')
        return
      }
      const timeNow = now()
      const seconds = Math.round(Math.abs(timeNow - then) / 1000)

      const unboundPeriod =
        seconds < MINUTE
        ? 1000
        : seconds < HOUR
          ? 1000 * MINUTE
          : seconds < DAY
            ? 1000 * HOUR
            : Infinity

      const period = Math.min(
        Math.max(unboundPeriod, minPeriod * 1000),
        maxPeriod * 1000,
      )

      if (period) {
        if (timeoutId) {
        clearTimeout(timeoutId)
        }
        timeoutId = setTimeout(tick, period)
      }
      if (!refresh) {
        setCount(c => c + 1)
      }
    }
    tick(true);
    return () => {
      clearTimeout(timeoutId)
    }
  }, [date])

  const Komponent = component
  const then = dateParser(date).valueOf()
  if (!then) {
    return null
  }

  const timeNow = now()
  const seconds = Math.round(Math.abs(timeNow - then) / 1000)
  const suffix = then < timeNow ? 'ago' : 'from now'

  const [value, unit] =
    seconds < MINUTE
      ? [Math.round(seconds), 'second']
      : seconds < HOUR
      ? [Math.round(seconds / MINUTE), 'minute']
      : seconds < DAY
      ? [Math.round(seconds / HOUR), 'hour']
      : seconds < WEEK
      ? [Math.round(seconds / DAY), 'day']
      : seconds < MONTH
      ? [Math.round(seconds / WEEK), 'week']
      : seconds < YEAR
      ? [Math.round(seconds / MONTH), 'month']
      : [Math.round(seconds / YEAR), 'year']

  const passDownTitle =
    typeof title === 'undefined'
      ? typeof date === 'string'
        ? date
        : dateParser(date).toISOString().substr(0, 16).replace('T', ' ')
      : title

  const spreadProps =
    Komponent === 'time'
      ? {...passDownProps, dateTime: dateParser(date).toISOString()}
      : passDownProps

  const nextFormatter = defaultFormatter.bind(null, value, unit, suffix)

  return (
    <Komponent {...spreadProps} title={passDownTitle}>
      {formatter(value, unit, suffix, then, nextFormatter, now)}
    </Komponent>
  )
}
<commit_msg>reformat<commit_after>// @flow

import * as React from 'react'
import { useEffect, useState } from 'react'
import defaultFormatter from './defaultFormatter'
import dateParser from './dateParser'

export type Unit =
  | 'second'
  | 'minute'
  | 'hour'
  | 'day'
  | 'week'
  | 'month'
  | 'year'
export type Suffix = 'ago' | 'from now'
export type Formatter = (
  value: number,
  unit: Unit,
  suffix: Suffix,
  epochMiliseconds: number,
  nextFormatter: () => React.Node,
  now: () => number,
) => React.Node

export type Props = $ReadOnly<{
  /** If the component should update itself over time */
  live?: boolean,
  /** minimum amount of time in seconds between re-renders */
  minPeriod?: number,
  /** Maximum time between re-renders in seconds. The component should update at least once every `x` seconds */
  maxPeriod?: number,
  /** The container to render the string into. You could use a string like `span` or a custom component */
  component?: string | React.ComponentType<mixed>,
  /**
   * A title used for setting the title attribute if a <time> HTML Element is used.
   */
  title?: string,
  /** A function to decide how to format the date.
   * If you use this, react-timeago is basically acting like a glorified setInterval for you.
   */
  formatter?: Formatter,
  /** The Date to display. An actual Date object or something that can be fed to new Date */
  date: string | number | Date,
  /** A function that returns what Date.now would return. Primarily for server
   * date: string | number | Date		 +   * rendering.
   */
  now?: () => number,
  ...
}>

// Just some simple constants for readability
const MINUTE = 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const WEEK = DAY * 7
const MONTH = DAY * 30
const YEAR = DAY * 365

export default function TimeAgo({
  date,
  formatter = defaultFormatter,
  component = 'time',
  live = true,
  minPeriod = 0,
  maxPeriod = Infinity,
  title,
  now = () => Date.now(),
  ...passDownProps
}: Props): null | React.MixedElement {
  const [_, setCount] = useState(0)
  useEffect(() => {
    if (!live) {
      return undefined
    }
    let timeoutId
    const tick = (refresh: ?boolean): void => {
      const then = dateParser(date).valueOf()
      if (!then) {
        console.warn('[react-timeago] Invalid Date provided')
        return
      }
      const timeNow = now()
      const seconds = Math.round(Math.abs(timeNow - then) / 1000)

      const unboundPeriod =
        seconds < MINUTE
          ? 1000
          : seconds < HOUR
          ? 1000 * MINUTE
          : seconds < DAY
          ? 1000 * HOUR
          : Infinity

      const period = Math.min(
        Math.max(unboundPeriod, minPeriod * 1000),
        maxPeriod * 1000,
      )

      if (period) {
        if (timeoutId) {
          clearTimeout(timeoutId)
        }
        timeoutId = setTimeout(tick, period)
      }
      if (!refresh) {
        setCount((c) => c + 1)
      }
    }
    tick(true)
    return () => {
      clearTimeout(timeoutId)
    }
  }, [date])

  const Komponent = component
  const then = dateParser(date).valueOf()
  if (!then) {
    return null
  }

  const timeNow = now()
  const seconds = Math.round(Math.abs(timeNow - then) / 1000)
  const suffix = then < timeNow ? 'ago' : 'from now'

  const [value, unit] =
    seconds < MINUTE
      ? [Math.round(seconds), 'second']
      : seconds < HOUR
      ? [Math.round(seconds / MINUTE), 'minute']
      : seconds < DAY
      ? [Math.round(seconds / HOUR), 'hour']
      : seconds < WEEK
      ? [Math.round(seconds / DAY), 'day']
      : seconds < MONTH
      ? [Math.round(seconds / WEEK), 'week']
      : seconds < YEAR
      ? [Math.round(seconds / MONTH), 'month']
      : [Math.round(seconds / YEAR), 'year']

  const passDownTitle =
    typeof title === 'undefined'
      ? typeof date === 'string'
        ? date
        : dateParser(date).toISOString().substr(0, 16).replace('T', ' ')
      : title

  const spreadProps =
    Komponent === 'time'
      ? { ...passDownProps, dateTime: dateParser(date).toISOString() }
      : passDownProps

  const nextFormatter = defaultFormatter.bind(null, value, unit, suffix)

  return (
    <Komponent {...spreadProps} title={passDownTitle}>
      {formatter(value, unit, suffix, then, nextFormatter, now)}
    </Komponent>
  )
}
<|endoftext|>


<commit_before>
const createModule = require("./container")

module.exports = createModule()
<commit_msg>Export lifetimes from module API<commit_after>
const createModule = require("./container")

module.exports = createModule()
module.exports.lifetimes = require("./lifetimes")
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

module.exports = (options) => {

    options = options || {};

    const rootPath = options.rootPath || path.resolve('../src');
    const folderContains = options.folderContains || '__tests__';
    const fileContains = options.fileContains || '.spec.js';

    const isDirectory = (name) => {
        return !~name.indexOf('.');
    };

    const searchForTests = (dir) => {

        const items = fs.readdirSync(dir);

        items.forEach((item) => {

            const directory = `${dir}/${item}`;

            if (~item.indexOf(folderContains)) {

                fs.readdirSync(directory).forEach((test) => {
                    if (~test.indexOf(fileContains)) {
                        require(`${directory}/${test}`);
                    }
                });

            } else if (isDirectory(item)) {

                searchForTests(directory);

            }
        });
    }

    searchForTests(rootPath);

};
<commit_msg>Updating the default rootPath<commit_after>const fs = require('fs');
const path = require('path');

module.exports = (options) => {

    options = options || {};

    const rootPath = options.rootPath || path.resolve('./src');
    const folderContains = options.folderContains || '__tests__';
    const fileContains = options.fileContains || '.spec.js';

    const isDirectory = (name) => {
        return !~name.indexOf('.');
    };

    const searchForTests = (dir) => {

        const items = fs.readdirSync(dir);

        items.forEach((item) => {

            const directory = `${dir}/${item}`;

            if (~item.indexOf(folderContains)) {

                fs.readdirSync(directory).forEach((test) => {
                    if (~test.indexOf(fileContains)) {
                        require(`${directory}/${test}`);
                    }
                });

            } else if (isDirectory(item)) {

                searchForTests(directory);

            }
        });
    }

    searchForTests(rootPath);

};
<|endoftext|>


<commit_before>// Defaults
const defaultOptions = {
	format: 'image/png',
	quality: 0.92,
	width: undefined,
	height: undefined
};

// Return Promise
const mergeImages = (sources = [], options = {}) => new Promise((resolve, reject) => {
	options = Object.assign({}, defaultOptions, options);

	// Setup browser/node specific variables
	const canvas = options.Canvas ? new options.Canvas() : window.document.createElement('canvas');
	const Image = options.Canvas ? options.Canvas.Image : window.Image;
	if (options.Canvas) {
		options.quality *= 100;
	}

	// Load sources
	const images = sources.map(source => new Promise(resolve => {
		// Convert strings to objects
		if (source.constructor.name !== 'Object') {
			source = { src: source };
		}

		// Resolve source and img when loaded
		const img = new Image();
		img.onerror = () => reject(new Error('Couldn\'t load image'));
		img.onload = () => resolve(Object.assign({}, source, { img }));
		img.src = source.src;
	}));

	// Get canvas context
	const ctx = canvas.getContext('2d');

	// When sources have loaded
	resolve(Promise.all(images)
		.then(images => {
			// Set canvas dimensions
			const getSize = dim => options[dim] || Math.max(...images.map(image => image.img[dim]));
			canvas.width = getSize('width');
			canvas.height = getSize('height');

			// Draw images to canvas
			images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0));

			if (options.Canvas && options.format === 'image/jpeg') {
				// Resolve data URI for node-canvas jpeg async
				return new Promise(resolve => {
					canvas.toDataURL(options.format, {
						quality: options.quality,
						progressive: false
					}, (err, jpeg) => {
						if (err) {
							throw err;
						}
						resolve(jpeg);
					});
				});
			}

			// Resolve all other data URIs sync
			return canvas.toDataURL(options.format, options.quality);
		}));
});

module.exports = mergeImages;
<commit_msg>Reject map Promise not main Promise<commit_after>// Defaults
const defaultOptions = {
	format: 'image/png',
	quality: 0.92,
	width: undefined,
	height: undefined
};

// Return Promise
const mergeImages = (sources = [], options = {}) => new Promise(resolve => {
	options = Object.assign({}, defaultOptions, options);

	// Setup browser/node specific variables
	const canvas = options.Canvas ? new options.Canvas() : window.document.createElement('canvas');
	const Image = options.Canvas ? options.Canvas.Image : window.Image;
	if (options.Canvas) {
		options.quality *= 100;
	}

	// Load sources
	const images = sources.map(source => new Promise((resolve, reject) => {
		// Convert strings to objects
		if (source.constructor.name !== 'Object') {
			source = { src: source };
		}

		// Resolve source and img when loaded
		const img = new Image();
		img.onerror = () => reject(new Error('Couldn\'t load image'));
		img.onload = () => resolve(Object.assign({}, source, { img }));
		img.src = source.src;
	}));

	// Get canvas context
	const ctx = canvas.getContext('2d');

	// When sources have loaded
	resolve(Promise.all(images)
		.then(images => {
			// Set canvas dimensions
			const getSize = dim => options[dim] || Math.max(...images.map(image => image.img[dim]));
			canvas.width = getSize('width');
			canvas.height = getSize('height');

			// Draw images to canvas
			images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0));

			if (options.Canvas && options.format === 'image/jpeg') {
				// Resolve data URI for node-canvas jpeg async
				return new Promise(resolve => {
					canvas.toDataURL(options.format, {
						quality: options.quality,
						progressive: false
					}, (err, jpeg) => {
						if (err) {
							throw err;
						}
						resolve(jpeg);
					});
				});
			}

			// Resolve all other data URIs sync
			return canvas.toDataURL(options.format, options.quality);
		}));
});

module.exports = mergeImages;
<|endoftext|>


<commit_before>'use strict';

const _ = require('underscore');
const compare = require('json-structure-diff').compareJSONObjects;

const structureJsonRaw = require('./keyfiles-structure.json');
const structureJson = toLower(structureJsonRaw);

/**
 * Deep copies JSON object with keys.toLowerCase()
 * @param  {Object} obj input
 * @return {Object}     output
 */
function toLower(obj) {
    var newObj = {};
    _.keys(obj).forEach((key) => {
        if (typeof(newObj[key.toLowerCase()] = obj[key]) === 'object')
            newObj[key] = toLower(newObj[key])
    });
    return newObj
}

/**
 * Matches the input object's structure against valid keyfile structures
 * (respects key and value-type)
 * @param  {Object} obj input keyfile object
 * @return {[String, Number]} array of type (web3|ethersale) and version
 */
module.exports = function(obj) {
    var result = null;
    try {
        _.keys(structureJson).forEach((structureType) => {
            var structure = {
                parent: structureType,
                content: structureJson[structureType]['json']
            }
            var instance = {
                parent: 'obj',
                content: toLower(obj)
            }
            var error = compare([structure, instance]);
            if (!error) {
                var match = structureJson[structure.parent];
                result = [ match.type, match.json.version ];
                throw BreakException;
            }
        });
    } catch (e) {
        // break out of loop; keyfile already validated
    }
    return (result) ? result : null
}
<commit_msg>improve return<commit_after>'use strict';

const _ = require('underscore');
const compare = require('json-structure-diff').compareJSONObjects;

const structureJsonRaw = require('./keyfiles-structure.json');
const structureJson = toLower(structureJsonRaw);

/**
 * Deep copies JSON object with keys.toLowerCase()
 * @param  {Object} obj input
 * @return {Object}     output
 */
function toLower(obj) {
    var newObj = {};
    _.keys(obj).forEach((key) => {
        if (typeof(newObj[key.toLowerCase()] = obj[key]) === 'object')
            newObj[key] = toLower(newObj[key])
    });
    return newObj
}

/**
 * Matches the input object's structure against valid keyfile structures
 * (respects key and value-type)
 * @param  {Object} obj input keyfile object
 * @return {[String, Number]} array of type (web3|ethersale) and version
 */
module.exports = function(obj) {
    var result = null;
    try {
        _.keys(structureJson).forEach((structureType) => {
            var structure = {
                parent: structureType,
                content: structureJson[structureType]['json']
            }
            var instance = {
                parent: 'obj',
                content: toLower(obj)
            }
            var error = compare([structure, instance]);
            if (!error) {
                var match = structureJson[structure.parent];
                result = [ match.type, match.json.version ];
                throw BreakException;
            }
        });
    } catch (e) {
        // break out of loop; keyfile already validated
    }
    return result;
}
<|endoftext|>


<commit_before>import fs from 'fs';
import Lexer from './transpiler/lexer';

let fileContent = fs.readFileSync('Example.dilmalang');

if (!fileContent) {
	console.error('File not found');
}

fileContent = fileContent.toString();

new Lexer(fileContent);
<commit_msg>Use Example - Loop as entry file and print lexer result<commit_after>import fs from 'fs';
import Lexer from './transpiler/lexer';

// let fileContent = fs.readFileSync('Example.dilmalang');
let fileContent = fs.readFileSync('Example - Loop.dilmalang');

if (!fileContent) {
	console.error('File not found');
}

fileContent = fileContent.toString();

const lexer = new Lexer(fileContent);
lexer.printTokens();
<|endoftext|>


<commit_before>import dotenv from "dotenv";

import archive from "./archive";
import getApplicationEvent from "./get-application-event";

dotenv.load();

export function handler (kinesisEvent, context) {
    return getApplicationEvent(kinesisEvent)
        .then(archive)
        .then(context.succeed)
        .then(context.fail);
}
<commit_msg>Added catch<commit_after>import dotenv from "dotenv";

import archive from "./archive";
import getApplicationEvent from "./get-application-event";

dotenv.load();

export function handler (kinesisEvent, context) {
    return getApplicationEvent(kinesisEvent)
        .then(archive)
        .then(context.succeed)
        .catch(context.fail);
}
<|endoftext|>


<commit_before>'use strict'
let Text = require("./text/text.js")

//by abstracting Text, we allow multiple Text objects by the same user
let nlp = function(str) {
  return new Text(str)
}

module.exports = nlp

console.log(nlp("Hiii Dr. Nick! hi there man"))
<commit_msg>removed console statement<commit_after>'use strict'
let Text = require("./text/text.js")

//by abstracting Text, we allow multiple Text objects by the same user
let nlp = function(str) {
  return new Text(str)
}

module.exports = nlp
<|endoftext|>


<commit_before>'use strict';

let tracerSession = require('continuation-local-storage').createNamespace('koa-tracer');
let Tracer = require('./tracer');

let tracer = new Tracer(tracerSession);

module.exports = function GetTracerMiddleware() {
  return function*(next) {
    tracer.initRequest(this);
    yield next;
    tracer.requestEnd();
  };
};

module.exports.startTracing = tracer.startTracing.bind(tracer);
module.exports.endTracing = tracer.endTracing.bind(tracer);
module.exports.getRequestId = tracer.getRequestId.bind(tracer);
<commit_msg>feat(tracer): delegate tracer instance to outside<commit_after>'use strict';

let tracerSession = require('continuation-local-storage').createNamespace('koa-tracer');
let Tracer = require('./tracer');

let tracer = new Tracer(tracerSession);

module.exports = function GetTracerMiddleware() {
  return function*(next) {
    tracer.initRequest(this);
    yield next;
    tracer.requestEnd();
  };
};

module.exports.tracer = tracer;
module.exports.startTracing = tracer.startTracing.bind(tracer);
module.exports.endTracing = tracer.endTracing.bind(tracer);
module.exports.getRequestId = tracer.getRequestId.bind(tracer);
<|endoftext|>


<commit_before>import React, { PureComponent, PropTypes } from 'react'
import SVGInjector from 'svg-injector'

export default class ReactSVG extends PureComponent {

  static defaultProps = {
    callback: () => {},
    className: '',
    evalScripts: 'once'
  }

  static propTypes = {
    callback: PropTypes.func,
    className: PropTypes.string,
    evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]),
    path: PropTypes.string.isRequired
  }

  injectSVG() {
    const {
      evalScripts,
      callback: each
    } = this.props

    if (this._img) {
      SVGInjector(this._img, {
        evalScripts,
        each
      })
    }
  }

  componentDidMount() {
    this.injectSVG()
  }

  componentDidUpdate() {
    this.injectSVG()
  }

  render() {
    const {
      className,
      path
    } = this.props

    return (
      <img
        ref={img => this._img = img}
        className={className}
        data-src={path}
      />
    )

  }

}
<commit_msg>Handle null parentNode from SVGInjector<commit_after>import React, { PureComponent, PropTypes } from 'react'
import SVGInjector from 'svg-injector'

export default class ReactSVG extends PureComponent {

  static defaultProps = {
    callback: () => {},
    className: '',
    evalScripts: 'once'
  }

  static propTypes = {
    callback: PropTypes.func,
    className: PropTypes.string,
    evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]),
    path: PropTypes.string.isRequired
  }

  injectSVG() {
    const {
      evalScripts,
      callback: each
    } = this.props

    if (this._img) {
      SVGInjector(this._img, {
        evalScripts,
        each
      })
    }
  }

  componentDidMount() {
    this.injectSVG()
  }

  componentDidUpdate() {
    this.injectSVG()
  }

  render() {
    const {
      className,
      path
    } = this.props

    return (
      <div>
        <img
          ref={img => this._img = img}
          className={className}
          data-src={path}
        />
      </div>
    )

  }

}
<|endoftext|>


<commit_before>// Helpers
import stripUnit from './helpers/stripUnit'

// Mixins
import clearFix from './mixins/clearFix'
import ellipsis from './mixins/ellipsis'

const polished = {
  clearFix,
  ellipsis,
  stripUnit,
}

export default polished
export { clearFix, ellipsis, stripUnit }
<commit_msg>chore(package): Export new methods<commit_after>// Helpers
import stripUnit from './helpers/stripUnit'

// Mixins
import clearFix from './mixins/clearFix'
import ellipsis from './mixins/ellipsis'
import hideText from './mixins/hideText'
import hiDIPI from './mixins/hiDPI'
import timingFunctions from './mixins/timingFunctions'
import wordWrap from './mixins/wordWrap'

const polished = {
  clearFix,
  ellipsis,
  hideText,
  hiDIPI,
  stripUnit,
  timingFunctions,
  wordWrap
}

export default polished

export {
  clearFix,
  ellipsis,
  hideText,
  hiDIPI,
  stripUnit,
  timingFunctions,
  wordWrap
}
<|endoftext|>


<commit_before>const hostname = require('os').hostname;
const hoek = require('hoek');
const Stream = require('stream');
const raven = require('raven');

const internals = {
  defaults: {
    name: hostname(),
    logger: '',
    release: '',
    environment: '',
  },
};

class GoodSentry extends Stream.Writable {
  constructor({ dsn = null, config = {}, patchGlobal = false } = {}) {
    super({ objectMode: true, decodeStrings: false });

    const settings = hoek.applyToDefaults(internals.defaults, config);
    const args = (dsn === null) ? [settings] : [dsn, settings];

    this._client = new raven.Client(...args);
    if (patchGlobal) {
      this._client.patchGlobal();
    }
  }
  _write(data, encoding, cb) {
    const extra = {
      level: ((tags = []) => {
        tags = (typeof tags === 'string') ? [tags] : tags; // eslint-disable-line no-param-reassign
        if (hoek.contain(tags, ['err', 'error'], { part: true })) {
          return 'error';
        } else if (hoek.contain(tags, ['warn', 'warning'], { part: true })) {
          return 'warning';
        } else if (hoek.contain(tags, ['info'], { part: true })) {
          return 'info';
        }

        return 'debug';
      })(data.tags),
      extra: {
        event: data.event,
        tags: data.tags || [],
      },
    };

    this._client.captureMessage(data.data, extra, () => cb());
  }
}

module.exports = GoodSentry;
<commit_msg>Remove depreciated stuff<commit_after>const hostname = require('os').hostname;
const hoek = require('hoek');
const Stream = require('stream');
const Raven = require('raven');

const internals = {
  defaults: {
    name: hostname(),
    logger: '',
    release: '',
    environment: '',
  },
};

class GoodSentry extends Stream.Writable {
  constructor({ dsn = null, config = {}, captureUncaught = false } = {}) {
    super({ objectMode: true, decodeStrings: false });

    const settings = hoek.applyToDefaults(internals.defaults, config);
    const args = (dsn === null) ? [settings] : [dsn, settings];

    this._client = Raven.config(...args);
    if (captureUncaught) {
      this._client.install();
    }
  }
  _write(data, encoding, cb) {
    const extra = {
      level: ((tags = []) => {
        tags = (typeof tags === 'string') ? [tags] : tags; // eslint-disable-line no-param-reassign
        if (hoek.contain(tags, ['err', 'error'], { part: true })) {
          return 'error';
        } else if (hoek.contain(tags, ['warn', 'warning'], { part: true })) {
          return 'warning';
        } else if (hoek.contain(tags, ['info'], { part: true })) {
          return 'info';
        }

        return 'debug';
      })(data.tags),
      extra: {
        event: data.event,
        tags: data.tags || [],
      },
    };

    this._client.captureMessage(data.data, extra, () => cb());
  }
}

module.exports = GoodSentry;
<|endoftext|>


<commit_before>import Button from './components/Button'

import Card from './components/Card/Card'
import CardMediaItem from './components/Card/CardMediaItem'

import Checkbox from './components/Checkbox'

import Dialog from './components/Dialog'

import Fab from './components/Fab'

import FormField from './components/FormField'

import Icon from './components/Icon'
import IconToggle from './components/IconToggle'

import LayoutGrid from './components/LayoutGrid/LayoutGrid'
import LayoutGridCell from './components/LayoutGrid/LayoutGridCell'
import LayoutGridInner from './components/LayoutGrid/LayoutGridInner'

import List from './components/List/List'
import ListDivider from './components/List/ListDivider'
import ListGroup from './components/List/ListGroup'
import ListGroupDivider from './components/List/ListGroupDivider'
import ListGroupSubheader from './components/List/ListGroupSubheader'
import ListItem from './components/List/ListItem'

import TemporaryDrawer from './components/TemporaryDrawer'

import Textfield from './components/Textfield/Textfield'
import TextfieldHelptext from './components/Textfield/TextfieldHelptext'
import TextfieldMultiline from './components/Textfield/TextfieldMultiline'

import Toolbar from './components/Toolbar'

const components = {
  Button,
  Card,
  CardMediaItem,
  Checkbox,
  Dialog,
  Fab,
  FormField,
  Icon,
  IconToggle,
  LayoutGrid,
  LayoutGridCell,
  LayoutGridInner,
  List,
  ListDivider,
  ListGroup,
  ListGroupDivider,
  ListGroupSubheader,
  ListItem,
  TemporaryDrawer,
  Textfield,
  TextfieldHelptext,
  TextfieldMultiline,
  Toolbar
}

function plugin (Vue, opts = { prefix: 'MCV' }) {
  const { prefix } = opts
  const compNames = Object.keys(components)
  for (let i = 0; i < compNames.length; i++) {
    const name = compNames[i]
    Vue.component(`${prefix}-${name}`, components[name])
  }
}

// Install by default if using the script tag
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(plugin)
}

export default plugin
<commit_msg>Update index.js<commit_after>import Button from './components/Button'

import Card from './components/Card/Card'
import CardMediaItem from './components/Card/CardMediaItem'

import Checkbox from './components/Checkbox'

import Dialog from './components/Dialog'

import Fab from './components/Fab'

import FormField from './components/FormField'

import Icon from './components/Icon'
import IconToggle from './components/IconToggle'

import LayoutGrid from './components/LayoutGrid/LayoutGrid'
import LayoutGridCell from './components/LayoutGrid/LayoutGridCell'
import LayoutGridInner from './components/LayoutGrid/LayoutGridInner'

import List from './components/List/List'
import ListDivider from './components/List/ListDivider'
import ListGroup from './components/List/ListGroup'
import ListGroupDivider from './components/List/ListGroupDivider'
import ListGroupSubheader from './components/List/ListGroupSubheader'
import ListItem from './components/List/ListItem'

import TemporaryDrawer from './components/TemporaryDrawer'

import Textfield from './components/Textfield/Textfield'
import TextfieldHelptext from './components/Textfield/TextfieldHelptext'
import TextfieldMultiline from './components/Textfield/TextfieldMultiline'

import Toolbar from './components/Toolbar'

const components = {
  Button,
  Card,
  CardMediaItem,
  Checkbox,
  Dialog,
  Fab,
  FormField,
  Icon,
  IconToggle,
  LayoutGrid,
  LayoutGridCell,
  LayoutGridInner,
  List,
  ListDivider,
  ListGroup,
  ListGroupDivider,
  ListGroupSubheader,
  ListItem,
  TemporaryDrawer,
  Textfield,
  TextfieldHelptext,
  TextfieldMultiline,
  Toolbar
}

function plugin (Vue, opts = { prefix: 'M' }) {
  const { prefix } = opts
  const compNames = Object.keys(components)
  for (let i = 0; i < compNames.length; i++) {
    const name = compNames[i]
    Vue.component(`${prefix}-${name}`, components[name])
  }
}

// Install by default if using the script tag
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(plugin)
}

export default plugin
<|endoftext|>


<commit_before>'use strict'

/**
 * @module serverless-plugin-warmup
 *
 * @see {@link https://serverless.com/framework/docs/providers/aws/guide/plugins/}
 *
 * @requires 'bluebird'
 * @requires 'fs-extra'
 * @requires 'path'
 * */
const BbPromise = require('bluebird')
const fs = BbPromise.promisifyAll(require('fs-extra'))
const path = require('path')

/**
 * @classdesc Keep your lambdas warm during Winter
 * @class WarmUP
 * */
class WarmUP {
  /**
   * @description Serverless Warm Up
   * @constructor
   *
   * @param {!Object} serverless - Serverless object
   * @param {!Object} options - Serverless options
   * */
  constructor (serverless, options) {
    /** Serverless variables */
    this.serverless = serverless
    this.options = options
    this.custom = this.serverless.service.custom
    this.provider = this.serverless.getProvider('aws')

    this.hooks = {
      'after:package:initialize': this.afterPackageInitialize.bind(this),
      'after:package:createDeploymentArtifacts': this.afterCreateDeploymentArtifacts.bind(this),
      'after:deploy:deploy': this.afterDeployFunctions.bind(this)
    }
  }

  /**
   * @description After package initialize hook. Create warmer function and add it to the service.
   *
   * @fulfil {} — Warm up set
   * @reject {Error} Warm up error
   *
   * @return {(boolean|Promise)}
   * */
  afterPackageInitialize () {
    this.configPlugin()
    return this.createWarmer()
  }

  /**
   * @description After create deployment artifacts. Clean prefix folder.
   *
   * @fulfil {} — Optimization finished
   * @reject {Error} Optimization error
   *
   * @return {Promise}
   * */
  afterCreateDeploymentArtifacts () {
    return this.cleanFolder()
  }

  /**
   * @description After deploy functions hooks
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  afterDeployFunctions () {
    this.configPlugin()
    if (this.warmup.prewarm) {
      return this.warmUpFunctions()
    }
  }

  /**
   * @description Configure the plugin based on the context of serverless.yml
   *
   * @return {}
   * */
  configPlugin () {
    /** Set warm up folder, file and handler paths */
    this.folderName = '_warmup'
    if (this.custom && this.custom.warmup && typeof this.custom.warmup.folderName === 'string') {
      this.folderName = this.custom.warmup.folderName
    }
    this.pathFolder = this.getPath(this.folderName)
    this.pathFile = this.pathFolder + '/index.js'
    this.pathHandler = this.folderName + '/index.warmUp'

    /** Default options */
    this.warmup = {
      cleanFolder: true,
      memorySize: 128,
      name: this.serverless.service.service + '-' + this.options.stage + '-warmup-plugin',
      schedule: ['rate(5 minutes)'],
      timeout: 10,
      prewarm: false
    }

    /** Set global custom options */
    if (!this.custom || !this.custom.warmup) {
      return
    }

    /** Clean folder */
    if (typeof this.custom.warmup.cleanFolder === 'boolean') {
      this.warmup.cleanFolder = this.custom.warmup.cleanFolder
    }

    /** Memory size */
    if (typeof this.custom.warmup.memorySize === 'number') {
      this.warmup.memorySize = this.custom.warmup.memorySize
    }

    /** Function name */
    if (typeof this.custom.warmup.name === 'string') {
      this.warmup.name = this.custom.warmup.name
    }

    /** Role */
    if (typeof this.custom.warmup.role === 'string') {
      this.warmup.role = this.custom.warmup.role
    }

    /** Tags */
    if (typeof this.custom.warmup.tags === 'object') {
      this.warmup.tags = this.custom.warmup.tags
    }

    /** Schedule expression */
    if (typeof this.custom.warmup.schedule === 'string') {
      this.warmup.schedule = [this.custom.warmup.schedule]
    } else if (Array.isArray(this.custom.warmup.schedule)) {
      this.warmup.schedule = this.custom.warmup.schedule
    }

    /** Timeout */
    if (typeof this.custom.warmup.timeout === 'number') {
      this.warmup.timeout = this.custom.warmup.timeout
    }

    /** Pre-warm */
    if (typeof this.custom.warmup.prewarm === 'boolean') {
      this.warmup.prewarm = this.custom.warmup.prewarm
    }
  }

  /**
   * @description After create deployment artifacts
   *
   * @param {string} file — File path
   *
   * @return {String} Absolute file path
   * */
  getPath (file) {
    return path.join(this.serverless.config.servicePath, file)
  }

  /**
   * @description Clean prefix folder
   *
   * @fulfil {} — Folder cleaned
   * @reject {Error} File system error
   *
   * @return {Promise}
   * */
  cleanFolder () {
    if (!this.warmup.cleanFolder) {
      return Promise.resolve()
    }
    return fs.removeAsync(this.pathFolder)
  }

  /**
   * @description Warm up functions
   *
   * @fulfil {} — Warm up function created and added to service
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  createWarmer () {
    /** Get functions */
    const allFunctions = this.serverless.service.getAllFunctions()

    /** Filter functions for warm up */
    return BbPromise.filter(allFunctions, (functionName) => {
      const functionObject = this.serverless.service.getFunction(functionName)

      /** Function needs to be warm */
      if (functionObject.warmup === true ||
        functionObject.warmup === this.options.stage ||
        (Array.isArray(functionObject.warmup) &&
          functionObject.warmup.indexOf(this.options.stage) !== -1)) {
        return functionObject
      }
    }).then((functionNames) => {
      /** Skip writing if no functions need to be warm */
      if (!functionNames.length) {
        /** Log no warmup */
        this.serverless.cli.log('WarmUP: no lambda to warm')
        return true
      }

      /** Write warm up function */
      return this.createWarmUpFunctionArtifact(functionNames)
    }).then((skip) => {
      /** Add warm up function to service */
      if (skip !== true) {
        return this.addWarmUpFunctionToService()
      }
    })
  }

  /**
   * @description Write warm up ES6 function
   *
   * @param {Array} functionNames - Function names
   *
   * @fulfil {} — Warm up function created
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  createWarmUpFunctionArtifact (functionNames) {
    /** Log warmup start */
    this.serverless.cli.log('WarmUP: setting ' + functionNames.length + ' lambdas to be warm')

    /** Get function names */
    functionNames = functionNames.map((functionName) => {
      const functionObject = this.serverless.service.getFunction(functionName)
      this.serverless.cli.log('WarmUP: ' + functionObject.name)
      return functionObject.name
    })

    /** Write function invoke promises and push to array */
    const warmUpFunction = `"use strict";

/** Generated by Serverless WarmUP Plugin at ${new Date().toISOString()} */
const aws = require("aws-sdk");
aws.config.region = "${this.serverless.service.provider.region}";
const lambda = new aws.Lambda();
const functionNames = "${functionNames.join()}".split(",");
module.exports.warmUp = (event, context, callback) => {
  let invokes = [];
  let errors = 0;
  console.log("Warm Up Start");
  functionNames.forEach((functionName) => {
    const params = {
      FunctionName: functionName,
      InvocationType: "RequestResponse",
      LogType: "None",
      Qualifier: process.env.SERVERLESS_ALIAS || "$LATEST",
      Payload: JSON.stringify({ source: "serverless-plugin-warmup" })
    };
    invokes.push(lambda.invoke(params).promise().then((data) => {
      console.log("Warm Up Invoke Success: " + functionName, data);
    }, (error) => {
      errors++;
      console.log("Warm Up Invoke Error: " + functionName, error);
    }));
  });
  Promise.all(invokes).then(() => {
    console.log("Warm Up Finished with " + errors + " invoke errors");
    callback();
  });
}`

    /** Write warm up file */
    return fs.outputFileAsync(this.pathFile, warmUpFunction)
  }

  /**
   * @description Add warm up function to service
   *
   * @return {Object} Warm up service function object
   * */
  addWarmUpFunctionToService () {
    /** SLS warm up function */
    this.serverless.service.functions.warmUpPlugin = {
      description: 'Serverless WarmUP Plugin',
      events: this.warmup.schedule.map(schedule => ({ schedule })),
      handler: this.pathHandler,
      memorySize: this.warmup.memorySize,
      name: this.warmup.name,
      runtime: 'nodejs6.10',
      package: {
        individually: true,
        exclude: ['**'],
        include: [this.folderName + '/**']
      },
      timeout: this.warmup.timeout
    }

    if (this.warmup.role) {
      this.serverless.service.functions.warmUpPlugin.role = this.warmup.role
    }

    if (this.warmup.tags) {
      this.serverless.service.functions.warmUpPlugin.tags = this.warmup.tags
    }

    /** Return service function object */
    return this.serverless.service.functions.warmUpPlugin
  }

  /**
   * @description Warm up the functions immediately after deployment
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  warmUpFunctions () {
    this.serverless.cli.log('WarmUP: Pre-warming up your functions')

    const params = {
      FunctionName: this.warmup.name,
      InvocationType: 'RequestResponse',
      LogType: 'None',
      Qualifier: process.env.SERVERLESS_ALIAS || '$LATEST',
      Payload: JSON.stringify({ source: 'serverless-plugin-warmup' })
    }

    return this.provider.request('Lambda', 'invoke', params)
      .then(data => this.serverless.cli.log('WarmUp: Functions sucessfuly pre-warmed'))
      .catch(error => this.serverless.cli.log('WarmUp: Error while pre-warming functions', error))
  }
}

/** Export WarmUP class */
module.exports = WarmUP
<commit_msg>Fix Region and Stage not being picked up from CLI<commit_after>'use strict'

/**
 * @module serverless-plugin-warmup
 *
 * @see {@link https://serverless.com/framework/docs/providers/aws/guide/plugins/}
 *
 * @requires 'bluebird'
 * @requires 'fs-extra'
 * @requires 'path'
 * */
const BbPromise = require('bluebird')
const fs = BbPromise.promisifyAll(require('fs-extra'))
const path = require('path')

/**
 * @classdesc Keep your lambdas warm during Winter
 * @class WarmUP
 * */
class WarmUP {
  /**
   * @description Serverless Warm Up
   * @constructor
   *
   * @param {!Object} serverless - Serverless object
   * @param {!Object} options - Serverless options
   * */
  constructor (serverless, options) {
    /** Serverless variables */
    this.serverless = serverless
    this.options = options

    // See https://github.com/serverless/serverless/issues/2631
    this.options.stage  = this.options.stage
      || this.serverless.service.provider.stage
      || (this.serverless.service.defaults && this.serverless.service.defaults.stage)
      || 'dev'
    this.options.region = this.options.region
      || this.serverless.service.provider.region
      || (this.serverless.service.defaults && this.serverless.service.defaults.region)
      || 'us-east-1'

    this.custom = this.serverless.service.custom
    this.provider = this.serverless.getProvider('aws')

    this.hooks = {
      'after:package:initialize': this.afterPackageInitialize.bind(this),
      'after:package:createDeploymentArtifacts': this.afterCreateDeploymentArtifacts.bind(this),
      'after:deploy:deploy': this.afterDeployFunctions.bind(this)
    }
  }

  /**
   * @description After package initialize hook. Create warmer function and add it to the service.
   *
   * @fulfil {} — Warm up set
   * @reject {Error} Warm up error
   *
   * @return {(boolean|Promise)}
   * */
  afterPackageInitialize () {
    this.configPlugin()
    return this.createWarmer()
  }

  /**
   * @description After create deployment artifacts. Clean prefix folder.
   *
   * @fulfil {} — Optimization finished
   * @reject {Error} Optimization error
   *
   * @return {Promise}
   * */
  afterCreateDeploymentArtifacts () {
    return this.cleanFolder()
  }

  /**
   * @description After deploy functions hooks
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  afterDeployFunctions () {
    this.configPlugin()
    if (this.warmup.prewarm) {
      return this.warmUpFunctions()
    }
  }

  /**
   * @description Configure the plugin based on the context of serverless.yml
   *
   * @return {}
   * */
  configPlugin () {
    /** Set warm up folder, file and handler paths */
    this.folderName = '_warmup'
    if (this.custom && this.custom.warmup && typeof this.custom.warmup.folderName === 'string') {
      this.folderName = this.custom.warmup.folderName
    }
    this.pathFolder = this.getPath(this.folderName)
    this.pathFile = this.pathFolder + '/index.js'
    this.pathHandler = this.folderName + '/index.warmUp'

    /** Default options */
    this.warmup = {
      cleanFolder: true,
      memorySize: 128,
      name: this.serverless.service.service + '-' + this.options.stage + '-warmup-plugin',
      schedule: ['rate(5 minutes)'],
      timeout: 10,
      prewarm: false
    }

    /** Set global custom options */
    if (!this.custom || !this.custom.warmup) {
      return
    }

    /** Clean folder */
    if (typeof this.custom.warmup.cleanFolder === 'boolean') {
      this.warmup.cleanFolder = this.custom.warmup.cleanFolder
    }

    /** Memory size */
    if (typeof this.custom.warmup.memorySize === 'number') {
      this.warmup.memorySize = this.custom.warmup.memorySize
    }

    /** Function name */
    if (typeof this.custom.warmup.name === 'string') {
      this.warmup.name = this.custom.warmup.name
    }

    /** Role */
    if (typeof this.custom.warmup.role === 'string') {
      this.warmup.role = this.custom.warmup.role
    }

    /** Tags */
    if (typeof this.custom.warmup.tags === 'object') {
      this.warmup.tags = this.custom.warmup.tags
    }

    /** Schedule expression */
    if (typeof this.custom.warmup.schedule === 'string') {
      this.warmup.schedule = [this.custom.warmup.schedule]
    } else if (Array.isArray(this.custom.warmup.schedule)) {
      this.warmup.schedule = this.custom.warmup.schedule
    }

    /** Timeout */
    if (typeof this.custom.warmup.timeout === 'number') {
      this.warmup.timeout = this.custom.warmup.timeout
    }

    /** Pre-warm */
    if (typeof this.custom.warmup.prewarm === 'boolean') {
      this.warmup.prewarm = this.custom.warmup.prewarm
    }
  }

  /**
   * @description After create deployment artifacts
   *
   * @param {string} file — File path
   *
   * @return {String} Absolute file path
   * */
  getPath (file) {
    return path.join(this.serverless.config.servicePath, file)
  }

  /**
   * @description Clean prefix folder
   *
   * @fulfil {} — Folder cleaned
   * @reject {Error} File system error
   *
   * @return {Promise}
   * */
  cleanFolder () {
    if (!this.warmup.cleanFolder) {
      return Promise.resolve()
    }
    return fs.removeAsync(this.pathFolder)
  }

  /**
   * @description Warm up functions
   *
   * @fulfil {} — Warm up function created and added to service
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  createWarmer () {
    /** Get functions */
    const allFunctions = this.serverless.service.getAllFunctions()

    /** Filter functions for warm up */
    return BbPromise.filter(allFunctions, (functionName) => {
      const functionObject = this.serverless.service.getFunction(functionName)

      /** Function needs to be warm */
      if (functionObject.warmup === true ||
        functionObject.warmup === this.options.stage ||
        (Array.isArray(functionObject.warmup) &&
          functionObject.warmup.indexOf(this.options.stage) !== -1)) {
        return functionObject
      }
    }).then((functionNames) => {
      /** Skip writing if no functions need to be warm */
      if (!functionNames.length) {
        /** Log no warmup */
        this.serverless.cli.log('WarmUP: no lambda to warm')
        return true
      }

      /** Write warm up function */
      return this.createWarmUpFunctionArtifact(functionNames)
    }).then((skip) => {
      /** Add warm up function to service */
      if (skip !== true) {
        return this.addWarmUpFunctionToService()
      }
    })
  }

  /**
   * @description Write warm up ES6 function
   *
   * @param {Array} functionNames - Function names
   *
   * @fulfil {} — Warm up function created
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  createWarmUpFunctionArtifact (functionNames) {
    /** Log warmup start */
    this.serverless.cli.log('WarmUP: setting ' + functionNames.length + ' lambdas to be warm')

    /** Get function names */
    functionNames = functionNames.map((functionName) => {
      const functionObject = this.serverless.service.getFunction(functionName)
      this.serverless.cli.log('WarmUP: ' + functionObject.name)
      return functionObject.name
    })

    /** Write function invoke promises and push to array */
    const warmUpFunction = `"use strict";

/** Generated by Serverless WarmUP Plugin at ${new Date().toISOString()} */
const aws = require("aws-sdk");
aws.config.region = "${this.options.region}";
const lambda = new aws.Lambda();
const functionNames = "${functionNames.join()}".split(",");
module.exports.warmUp = (event, context, callback) => {
  let invokes = [];
  let errors = 0;
  console.log("Warm Up Start");
  functionNames.forEach((functionName) => {
    const params = {
      FunctionName: functionName,
      InvocationType: "RequestResponse",
      LogType: "None",
      Qualifier: process.env.SERVERLESS_ALIAS || "$LATEST",
      Payload: JSON.stringify({ source: "serverless-plugin-warmup" })
    };
    invokes.push(lambda.invoke(params).promise().then((data) => {
      console.log("Warm Up Invoke Success: " + functionName, data);
    }, (error) => {
      errors++;
      console.log("Warm Up Invoke Error: " + functionName, error);
    }));
  });
  Promise.all(invokes).then(() => {
    console.log("Warm Up Finished with " + errors + " invoke errors");
    callback();
  });
}`

    /** Write warm up file */
    return fs.outputFileAsync(this.pathFile, warmUpFunction)
  }

  /**
   * @description Add warm up function to service
   *
   * @return {Object} Warm up service function object
   * */
  addWarmUpFunctionToService () {
    /** SLS warm up function */
    this.serverless.service.functions.warmUpPlugin = {
      description: 'Serverless WarmUP Plugin',
      events: this.warmup.schedule.map(schedule => ({ schedule })),
      handler: this.pathHandler,
      memorySize: this.warmup.memorySize,
      name: this.warmup.name,
      runtime: 'nodejs6.10',
      package: {
        individually: true,
        exclude: ['**'],
        include: [this.folderName + '/**']
      },
      timeout: this.warmup.timeout
    }

    if (this.warmup.role) {
      this.serverless.service.functions.warmUpPlugin.role = this.warmup.role
    }

    if (this.warmup.tags) {
      this.serverless.service.functions.warmUpPlugin.tags = this.warmup.tags
    }

    /** Return service function object */
    return this.serverless.service.functions.warmUpPlugin
  }

  /**
   * @description Warm up the functions immediately after deployment
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  warmUpFunctions () {
    this.serverless.cli.log('WarmUP: Pre-warming up your functions')

    const params = {
      FunctionName: this.warmup.name,
      InvocationType: 'RequestResponse',
      LogType: 'None',
      Qualifier: process.env.SERVERLESS_ALIAS || '$LATEST',
      Payload: JSON.stringify({ source: 'serverless-plugin-warmup' })
    }

    return this.provider.request('Lambda', 'invoke', params)
      .then(data => this.serverless.cli.log('WarmUp: Functions sucessfuly pre-warmed'))
      .catch(error => this.serverless.cli.log('WarmUp: Error while pre-warming functions', error))
  }
}

/** Export WarmUP class */
module.exports = WarmUP
<|endoftext|>


<commit_before>export const version = '0.0.15'
export const TextOperation = require('./text-operation')
export const SimpleTextOperation = require('./simple-text-operation')
export const Client = require('./client')
export const Server = require('./server')
export const Selection = require('./selection')
export const EditorSocketIOServer = require('./editor-socketio-server')
<commit_msg>Remove version in src/index.js<commit_after>export const TextOperation = require('./text-operation')
export const SimpleTextOperation = require('./simple-text-operation')
export const Client = require('./client')
export const Server = require('./server')
export const Selection = require('./selection')
export const EditorSocketIOServer = require('./editor-socketio-server')
<|endoftext|>