<commit_before>import camelCase from 'camel-case';

function makeCustomElementProps (props) {
  let customElementProps = {};
  Object.keys(props).forEach(function (key) {
    if (key !== 'children') {
      customElementProps[key] = props[key];
    }
  });

  return customElementProps;
}

function setCustomElementProps (customElement, props) {
  Object.keys(makeCustomElementProps(props)).forEach(function (key) {
    customElement[key] = props[key];
  });
}

function getDefaultProps (properties) {
  let defaults = {};
  Object.keys(properties).forEach(function (p) {
    defaults[p] = properties[p].default;
  });
  return defaults;
}

export default function (CustomElement, opts = {}) {
  const React = opts.React || window.React;
  const ReactDOM = opts.ReactDOM || window.ReactDOM;
  const container = opts.container || 'div';
  const defaultProps = getDefaultProps(CustomElement.properties);

  const ReactClass = React.createClass({
    getDefaultProps() {
      return defaultProps;
    },
    render () {
      return React.createElement(container);
    },
    renderChildren (props) {
      // Render the component in the new tree
      ReactDOM.render(React.createElement(container, null, props.children), this._realCustomElement);

      // Passes on all non-react-special props to the custom element.
      setCustomElementProps(this._realCustomElement, props);
    },
    componentDidMount () {
      const props = this.props;

      // The real custom element is the component that we want to contain the
      // new render tree as its content.
      this._realCustomElement = CustomElement(makeCustomElementProps(props));

      // Listen for custom element changes and cancel them to make a stateless component
      this._realCustomElement.addEventListener('property-change', function (e) {
        if (props.handlePropertyChange) {
          props.handlePropertyChange(e, props);
          e.preventDefault();
        }
      });

      // The real portal node is this node which we will be appending the real
      // custom element to.
      this._realPortalNode = ReactDOM.findDOMNode(this);

      // The custom element becomes the content of this node.
      this._realPortalNode.appendChild(this._realCustomElement);

      // Now kick off the rendering of the custom element and react tree.
      this.renderChildren(this.props);
    },
    componentWillReceiveProps (props) {
      this.renderChildren(props);
    }
  });

  ReactClass.displayName = camelCase(CustomElement.id);

  return ReactClass;
}
<commit_msg>Remove portals and add support for events (all types: custom and built-in).<commit_after>import assign from 'object-assign';

function makeStateless(comp, node, props, opts) {
  const propChangeHandler = props[opts.propChangeHandler];
  node.addEventListener(opts.propChangeEvent, function (e) {
    if (propChangeHandler) {
      propChangeHandler.call(comp, e);
      e.preventDefault();
    }
  });
}

function syncEvent(node, eventName, newEventHandler) {
  const eventStore = node.__events || (node.__events = {});
  const oldEventHandler = eventStore[eventName];

  // Remove old listener so they don't double up.
  if (oldEventHandler) {
    node.removeEventListener(eventName, oldEventHandler);
  }

  // Bind new listener.
  if (newEventHandler) {
    node.addEventListener(eventName, eventStore[eventName] = function (e) {
      newEventHandler.call(this, e);
    });
  }
}

const defaults = {
  propChangeEvent: 'prop-change',
  propChangeHandler: 'propChangeHandler',
  React: window.React,
  ReactDOM: window.ReactDOM
};

export default function(CustomElement, opts) {
  opts = assign(defaults, opts);
  const displayName = (new CustomElement()).tagName;
  const { React, ReactDOM } = opts;

  return React.createClass({
    displayName,
    render() {
      return React.createElement(displayName, null, this.props.children);
    },
    componentDidMount() {
      const node = ReactDOM.findDOMNode(this);
      const props = this.props;
      makeStateless(this, node, props, opts);
      this.componentWillReceiveProps(props);
    },
    componentWillReceiveProps(props) {
      const node = ReactDOM.findDOMNode(this);
      Object.keys(props).forEach(name => {
        if (name === 'children') {
          return;
        }

        if (name.indexOf('on') === 0) {
          syncEvent(node, name.substring(2), props[name]);
        } else {
          node[name] = props[name];
        }
      });
    }
  });
}
<|endoftext|>


<commit_before>const express     = require('express');
const bodyParser  = require('body-parser');

const log      = require('./logger')(__filename);

const DEFAULT_HOSTNAME = 'localhost';
const DEFAULT_PORT = 3000;

module.exports = class Core {
  constructor(port = DEFAULT_PORT, hostname = DEFAULT_HOSTNAME) {
    this._tgApiKey = null;
    this._webhookUrl = null;
    this._port = port;
    this._hostname = hostname;

    this._server = startHttpServer(port, hostname);
  }

  subscribeWebhook(url, callback) {
    if (!this._webhookUrl) {
      this._webhookUrl = url;
      this._server.post(url, (req, res) => {
        callback(req);
      });
    }
  }
};

function startHttpServer(port, hostname) {
  const server = express();

  // Add required middlewares
  server.use(bodyParser.urlencoded({ extended: false }));
  server.use(bodyParser.json());

  // Start!
  server.listen(port, hostname, () => {
    log.info(`HTTP-server started at ${this._hostname}:${this._port}`);
  });

  return server;
}
<commit_msg>Bugfix: log the server address which is being used<commit_after>const express     = require('express');
const bodyParser  = require('body-parser');

const log      = require('./logger')(__filename);

const DEFAULT_HOSTNAME = 'localhost';
const DEFAULT_PORT = 3000;

module.exports = class Core {
  constructor(port = DEFAULT_PORT, hostname = DEFAULT_HOSTNAME) {
    this._tgApiKey = null;
    this._webhookUrl = null;
    this._port = port;
    this._hostname = hostname;

    this._server = startHttpServer(port, hostname);
  }

  subscribeWebhook(url, callback) {
    if (!this._webhookUrl) {
      this._webhookUrl = url;
      this._server.post(url, (req, res) => {
        callback(req);
      });
    }
  }
};

function startHttpServer(port, hostname) {
  const server = express();

  // Add required middlewares
  server.use(bodyParser.urlencoded({ extended: false }));
  server.use(bodyParser.json());

  // Start!
  server.listen(port, hostname, () => {
    log.info(`HTTP-server started at ${hostname}:${port}`);
  });

  return server;
}
<|endoftext|>


<commit_before>export default function ({types: t}) {
  var restoreIdentifier = t.identifier('restore');
  var defaultIdentifier = t.identifier('default');
  var IGNORE_SYMBOL = Symbol();

  function markIgnored(node) {
    node[IGNORE_SYMBOL] = true;
    return node;
  }

  function isLiteral(node) {
    return t.isRegExpLiteral(node) || t.isNullLiteral(node) || t.isStringLiteral(node) || t.isBooleanLiteral(node) || t.isNumericLiteral(node);
  }

  return {
    visitor: {
      Program: {
        enter: function (path, state) {
          state.exports = {};
        },
        exit: function (path, {exports}) {
          var exported = Object.keys(exports);
          if (!exported.length) return;
          var rewired = exported.map(e => ({
            exported: t.identifier(e),
            local: exports[e],
            temp: path.scope.generateUidIdentifier(e)
          }));
          var vars = rewired.map(({local, temp}) => t.variableDeclarator(temp, local));
          var assignments = rewired.map(({local, temp}) => t.expressionStatement(t.assignmentExpression('=', local, temp)));
          path.pushContainer('body', [
            t.variableDeclaration('var', vars),
            markIgnored(t.exportNamedDeclaration(t.functionDeclaration(restoreIdentifier, [], t.blockStatement(assignments)), []))
          ]);
        }
      },
      ExportDefaultDeclaration: function (path, {exports}) {
        var declaration = path.node.declaration;
        if (t.isIdentifier(declaration)) {
          exports[defaultIdentifier.name] = declaration;
          path.replaceWith(markIgnored(t.exportNamedDeclaration(null, [
            t.exportSpecifier(declaration, defaultIdentifier)
          ])));
        } else if (t.isFunctionDeclaration(declaration)) {
          const id = path.scope.generateUidIdentifier('default');
          exports[defaultIdentifier.name] = id;
          path.replaceWithMultiple([
            t.variableDeclaration('var', [
              t.variableDeclarator(id, t.functionExpression(declaration.id, declaration.params, declaration.body, declaration.generator, declaration.async))
            ]),
            markIgnored(t.exportNamedDeclaration(null, [
              t.exportSpecifier(id, defaultIdentifier)
            ]))
          ]);
        } else if (isLiteral(declaration)) {
          const id = path.scope.generateUidIdentifier('default');
          exports[defaultIdentifier.name] = id;
          path.replaceWithMultiple([
            t.variableDeclaration('var', [t.variableDeclarator(id, declaration)]),
            markIgnored(t.exportNamedDeclaration(null, [
              t.exportSpecifier(id, defaultIdentifier)
            ]))
          ]);
        }
      },
      ExportNamedDeclaration: function (path, {exports}) {
        if (path.node[IGNORE_SYMBOL]) return;
        var declaration = path.node.declaration;
        if (t.isVariableDeclaration(declaration)) {
          declaration.declarations.forEach(({id}) => {
            exports[id.name] = id;
          });
        } else if (t.isFunctionDeclaration(declaration)) {
          const id = declaration.id;
          exports[id.name] = id;
          path.replaceWithMultiple([
            t.variableDeclaration('var', [
              t.variableDeclarator(id, t.functionExpression(id, declaration.params, declaration.body, declaration.generator, declaration.async))
            ]),
            markIgnored(t.exportNamedDeclaration(null, [
              t.exportSpecifier(id, id)
            ]))
          ]);
        } else {
          path.node.specifiers.forEach(({exported, local}) => {
            exports[exported.name] = local;
          });
        }
      }
    }
  };
}
<commit_msg>store exports as map<commit_after>export default function ({types: t}) {
  var restoreIdentifier = t.identifier('restore');
  var defaultIdentifier = t.identifier('default');
  var IGNORE_SYMBOL = Symbol();

  function markIgnored(node) {
    node[IGNORE_SYMBOL] = true;
    return node;
  }

  function isLiteral(node) {
    return t.isRegExpLiteral(node) || t.isNullLiteral(node) || t.isStringLiteral(node) || t.isBooleanLiteral(node) || t.isNumericLiteral(node);
  }

  return {
    visitor: {
      Program: {
        enter: function (path, state) {
          state.exports = new Map();
        },
        exit: function (path, {exports}) {
          if (!exports.size) return;
          var rewired = Array.from(exports.entries()).map(([exported, local]) => ({
            exported,
            local,
            temp: path.scope.generateUidIdentifierBasedOnNode(exported)
          }));
          var vars = rewired.map(({local, temp}) => t.variableDeclarator(temp, local));
          var assignments = rewired.map(({local, temp}) => t.expressionStatement(t.assignmentExpression('=', local, temp)));
          path.pushContainer('body', [
            t.variableDeclaration('var', vars),
            markIgnored(t.exportNamedDeclaration(t.functionDeclaration(restoreIdentifier, [], t.blockStatement(assignments)), []))
          ]);
        }
      },
      ExportDefaultDeclaration: function (path, {exports}) {
        var declaration = path.node.declaration;
        if (t.isIdentifier(declaration)) {
          exports.set(defaultIdentifier, declaration);
          path.replaceWith(markIgnored(t.exportNamedDeclaration(null, [
            t.exportSpecifier(declaration, defaultIdentifier)
          ])));
        } else if (t.isFunctionDeclaration(declaration)) {
          const id = path.scope.generateUidIdentifier('default');
          exports.set(defaultIdentifier, id);
          path.replaceWithMultiple([
            t.variableDeclaration('var', [
              t.variableDeclarator(id, t.functionExpression(declaration.id, declaration.params, declaration.body, declaration.generator, declaration.async))
            ]),
            markIgnored(t.exportNamedDeclaration(null, [
              t.exportSpecifier(id, defaultIdentifier)
            ]))
          ]);
        } else if (isLiteral(declaration)) {
          const id = path.scope.generateUidIdentifier('default');
          exports.set(defaultIdentifier, id);
          path.replaceWithMultiple([
            t.variableDeclaration('var', [t.variableDeclarator(id, declaration)]),
            markIgnored(t.exportNamedDeclaration(null, [
              t.exportSpecifier(id, defaultIdentifier)
            ]))
          ]);
        }
      },
      ExportNamedDeclaration: function (path, {exports}) {
        if (path.node[IGNORE_SYMBOL]) return;
        var declaration = path.node.declaration;
        if (t.isVariableDeclaration(declaration)) {
          declaration.declarations.forEach(({id}) => {
            exports.set(id, id);
          });
        } else if (t.isFunctionDeclaration(declaration)) {
          const id = declaration.id;
          exports.set(id, id);
          path.replaceWithMultiple([
            t.variableDeclaration('var', [
              t.variableDeclarator(id, t.functionExpression(id, declaration.params, declaration.body, declaration.generator, declaration.async))
            ]),
            markIgnored(t.exportNamedDeclaration(null, [
              t.exportSpecifier(id, id)
            ]))
          ]);
        } else {
          path.node.specifiers.forEach(({exported, local}) => {
            exports.set(exported, local);
          });
        }
      }
    }
  };
}
<|endoftext|>


<commit_before>var isArray = require("is_array"),
    isObject = require("is_object"),
    isFunction = require("is_function"),
    createStore = require("create_store"),
    fastSlice = require("fast_slice");

var PromiseShim, PrivatePromise;

if (typeof(Promise) !== "undefined") {
    PromiseShim = Promise;
} else {
    PrivatePromise = (function() {

        function PrivatePromise(resolver) {
            var _this = this;

            this.handlers = [];
            this.state = null;
            this.value = null;

            handleResolve(
                resolver,
                function resolve(newValue) {
                    resolveValue(_this, newValue);
                },
                function reject(newValue) {
                    rejectValue(_this, newValue);
                }
            );
        }

        PrivatePromise.store = createStore();

        PrivatePromise.handle = function(_this, onFulfilled, onRejected, resolve, reject) {
            handle(_this, new Handler(onFulfilled, onRejected, resolve, reject));
        };

        function Handler(onFulfilled, onRejected, resolve, reject) {
            this.onFulfilled = isFunction(onFulfilled) ? onFulfilled : null;
            this.onRejected = isFunction(onRejected) ? onRejected : null;
            this.resolve = resolve;
            this.reject = reject;
        }

        function handleResolve(resolver, onFulfilled, onRejected) {
            var done = false;

            try {
                resolver(
                    function(value) {
                        if (done) {
                            return;
                        }
                        done = true;
                        onFulfilled(value);
                    },
                    function(reason) {
                        if (done) {
                            return;
                        }
                        done = true;
                        onRejected(reason);
                    }
                );
            } catch (err) {
                if (done) {
                    return;
                }
                done = true;
                onRejected(err);
            }
        }

        function resolveValue(_this, newValue) {
            try {
                if (newValue === _this) {
                    throw new TypeError("A promise cannot be resolved with itself");
                }

                if (newValue && (isObject(newValue) || isFunction(newValue))) {
                    if (isFunction(newValue.then)) {
                        handleResolve(
                            function resolver(resolve, reject) {
                                newValue.then(resolve, reject);
                            },
                            function resolve(newValue) {
                                resolveValue(_this, newValue);
                            },
                            function reject(newValue) {
                                rejectValue(_this, newValue);
                            }
                        );
                        return;
                    }
                }
                _this.state = true;
                _this.value = newValue;
                finale(_this);
            } catch (err) {
                rejectValue(_this, err);
            }
        }

        function rejectValue(_this, newValue) {
            _this.state = false;
            _this.value = newValue;
            finale(_this);
        }

        function finale(_this) {
            var handlers = _this.handlers,
                i = -1,
                il = handlers.length - 1;

            while (i++ < il) {
                handle(_this, handlers[i]);
            }

            handlers.length = 0;
        }

        function handle(_this, handler) {
            var state = _this.state;

            if (_this.state === null) {
                _this.handlers.push(handler);
                return;
            }

            process.nextTick(function nextTick() {
                var callback = state ? handler.onFulfilled : handler.onRejected,
                    value = _this.value,
                    out;

                if (callback === null) {
                    (state ? handler.resolve : handler.reject)(value);
                    return;
                }

                try {
                    out = callback(value);
                } catch (err) {
                    handler.reject(err);
                    return;
                }

                handler.resolve(out);
            });
        }

        return PrivatePromise;
    }());

    PromiseShim = function Promise(resolver) {

        if (!(this instanceof PromiseShim)) {
            throw new TypeError("Promise(resolver) \"this\" must be an instance of of Promise");
        }
        if (!isFunction(resolver)) {
            throw new TypeError("Promise(resolver) You must pass a resolver function as the first argument to the promise constructor");
        }

        PrivatePromise.store.set(this, new PrivatePromise(resolver));
    };

    PromiseShim.prototype.then = function(onFulfilled, onRejected) {
        var _this = PrivatePromise.store.get(this);

        return new PromiseShim(function resolver(resolve, reject) {
            PrivatePromise.handle(_this, onFulfilled, onRejected, resolve, reject);
        });
    };
}

if (!isFunction(PromiseShim.prototype["catch"])) {
    PromiseShim.prototype["catch"] = function(onRejected) {
        return this.then(null, onRejected);
    };
}

if (!isFunction(PromiseShim.resolve)) {
    PromiseShim.resolve = function(value) {
        if (value instanceof PromiseShim) {
            return value;
        }

        return new PromiseShim(function resolver(resolve) {
            resolve(value);
        });
    };
}

if (!isFunction(PromiseShim.reject)) {
    PromiseShim.reject = function(value) {
        return new PromiseShim(function resolver(resolve, reject) {
            reject(value);
        });
    };
}

if (!isFunction(PromiseShim.defer)) {
    PromiseShim.defer = function() {
        var deferred = {};

        deferred.promise = new PromiseShim(function resolver(resolve, reject) {
            deferred.resolve = resolve;
            deferred.reject = reject;
        });

        return deferred;
    };
}

if (!isFunction(PromiseShim.all)) {
    PromiseShim.all = function(value) {
        var args = (arguments.length === 1 && isArray(value)) ? value : fastSlice(arguments);

        return new PromiseShim(function resolver(resolve, reject) {
            var length = args.length,
                i = -1,
                il = length - 1;

            if (length === 0) {
                resolve([]);
                return;
            }

            function resolveValue(index, value) {
                try {
                    if (value && (isObject(value) || isFunction(value)) && isFunction(value.then)) {
                        value.then(function(v) {
                            resolveValue(index, v);
                        }, reject);
                        return;
                    }
                    if (--length === 0) {
                        resolve(args);
                    }
                } catch (e) {
                    reject(e);
                }
            }

            while (i++ < il) {
                resolveValue(i, args[i]);
            }
        });
    };
}

if (!isFunction(PromiseShim.race)) {
    PromiseShim.race = function(values) {
        return new PromiseShim(function resolver(resolve, reject) {
            var i = -1,
                il = values.length - 1,
                value;

            while (i++ < il) {
                value = values[i];

                if (value && (isObject(value) || isFunction(value)) && isFunction(value.then)) {
                    value.then(resolve, reject);
                }
            }
        });
    };
}

module.exports = PromiseShim;
<commit_msg>updates<commit_after>var isArray = require("is_array"),
    isObject = require("is_object"),
    isFunction = require("is_function"),
    createStore = require("create_store"),
    fastSlice = require("fast_slice");

var PromisePolyfill, PrivatePromise;

if (typeof(Promise) !== "undefined") {
    PromisePolyfill = Promise;
} else {
    PrivatePromise = (function() {

        function PrivatePromise(resolver) {
            var _this = this;

            this.handlers = [];
            this.state = null;
            this.value = null;

            handleResolve(
                resolver,
                function resolve(newValue) {
                    resolveValue(_this, newValue);
                },
                function reject(newValue) {
                    rejectValue(_this, newValue);
                }
            );
        }

        PrivatePromise.store = createStore();

        PrivatePromise.handle = function(_this, onFulfilled, onRejected, resolve, reject) {
            handle(_this, new Handler(onFulfilled, onRejected, resolve, reject));
        };

        function Handler(onFulfilled, onRejected, resolve, reject) {
            this.onFulfilled = isFunction(onFulfilled) ? onFulfilled : null;
            this.onRejected = isFunction(onRejected) ? onRejected : null;
            this.resolve = resolve;
            this.reject = reject;
        }

        function handleResolve(resolver, onFulfilled, onRejected) {
            var done = false;

            try {
                resolver(
                    function(value) {
                        if (done) {
                            return;
                        }
                        done = true;
                        onFulfilled(value);
                    },
                    function(reason) {
                        if (done) {
                            return;
                        }
                        done = true;
                        onRejected(reason);
                    }
                );
            } catch (err) {
                if (done) {
                    return;
                }
                done = true;
                onRejected(err);
            }
        }

        function resolveValue(_this, newValue) {
            try {
                if (newValue === _this) {
                    throw new TypeError("A promise cannot be resolved with itself");
                }

                if (newValue && (isObject(newValue) || isFunction(newValue))) {
                    if (isFunction(newValue.then)) {
                        handleResolve(
                            function resolver(resolve, reject) {
                                newValue.then(resolve, reject);
                            },
                            function resolve(newValue) {
                                resolveValue(_this, newValue);
                            },
                            function reject(newValue) {
                                rejectValue(_this, newValue);
                            }
                        );
                        return;
                    }
                }
                _this.state = true;
                _this.value = newValue;
                finale(_this);
            } catch (err) {
                rejectValue(_this, err);
            }
        }

        function rejectValue(_this, newValue) {
            _this.state = false;
            _this.value = newValue;
            finale(_this);
        }

        function finale(_this) {
            var handlers = _this.handlers,
                i = -1,
                il = handlers.length - 1;

            while (i++ < il) {
                handle(_this, handlers[i]);
            }

            handlers.length = 0;
        }

        function handle(_this, handler) {
            var state = _this.state;

            if (_this.state === null) {
                _this.handlers.push(handler);
                return;
            }

            process.nextTick(function nextTick() {
                var callback = state ? handler.onFulfilled : handler.onRejected,
                    value = _this.value,
                    out;

                if (callback === null) {
                    (state ? handler.resolve : handler.reject)(value);
                    return;
                }

                try {
                    out = callback(value);
                } catch (err) {
                    handler.reject(err);
                    return;
                }

                handler.resolve(out);
            });
        }

        return PrivatePromise;
    }());

    PromisePolyfill = function Promise(resolver) {

        if (!(this instanceof PromisePolyfill)) {
            throw new TypeError("Promise(resolver) \"this\" must be an instance of of Promise");
        }
        if (!isFunction(resolver)) {
            throw new TypeError("Promise(resolver) You must pass a resolver function as the first argument to the promise constructor");
        }

        PrivatePromise.store.set(this, new PrivatePromise(resolver));
    };

    PromisePolyfill.prototype.then = function(onFulfilled, onRejected) {
        var _this = PrivatePromise.store.get(this);

        return new PromisePolyfill(function resolver(resolve, reject) {
            PrivatePromise.handle(_this, onFulfilled, onRejected, resolve, reject);
        });
    };
}

if (!isFunction(PromisePolyfill.prototype["catch"])) {
    PromisePolyfill.prototype["catch"] = function(onRejected) {
        return this.then(null, onRejected);
    };
}

if (!isFunction(PromisePolyfill.resolve)) {
    PromisePolyfill.resolve = function(value) {
        if (value instanceof PromisePolyfill) {
            return value;
        }

        return new PromisePolyfill(function resolver(resolve) {
            resolve(value);
        });
    };
}

if (!isFunction(PromisePolyfill.reject)) {
    PromisePolyfill.reject = function(value) {
        return new PromisePolyfill(function resolver(resolve, reject) {
            reject(value);
        });
    };
}

if (!isFunction(PromisePolyfill.defer)) {
    PromisePolyfill.defer = function() {
        var deferred = {};

        deferred.promise = new PromisePolyfill(function resolver(resolve, reject) {
            deferred.resolve = resolve;
            deferred.reject = reject;
        });

        return deferred;
    };
}

if (!isFunction(PromisePolyfill.all)) {
    PromisePolyfill.all = function(value) {
        var args = (arguments.length === 1 && isArray(value)) ? value : fastSlice(arguments);

        return new PromisePolyfill(function resolver(resolve, reject) {
            var length = args.length,
                i = -1,
                il = length - 1;

            if (length === 0) {
                resolve([]);
                return;
            }

            function resolveValue(index, value) {
                try {
                    if (value && (isObject(value) || isFunction(value)) && isFunction(value.then)) {
                        value.then(function(v) {
                            resolveValue(index, v);
                        }, reject);
                        return;
                    }
                    if (--length === 0) {
                        resolve(args);
                    }
                } catch (e) {
                    reject(e);
                }
            }

            while (i++ < il) {
                resolveValue(i, args[i]);
            }
        });
    };
}

if (!isFunction(PromisePolyfill.race)) {
    PromisePolyfill.race = function(values) {
        return new PromisePolyfill(function resolver(resolve, reject) {
            var i = -1,
                il = values.length - 1,
                value;

            while (i++ < il) {
                value = values[i];

                if (value && (isObject(value) || isFunction(value)) && isFunction(value.then)) {
                    value.then(resolve, reject);
                }
            }
        });
    };
}

module.exports = PromisePolyfill;
<|endoftext|>


<commit_before>var stats, scene, renderer, composer;
var camera, cameraControls;
var material;
var keyboard = new THREEx.KeyboardState();

import vertex_shader from '../glsl/vertex.glsl';
import fragment_shader from '../glsl/fragment.glsl';

import * as THREE from 'three';

if( !init() )    animate();

// init the scene
function init(){

    if( Detector.webgl ){
        renderer = new THREE.WebGLRenderer({
            antialias        : true,    // to get smoother output
            preserveDrawingBuffer    : true    // to allow screenshot
        });
        renderer.setClearColor( 0xA0FF3A, 1 );
    }else{
        Detector.addGetWebGLMessage();
        return true;
    }
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.getElementById('container').appendChild(renderer.domElement);

    // add Stats.js - https://github.com/mrdoob/stats.js
    stats = new Stats();
    stats.domElement.style.position    = 'absolute';
    stats.domElement.style.bottom    = '0px';
    document.body.appendChild( stats.domElement );

    // create a scene
    scene = new THREE.Scene();

    // put a camera in the scene
    camera    = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.set(0, 0, 5);
    scene.add(camera);

    // create a camera contol
    cameraControls    = new THREEx.DragPanControls(camera)

    // transparently support window resize
    THREEx.WindowResize.bind(renderer, camera);
    // allow 'p' to make screenshot
    THREEx.Screenshot.bindKey(renderer);
    // allow 'f' to go fullscreen where this feature is supported
    if( THREEx.FullScreen.available() ){
        THREEx.FullScreen.bindKey();
        document.getElementById('inlineDoc').innerHTML    += "- f for fullscreen";
    }

    var uniforms = {
        camera_pos: {
            type: 'v3',
            value: new THREE.Vector3(),
        },
        grain: {
             type: 'f',
             value: 1.0,
        },
        harmonics: {
             type: 'f',
             value: 4.0,
        },
    };

    var geometry    = new THREE.CubeGeometry( 2, 2, 2 );
    material        = new THREE.ShaderMaterial({
                          ambient:        0x808080,
                          uniforms:       uniforms,
                          vertexShader:   vertex_shader,
                          fragmentShader: fragment_shader,
                      });
    var mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );
}

// animation loop
function animate() {

    // loop on request animation loop
    // - it has to be at the begining of the function
    // - see details at http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
    requestAnimationFrame( animate );

    // do the render
    render();

    // update stats
    stats.update();

}

// render the scene
function render() {
    // variable which is increase by Math.PI every seconds - usefull for animation
    var PIseconds    = Date.now() * Math.PI;

    // update camera controls
    cameraControls.update();

    if ( material && camera ) {
        // https://github.com/mrdoob/three.js/issues/1188
        // var viewMatrix       = camera.matrixWorld.clone();
        // var modelMatrix      = mesh.matrixWorld.clone();
        // var modelViewMatrix  = camera.matrixWorld.clone().multiplySelf( mesh.matrixWorld );
        // material.uniforms.modelViewMatrixInverse.value.getInverse( modelViewMatrix );
        material.uniforms.camera_pos.value = camera.position;
    }
    if( keyboard.pressed("a") ) {
        material.uniforms.grain.value += 0.1;
        document.getElementById('grain').innerHTML = material.uniforms.grain.value.toFixed(1);
    }
    if( keyboard.pressed("z") && material.uniforms.grain.value > 1) {
        material.uniforms.grain.value -= 0.1;
        document.getElementById('grain').innerHTML = material.uniforms.grain.value.toFixed(1);
    }
    if( keyboard.pressed("s") && material.uniforms.harmonics.value < 8) {
        material.uniforms.harmonics.value += 1.0;
        document.getElementById('harmonics').innerHTML = material.uniforms.harmonics.value;
    }
    if( keyboard.pressed("x") && material.uniforms.harmonics.value > 1) {
        material.uniforms.harmonics.value -= 1.0;
        document.getElementById('harmonics').innerHTML = material.uniforms.harmonics.value;
    }

    // actually render the scene
    renderer.render( scene, camera );
}
<commit_msg>Require three and make it global, so DragPanControl can see it<commit_after>var stats, scene, renderer, composer;
var camera, cameraControls;
var material;
var keyboard = new THREEx.KeyboardState();

import vertex_shader from '../glsl/vertex.glsl';
import fragment_shader from '../glsl/fragment.glsl';

var THREE = require('three');
window.THREE = THREE;

if( !init() )    animate();

// init the scene
function init(){

    if( Detector.webgl ){
        renderer = new THREE.WebGLRenderer({
            antialias        : true,    // to get smoother output
            preserveDrawingBuffer    : true    // to allow screenshot
        });
        renderer.setClearColor( 0xA0FF3A, 1 );
    }else{
        Detector.addGetWebGLMessage();
        return true;
    }
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.getElementById('container').appendChild(renderer.domElement);

    // add Stats.js - https://github.com/mrdoob/stats.js
    stats = new Stats();
    stats.domElement.style.position    = 'absolute';
    stats.domElement.style.bottom    = '0px';
    document.body.appendChild( stats.domElement );

    // create a scene
    scene = new THREE.Scene();

    // put a camera in the scene
    camera    = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.set(0, 0, 5);
    scene.add(camera);

    // create a camera contol
    cameraControls    = new THREEx.DragPanControls(camera)

    // transparently support window resize
    THREEx.WindowResize.bind(renderer, camera);
    // allow 'p' to make screenshot
    THREEx.Screenshot.bindKey(renderer);
    // allow 'f' to go fullscreen where this feature is supported
    if( THREEx.FullScreen.available() ){
        THREEx.FullScreen.bindKey();
        document.getElementById('inlineDoc').innerHTML    += "- f for fullscreen";
    }

    var uniforms = {
        camera_pos: {
            type: 'v3',
            value: new THREE.Vector3(),
        },
        grain: {
             type: 'f',
             value: 1.0,
        },
        harmonics: {
             type: 'f',
             value: 4.0,
        },
    };

    var geometry    = new THREE.CubeGeometry( 2, 2, 2 );
    material        = new THREE.ShaderMaterial({
                          ambient:        0x808080,
                          uniforms:       uniforms,
                          vertexShader:   vertex_shader,
                          fragmentShader: fragment_shader,
                      });
    var mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );
}

// animation loop
function animate() {

    // loop on request animation loop
    // - it has to be at the begining of the function
    // - see details at http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
    requestAnimationFrame( animate );

    // do the render
    render();

    // update stats
    stats.update();

}

// render the scene
function render() {
    // variable which is increase by Math.PI every seconds - usefull for animation
    var PIseconds    = Date.now() * Math.PI;

    // update camera controls
    cameraControls.update();

    if ( material && camera ) {
        // https://github.com/mrdoob/three.js/issues/1188
        // var viewMatrix       = camera.matrixWorld.clone();
        // var modelMatrix      = mesh.matrixWorld.clone();
        // var modelViewMatrix  = camera.matrixWorld.clone().multiplySelf( mesh.matrixWorld );
        // material.uniforms.modelViewMatrixInverse.value.getInverse( modelViewMatrix );
        material.uniforms.camera_pos.value = camera.position;
    }
    if( keyboard.pressed("a") ) {
        material.uniforms.grain.value += 0.1;
        document.getElementById('grain').innerHTML = material.uniforms.grain.value.toFixed(1);
    }
    if( keyboard.pressed("z") && material.uniforms.grain.value > 1) {
        material.uniforms.grain.value -= 0.1;
        document.getElementById('grain').innerHTML = material.uniforms.grain.value.toFixed(1);
    }
    if( keyboard.pressed("s") && material.uniforms.harmonics.value < 8) {
        material.uniforms.harmonics.value += 1.0;
        document.getElementById('harmonics').innerHTML = material.uniforms.harmonics.value;
    }
    if( keyboard.pressed("x") && material.uniforms.harmonics.value > 1) {
        material.uniforms.harmonics.value -= 1.0;
        document.getElementById('harmonics').innerHTML = material.uniforms.harmonics.value;
    }

    // actually render the scene
    renderer.render( scene, camera );
}
<|endoftext|>


<commit_before>'use strict';
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
chai.should();

var assert = require('assert');
var createNewDevice = require('../lib/handlers/CreateNewDevice');
var getDeviceByName = require('../lib/handlers/GetDeviceByName');
var putDeviceForName = require('../lib/handlers/PutDeviceForName');

describe("Aws calls", function() {
  describe('CreateNewDevice', function () {
    // it("should create a simple object", function() {
    //   return createNewDevice.handler({
    //     "name": "test_" + Math.random(),
    //     "room": "MyLivingRoom",
    //     "type": "light"
    //   }).should.be.fulfilled
    //   .and.eventually.have.property("status");
    // });
    it("should have a private file with data", function() {
      var priv = require('../lib/handlers/CreateNewDevice/private');
      assert(priv, "Private file exists.")
      assert(priv.mqtt.url)
      assert(priv.mqtt.username)
      assert(priv.mqtt.password)
    })
    it("should require a name", function() {
      return createNewDevice.handler({
        "room": "MyLivingRoom",
        "type": "light"
      }).should.eventually.be.rejected;
    });
    it("should require a room", function() {
      return createNewDevice.handler({
        "name": "test_" + Math.random(),
        "type": "light"
      }).should.eventually.be.rejected;
    });
    it("should require a type", function() {
      return createNewDevice.handler({
        "name": "test_" + Math.random(),
        "room": "MyLivingRoom",
      }).should.eventually.be.rejected;
    });
  });

  describe("GetDeviceByName", function() {
    it("should complete normally", function() {
      return getDeviceByName.handler({
        name: "b7aae05e-39e2-4385-85f4-a5914bc33d93"
      })
      .should.be.fulfilled
      .and.eventually.have.property("status");
    });
  });

  describe("PutDeviceForName", function() {
    it("should complete normally", function() {
      putDeviceForName.handler({
        name: "b7aae05e-39e2-4385-85f4-a5914bc33d93",
        room: "DavidsRoom",
        type: "light"
      }).catch(function(err) {
        console.error(err);
      }).should.be.fulfilled
      .and.eventually.have.property("status");
    })
  })
})
<commit_msg>Added error check for put, tracking failed test for put<commit_after>'use strict';
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
chai.should();

var assert = require('assert');
var createNewDevice = require('../lib/handlers/CreateNewDevice');
var getDeviceByName = require('../lib/handlers/GetDeviceByName');
var putDeviceForName = require('../lib/handlers/PutDeviceForName');

describe("Aws calls", function() {
  describe('CreateNewDevice', function () {
    // it("should create a simple object", function() {
    //   return createNewDevice.handler({
    //     "name": "test_" + Math.random(),
    //     "room": "MyLivingRoom",
    //     "type": "light"
    //   }).should.be.fulfilled
    //   .and.eventually.have.property("status");
    // });
    it("should have a private file with data", function() {
      var priv = require('../lib/handlers/CreateNewDevice/private');
      assert(priv, "Private file exists.")
      assert(priv.mqtt.url)
      assert(priv.mqtt.username)
      assert(priv.mqtt.password)
    })
    it("should require a name", function() {
      return createNewDevice.handler({
        "room": "MyLivingRoom",
        "type": "light"
      }).should.eventually.be.rejected;
    });
    it("should require a room", function() {
      return createNewDevice.handler({
        "name": "test_" + Math.random(),
        "type": "light"
      }).should.eventually.be.rejected;
    });
    it("should require a type", function() {
      return createNewDevice.handler({
        "name": "test_" + Math.random(),
        "room": "MyLivingRoom",
      }).should.eventually.be.rejected;
    });
  });

  describe("GetDeviceByName", function() {
    it("should complete normally", function() {
      return getDeviceByName.handler({
        name: "b7aae05e-39e2-4385-85f4-a5914bc33d93"
      })
      .should.be.fulfilled
      .and.eventually.have.property("status");
    });
  });

  describe("PutDeviceForName", function() {
    it("should complete normally", function() {
      putDeviceForName.handler({
        name: "b7aae05e-39e2-4385-85f4-a5914bc33d93",
        room: "DavidsRoom",
        type: "light"
      }).catch(function(err) {
        console.error(err);
      }).should.eventally.be.fulfilled
      .and.eventually.have.property("status");
    })
  })
})
<|endoftext|>


<commit_before>import isPromise from './isPromise.js';

/**
 * For TypeScript support: Remember to check and make sure
 * that `index.d.ts` is also up to date with the implementation.
 */
export const ActionType = {
  Pending: 'PENDING',
  Fulfilled: 'FULFILLED',
  Rejected: 'REJECTED',
};

/**
 * Function: createPromise
 * Description: The main createPromise accepts a configuration
 * object and returns the middleware.
 */
export function createPromise(config = {}) {
  const defaultTypes = [ActionType.Pending, ActionType.Fulfilled, ActionType.Rejected];
  const PROMISE_TYPE_SUFFIXES = config.promiseTypeSuffixes || defaultTypes;
  const PROMISE_TYPE_DELIMITER = config.promiseTypeDelimiter || '_';

  return ref => {
    const { dispatch } = ref;

    return next => action => {

      /**
       * Instantiate variables to hold:
       * (1) the promise
       * (2) the data for optimistic updates
       */
      let promise;
      let data;

      /**
       * There are multiple ways to dispatch a promise. The first step is to
       * determine if the promise is defined:
       * (a) explicitly (action.payload.promise is the promise)
       * (b) implicitly (action.payload is the promise)
       * (c) as an async function (returns a promise when called)
       *
       * If the promise is not defined in one of these three ways, we don't do
       * anything and move on to the next middleware in the middleware chain.
       */

      // Step 1a: Is there a payload?
      if (action.payload) {
        const PAYLOAD = action.payload;

        // Step 1.1: Is the promise implicitly defined?
        if (isPromise(PAYLOAD)) {
          promise = PAYLOAD;
        }

        // Step 1.2: Is the promise explicitly defined?
        else if (isPromise(PAYLOAD.promise)) {
          promise = PAYLOAD.promise;
          data = PAYLOAD.data;
        }

        // Step 1.3: Is the promise returned by an async function?
        else if (
          typeof PAYLOAD === 'function' ||
          typeof PAYLOAD.promise === 'function'
        ) {
          promise = PAYLOAD.promise ? PAYLOAD.promise() : PAYLOAD();
          data = PAYLOAD.promise ? PAYLOAD.data : undefined;

          // Step 1.3.1: Is the return of action.payload a promise?
          if (!isPromise(promise)) {

            // If not, move on to the next middleware.
            return next({
              ...action,
              payload: promise
            });
          }
        }

        // Step 1.4: If there's no promise, move on to the next middleware.
        else {
          return next(action);
        }

      // Step 1b: If there's no payload, move on to the next middleware.
      } else {
        return next(action);
      }

      /**
       * Instantiate and define constants for:
       * (1) the action type
       * (2) the action meta
       */
      const TYPE = action.type;
      const META = action.meta;

      /**
       * Instantiate and define constants for the action type suffixes.
       * These are appended to the end of the action type.
       */
      const [
        PENDING,
        FULFILLED,
        REJECTED
      ] = PROMISE_TYPE_SUFFIXES;

      /**
       * Function: getAction
       * Description: This function constructs and returns a rejected
       * or fulfilled action object. The action object is based off the Flux
       * Standard Action (FSA).
       *
       * Given an original action with the type FOO:
       *
       * The rejected object model will be:
       * {
       *   error: true,
       *   type: 'FOO_REJECTED',
       *   payload: ...,
       *   meta: ... (optional)
       * }
       *
       * The fulfilled object model will be:
       * {
       *   type: 'FOO_FULFILLED',
       *   payload: ...,
       *   meta: ... (optional)
       * }
       */
      const getAction = (newPayload, isRejected) => ({
        // Concatenate the type string property.
        type: [
          TYPE,
          isRejected ? REJECTED : FULFILLED
        ].join(PROMISE_TYPE_DELIMITER),

        // Include the payload property.
        ...((newPayload === null || typeof newPayload === 'undefined') ? {} : {
          payload: newPayload
        }),

        // If the original action includes a meta property, include it.
        ...(META !== undefined ? { meta: META } : {}),

        // If the action is rejected, include an error property.
        ...(isRejected ? {
          error: true
        } : {})
      });

      /**
       * Function: handleReject
       * Calls: getAction to construct the rejected action
       * Description: This function dispatches the rejected action and returns
       * the original Error object. Please note the developer is responsible
       * for constructing and throwing an Error object. The middleware does not
       * construct any Errors.
       */
      const handleReject = reason => {
        const rejectedAction = getAction(reason, true);
        dispatch(rejectedAction);

        throw reason;
      };

      /**
       * Function: handleFulfill
       * Calls: getAction to construct the fullfilled action
       * Description: This function dispatches the fulfilled action and
       * returns the success object. The success object should
       * contain the value and the dispatched action.
       */
      const handleFulfill = (value = null) => {
        const resolvedAction = getAction(value, false);
        dispatch(resolvedAction);

        return { value, action: resolvedAction };
      };

      /**
       * First, dispatch the pending action:
       * This object describes the pending state of a promise and will include
       * any data (for optimistic updates) and/or meta from the original action.
       */
      next({
        // Concatenate the type string.
        type: [TYPE, PENDING].join(PROMISE_TYPE_DELIMITER),

        // Include payload (for optimistic updates) if it is defined.
        ...(data !== undefined ? { payload: data } : {}),

        // Include meta data if it is defined.
        ...(META !== undefined ? { meta: META } : {})
      });

      /**
       * Second, dispatch a rejected or fulfilled action and move on to the
       * next middleware.
       */
      return promise.then(handleFulfill, handleReject);
    };
  };
}

export default function middleware({ dispatch } = {}) {
  if (typeof dispatch === 'function') {
    return createPromise()({ dispatch });
  }

  if (process && process.env && (process.env.NODE_ENV === 'development' || 'test')) {
    // eslint-disable-next-line no-console
    console.warn(`Redux Promise Middleware: As of version 6.0.0, the \
middleware library supports both preconfigured and custom configured \
middleware. To use a custom configuration, use the "createPromise" export \
and call this function with your configuration property. To use a \
preconfiguration, use the default export. For more help, check the upgrading \
guide: https://docs.psb.design/redux-promise-middleware/upgrade-guides/v6

For custom configuration:
import { createPromise } from 'redux-promise-middleware';
const promise = createPromise({ types: { fulfilled: 'success' } });
applyMiddleware(promise);

For preconfiguration:
import promise from 'redux-promise-middleware';
applyMiddleware(promise);
    `);
  }

  return null;
}
<commit_msg>Fix removing warning from production build (#256)<commit_after>import isPromise from './isPromise.js';

/**
 * For TypeScript support: Remember to check and make sure
 * that `index.d.ts` is also up to date with the implementation.
 */
export const ActionType = {
  Pending: 'PENDING',
  Fulfilled: 'FULFILLED',
  Rejected: 'REJECTED',
};

/**
 * Function: createPromise
 * Description: The main createPromise accepts a configuration
 * object and returns the middleware.
 */
export function createPromise(config = {}) {
  const defaultTypes = [ActionType.Pending, ActionType.Fulfilled, ActionType.Rejected];
  const PROMISE_TYPE_SUFFIXES = config.promiseTypeSuffixes || defaultTypes;
  const PROMISE_TYPE_DELIMITER = config.promiseTypeDelimiter || '_';

  return ref => {
    const { dispatch } = ref;

    return next => action => {

      /**
       * Instantiate variables to hold:
       * (1) the promise
       * (2) the data for optimistic updates
       */
      let promise;
      let data;

      /**
       * There are multiple ways to dispatch a promise. The first step is to
       * determine if the promise is defined:
       * (a) explicitly (action.payload.promise is the promise)
       * (b) implicitly (action.payload is the promise)
       * (c) as an async function (returns a promise when called)
       *
       * If the promise is not defined in one of these three ways, we don't do
       * anything and move on to the next middleware in the middleware chain.
       */

      // Step 1a: Is there a payload?
      if (action.payload) {
        const PAYLOAD = action.payload;

        // Step 1.1: Is the promise implicitly defined?
        if (isPromise(PAYLOAD)) {
          promise = PAYLOAD;
        }

        // Step 1.2: Is the promise explicitly defined?
        else if (isPromise(PAYLOAD.promise)) {
          promise = PAYLOAD.promise;
          data = PAYLOAD.data;
        }

        // Step 1.3: Is the promise returned by an async function?
        else if (
          typeof PAYLOAD === 'function' ||
          typeof PAYLOAD.promise === 'function'
        ) {
          promise = PAYLOAD.promise ? PAYLOAD.promise() : PAYLOAD();
          data = PAYLOAD.promise ? PAYLOAD.data : undefined;

          // Step 1.3.1: Is the return of action.payload a promise?
          if (!isPromise(promise)) {

            // If not, move on to the next middleware.
            return next({
              ...action,
              payload: promise
            });
          }
        }

        // Step 1.4: If there's no promise, move on to the next middleware.
        else {
          return next(action);
        }

      // Step 1b: If there's no payload, move on to the next middleware.
      } else {
        return next(action);
      }

      /**
       * Instantiate and define constants for:
       * (1) the action type
       * (2) the action meta
       */
      const TYPE = action.type;
      const META = action.meta;

      /**
       * Instantiate and define constants for the action type suffixes.
       * These are appended to the end of the action type.
       */
      const [
        PENDING,
        FULFILLED,
        REJECTED
      ] = PROMISE_TYPE_SUFFIXES;

      /**
       * Function: getAction
       * Description: This function constructs and returns a rejected
       * or fulfilled action object. The action object is based off the Flux
       * Standard Action (FSA).
       *
       * Given an original action with the type FOO:
       *
       * The rejected object model will be:
       * {
       *   error: true,
       *   type: 'FOO_REJECTED',
       *   payload: ...,
       *   meta: ... (optional)
       * }
       *
       * The fulfilled object model will be:
       * {
       *   type: 'FOO_FULFILLED',
       *   payload: ...,
       *   meta: ... (optional)
       * }
       */
      const getAction = (newPayload, isRejected) => ({
        // Concatenate the type string property.
        type: [
          TYPE,
          isRejected ? REJECTED : FULFILLED
        ].join(PROMISE_TYPE_DELIMITER),

        // Include the payload property.
        ...((newPayload === null || typeof newPayload === 'undefined') ? {} : {
          payload: newPayload
        }),

        // If the original action includes a meta property, include it.
        ...(META !== undefined ? { meta: META } : {}),

        // If the action is rejected, include an error property.
        ...(isRejected ? {
          error: true
        } : {})
      });

      /**
       * Function: handleReject
       * Calls: getAction to construct the rejected action
       * Description: This function dispatches the rejected action and returns
       * the original Error object. Please note the developer is responsible
       * for constructing and throwing an Error object. The middleware does not
       * construct any Errors.
       */
      const handleReject = reason => {
        const rejectedAction = getAction(reason, true);
        dispatch(rejectedAction);

        throw reason;
      };

      /**
       * Function: handleFulfill
       * Calls: getAction to construct the fullfilled action
       * Description: This function dispatches the fulfilled action and
       * returns the success object. The success object should
       * contain the value and the dispatched action.
       */
      const handleFulfill = (value = null) => {
        const resolvedAction = getAction(value, false);
        dispatch(resolvedAction);

        return { value, action: resolvedAction };
      };

      /**
       * First, dispatch the pending action:
       * This object describes the pending state of a promise and will include
       * any data (for optimistic updates) and/or meta from the original action.
       */
      next({
        // Concatenate the type string.
        type: [TYPE, PENDING].join(PROMISE_TYPE_DELIMITER),

        // Include payload (for optimistic updates) if it is defined.
        ...(data !== undefined ? { payload: data } : {}),

        // Include meta data if it is defined.
        ...(META !== undefined ? { meta: META } : {})
      });

      /**
       * Second, dispatch a rejected or fulfilled action and move on to the
       * next middleware.
       */
      return promise.then(handleFulfill, handleReject);
    };
  };
}

export default function middleware({ dispatch } = {}) {
  if (typeof dispatch === 'function') {
    return createPromise()({ dispatch });
  }

  if (process && process.env && process.env.NODE_ENV !== 'production') {
    // eslint-disable-next-line no-console
    console.warn(`Redux Promise Middleware: As of version 6.0.0, the \
middleware library supports both preconfigured and custom configured \
middleware. To use a custom configuration, use the "createPromise" export \
and call this function with your configuration property. To use a \
preconfiguration, use the default export. For more help, check the upgrading \
guide: https://docs.psb.design/redux-promise-middleware/upgrade-guides/v6

For custom configuration:
import { createPromise } from 'redux-promise-middleware';
const promise = createPromise({ types: { fulfilled: 'success' } });
applyMiddleware(promise);

For preconfiguration:
import promise from 'redux-promise-middleware';
applyMiddleware(promise);
    `);
  }

  return null;
}
<|endoftext|>


<commit_before>var through = require('through2');
var gutil = require('gulp-util');
var http = require('http');
var https = require('https');
var connect = require('connect');
var serveStatic = require('serve-static');
var connectLivereload = require('connect-livereload');
var proxy = require('proxy-middleware');
var tinyLr = require('tiny-lr');
var watch = require('watch');
var fs = require('fs');
var serveIndex = require('serve-index');
var path = require('path');
var open = require('open');
var url = require('url');
var extend = require('node.extend');
var enableMiddlewareShorthand = require('./enableMiddlewareShorthand');

module.exports = function(options) {

  var defaults = {

    /**
     *
     * BASIC DEFAULTS
     *
     **/

    host: 'localhost',
    port: 8000,
    fallback: false,
    https: false,
    open: false,

    /**
     *
     * MIDDLEWARE DEFAULTS
     *
     * NOTE:
     *  All middleware should defaults should have the 'enable'
     *  property if you want to support shorthand syntax like:
     *
     *    webserver({
     *      livereload: true
     *    });
     *
     */

    // Middleware: Livereload
    livereload: {
      enable: false,
      port: 35729,
      filter: function (filename) {
        if (filename.match(/node_modules/)) {
          return false;
        } else { return true; }
      }
    },

    // Middleware: Directory listing
    // For possible options, see:
    //  https://github.com/expressjs/serve-index
    directoryListing: {
      enable: false,
      path: './',
      options: undefined
    },

    // Middleware: Proxy
    // For possible options, see:
    //  https://github.com/andrewrk/connect-proxy
    proxies: []

  };

  // Deep extend user provided options over the all of the defaults
  // Allow shorthand syntax, using the enable property as a flag
  var config = enableMiddlewareShorthand(defaults, options, [
    'directoryListing',
    'livereload'
  ]);

  if (typeof config.open === 'string' && config.open.length > 0) {
    // ensure leading slash
    config.open = (config.open.indexOf('/') !== 0 ? '/' : '') + config.open;
  }

  var app = connect();

  var openInBrowser = function() {
    if (config.open === false) return;
    if (config.open.indexOf('http') === 0) {
      // if this is a complete url form
      open(config.open);
      return;
    }
    open('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port + (typeof config.open === 'string' ? config.open : ''));
  };

  var lrServer;

  if (config.livereload.enable) {

    app.use(connectLivereload({
      port: config.livereload.port
    }));

    if (config.https) {
      if (config.https.pfx) {
        lrServer = tinyLr({
          pfx: fs.readFileSync(config.https.pfx),
          passphrase: config.https.passphrase
        });
      }
      else {
        lrServer = tinyLr({
          key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
          cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
        });
      }
    } else {
      lrServer = tinyLr();
    }

    lrServer.listen(config.livereload.port, config.host);

  }

  if (config.directoryListing.enable) {
    app.use(serveIndex(path.resolve(config.directoryListing.path), config.directoryListing.options));
  }

  // Proxy requests
  for (var i = 0, len = config.proxies.length; i < len; i++) {
    var proxyoptions = url.parse(config.proxies[i].target);
    if (config.proxies[i].hasOwnProperty('options')) {
      extend(proxyoptions, config.proxies[i].options);
    }
    app.use(config.proxies[i].source, proxy(proxyoptions));
  }

  var files = [];

  // Create server
  var stream = through.obj(function(file, enc, callback) {

    app.use(serveStatic(file.path));

    if (config.livereload.enable) {
      var watchOptions = {
        ignoreDotFiles: true,
        filter: config.livereload.filter
      };
      watch.watchTree(file.path, watchOptions, function (filename) {
        lrServer.changed({
          body: {
            files: filename
          }
        });

      });
    }

    this.push(file);
    callback();
  })
  .on('data', function(f){files.push(f);})
  .on('end', function(){
    if (config.fallback) {
      files.forEach(function(file){
        var fallbackFile = file.path + '/' + config.fallback;
        if (fs.existsSync(fallbackFile)) {
          app.use(function(req, res) {
            res.setHeader('Content-Type', 'text/html; charset=UTF-8');
            fs.createReadStream(fallbackFile).pipe(res);
          });
        }
      });
    }
  });

  var webserver;

  if (config.https) {
    var opts;

    if (config.https.pfx) {
      opts = {
        pfx: fs.readFileSync(config.https.pfx),
        passphrase: config.https.passphrase
      };
    } else {
      opts = {
        key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
        cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
      };
    }
    webserver = https.createServer(opts, app).listen(config.port, config.host, openInBrowser);
  } else {
    webserver = http.createServer(app).listen(config.port, config.host, openInBrowser);
  }

  gutil.log('Webserver started at', gutil.colors.cyan('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port));

  stream.on('kill', function() {

    webserver.close();

    if (config.livereload.enable) {
      lrServer.close();
    }

  });

  return stream;

};
<commit_msg>fix partial and complete url problems<commit_after>var through = require('through2');
var gutil = require('gulp-util');
var http = require('http');
var https = require('https');
var connect = require('connect');
var serveStatic = require('serve-static');
var connectLivereload = require('connect-livereload');
var proxy = require('proxy-middleware');
var tinyLr = require('tiny-lr');
var watch = require('watch');
var fs = require('fs');
var serveIndex = require('serve-index');
var path = require('path');
var open = require('open');
var url = require('url');
var extend = require('node.extend');
var enableMiddlewareShorthand = require('./enableMiddlewareShorthand');

module.exports = function(options) {

  var defaults = {

    /**
     *
     * BASIC DEFAULTS
     *
     **/

    host: 'localhost',
    port: 8000,
    fallback: false,
    https: false,
    open: false,

    /**
     *
     * MIDDLEWARE DEFAULTS
     *
     * NOTE:
     *  All middleware should defaults should have the 'enable'
     *  property if you want to support shorthand syntax like:
     *
     *    webserver({
     *      livereload: true
     *    });
     *
     */

    // Middleware: Livereload
    livereload: {
      enable: false,
      port: 35729,
      filter: function (filename) {
        if (filename.match(/node_modules/)) {
          return false;
        } else { return true; }
      }
    },

    // Middleware: Directory listing
    // For possible options, see:
    //  https://github.com/expressjs/serve-index
    directoryListing: {
      enable: false,
      path: './',
      options: undefined
    },

    // Middleware: Proxy
    // For possible options, see:
    //  https://github.com/andrewrk/connect-proxy
    proxies: []

  };

  // Deep extend user provided options over the all of the defaults
  // Allow shorthand syntax, using the enable property as a flag
  var config = enableMiddlewareShorthand(defaults, options, [
    'directoryListing',
    'livereload'
  ]);

  if (typeof config.open === 'string' && config.open.length > 0 && config.open.indexOf('http') !== 0) {
    // ensure leading slash if this is NOT a complete url form
    config.open = (config.open.indexOf('/') !== 0 ? '/' : '') + config.open;
  }

  var app = connect();

  var openInBrowser = function() {
    if (config.open === false) return;
    if (typeof config.open === 'string' && config.open.indexOf('http') === 0) {
      // if this is a complete url form
      open(config.open);
      return;
    }
    open('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port + (typeof config.open === 'string' ? config.open : ''));
  };

  var lrServer;

  if (config.livereload.enable) {

    app.use(connectLivereload({
      port: config.livereload.port
    }));

    if (config.https) {
      if (config.https.pfx) {
        lrServer = tinyLr({
          pfx: fs.readFileSync(config.https.pfx),
          passphrase: config.https.passphrase
        });
      }
      else {
        lrServer = tinyLr({
          key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
          cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
        });
      }
    } else {
      lrServer = tinyLr();
    }

    lrServer.listen(config.livereload.port, config.host);

  }

  if (config.directoryListing.enable) {
    app.use(serveIndex(path.resolve(config.directoryListing.path), config.directoryListing.options));
  }

  // Proxy requests
  for (var i = 0, len = config.proxies.length; i < len; i++) {
    var proxyoptions = url.parse(config.proxies[i].target);
    if (config.proxies[i].hasOwnProperty('options')) {
      extend(proxyoptions, config.proxies[i].options);
    }
    app.use(config.proxies[i].source, proxy(proxyoptions));
  }

  var files = [];

  // Create server
  var stream = through.obj(function(file, enc, callback) {

    app.use(serveStatic(file.path));

    if (config.livereload.enable) {
      var watchOptions = {
        ignoreDotFiles: true,
        filter: config.livereload.filter
      };
      watch.watchTree(file.path, watchOptions, function (filename) {
        lrServer.changed({
          body: {
            files: filename
          }
        });

      });
    }

    this.push(file);
    callback();
  })
  .on('data', function(f){files.push(f);})
  .on('end', function(){
    if (config.fallback) {
      files.forEach(function(file){
        var fallbackFile = file.path + '/' + config.fallback;
        if (fs.existsSync(fallbackFile)) {
          app.use(function(req, res) {
            res.setHeader('Content-Type', 'text/html; charset=UTF-8');
            fs.createReadStream(fallbackFile).pipe(res);
          });
        }
      });
    }
  });

  var webserver;

  if (config.https) {
    var opts;

    if (config.https.pfx) {
      opts = {
        pfx: fs.readFileSync(config.https.pfx),
        passphrase: config.https.passphrase
      };
    } else {
      opts = {
        key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
        cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
      };
    }
    webserver = https.createServer(opts, app).listen(config.port, config.host, openInBrowser);
  } else {
    webserver = http.createServer(app).listen(config.port, config.host, openInBrowser);
  }

  gutil.log('Webserver started at', gutil.colors.cyan('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port));

  stream.on('kill', function() {

    webserver.close();

    if (config.livereload.enable) {
      lrServer.close();
    }

  });

  return stream;

};
<|endoftext|>


<commit_before>/**************************************\
                Config
\**************************************/
var APP_ID = 'amzn1.echo-sdk-ams.app.xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; //replace with your amazon app ID
var appToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; //replace with your LIFX app token
var dimString = ["dim", "lower", "decrease", "down"]; //strings to dim the lights as setup in the utterances
var brightString = ["bright", "brighten", "increase", "raise", "up"]; //strings to brighten the lights as setup in the utterances
var enableFeedback = true; //whether or not you want Alexa to tell you she changed the lights

/**************************************\
                Globals
\**************************************/
var https = require('https');
var querystring = require('querystring');
var brightness = 0.00;
var addProcess = false;
var AlexaSkill = require('./AlexaSkill');
var urlPrefix = '/v1/lights/';
var intentEnum = {
    BRIGHTNESS: 0,
    POWER: 1,
    COLOR: 2,
    SCENE: 3
};
var currentIntent = intentEnum.BRIGHTNESS;

/**
 * LIFX is a child of AlexaSkill.
 * To read more about inheritance in JavaScript, see the link below.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance
 */
var LIFX = function() {
    AlexaSkill.call(this, APP_ID);
};
// Extend AlexaSkill
LIFX.prototype = Object.create(AlexaSkill.prototype);
LIFX.prototype.constructor = LIFX;
LIFX.prototype.eventHandlers.onSessionStarted = function(sessionStartedRequest, session) {
    console.log("LIFX onSessionStarted requestId: " + sessionStartedRequest.requestId + ", sessionId: " + session.sessionId);
    // any session init logic would go here
};
LIFX.prototype.eventHandlers.onLaunch = function(launchRequest, session, response) {
    console.log("LIFX onLaunch requestId: " + launchRequest.requestId + ", sessionId: " + session.sessionId);
    var launchText = "How would you like to control your lights?";
    response.ask(launchText);
};
LIFX.prototype.eventHandlers.onSessionEnded = function(sessionEndedRequest, session) {
    console.log("onSessionEnded requestId: " + sessionEndedRequest.requestId + ", sessionId: " + session.sessionId);
    // any session cleanup logic would go here
};
LIFX.prototype.intentHandlers = {
    AdjustBrightness: function(intent, session, response) {
        currentIntent = intentEnum.BRIGHTNESS;
        generateRequest(intent, session, response);
    },
    AdjustPower: function(intent, session, response) {
        currentIntent = intentEnum.POWER;
        generateRequest(intent, session, response);
    },
    AdjustColor: function(intent, session, response) {
        currentIntent = intentEnum.COLOR;
        generateRequest(intent, session, response);
    },
    AdjustScene: function(intent, session, response) {
        currentIntent = intentEnum.SCENE;
        generateRequest(intent, session, response);
    }
};
//Prepares the request to be sent to the LIFX server
function generateRequest(intent, session, response) {
    var intentName = String(intent.name).toLowerCase();
    var url = "";
	var selector = "/";
    var methodType = "";
    var bodyString = "";
    var speechOutput = "An error has occured.";
	var selectorFirstSlot = intent.slots.SelectorFirst;
	var selectorSecondSlot = intent.slots.SelectorSecond;
	var numSelectors = 0;
	if (selectorFirstSlot && selectorFirstSlot.value)
	{
		numSelectors = 1;
		selector = selector + 'label:' + selectorFirstSlot.value.capitalize();
		if (selectorSecondSlot && selectorSecondSlot.value)
		{
			selector = selector + ',label:' + selectorSecondSlot.value.capitalize();
			numSelectors = 2;
		}
	}
	else
	{
		selector = selector + 'all';
	}
	console.log("Selector: " + selector);
    switch (currentIntent) {

        case intentEnum.BRIGHTNESS:
            {
                url = urlPrefix + selector + '/state';
                methodType = 'PUT';
                var brightnessSlot = intent.slots.Brightness;
                var adjustmentSlot = intent.slots.Adjustment;
                var brightnessValue = 0.5;

                if (brightnessSlot && brightnessSlot.value) { //if utterance contains a specified value
                    brightnessValue = brightnessSlot.value / 100.0;
                    speechOutput = "I have set the brightness to " + (brightnessValue * 100) + " percent.";
                }
                if (adjustmentSlot && adjustmentSlot.value) { //if utterance contains a dim/brighten request
                    addProcess = true;
                    parseBrightness(intent, response, url); //gets current brightness to dim/brighten with a shift
                }
                bodyString = JSON.stringify({
                    "brightness": + brightnessValue
                });
                break;
            }
        case intentEnum.POWER:
            {
                var powerSlot = intent.slots.State
                if (powerSlot && powerSlot.value) { //if utterance contains an on/off request
                    url = urlPrefix + selector + '/state';
                    methodType = 'PUT';
                    var state = String(powerSlot.value).toLowerCase();
                    bodyString = JSON.stringify({
                        "power": state
                    });
					if(numSelectors == 1){
					speechOutput = "I have turned " + String(selectorFirstSlot.value) + " " + state + ".";
					}
					else if(numSelectors == 2){
					speechOutput = "I have turned " + String(selectorFirstSlot.value) + " and " + String(selectorSecondSlot.value) + " " + state + ".";
					}
					else{
					speechOutput = "I have turned the lights " + state + ".";
					}
					}
					else { //if no specific request, toggle the lights
                    url = urlPrefix + '/all' + '/toggle';
                    methodType = 'POST';
                    bodyString = JSON.stringify({});
                    speechOutput = "I have toggled the lights.";
                }
                break;
            }
        case intentEnum.COLOR:
            {
                url = urlPrefix + selector + '/state';
                methodType = 'PUT';
                var color = String(intent.slots.Color.value).toLowerCase();
                bodyString = JSON.stringify({
                    "color": color
                });
                speechOutput = "I have set color to " + color + ".";
                break;
            }
        case intentEnum.SCENE:
            {
				addProcess = true;
				parseScenes(intent,response);
                break;
            }
        default:
            {
                speechOutput = "That was not a valid command, please try again.";
            }
    }
    if (!addProcess) { //no additional processing required (ie no brightness shift nor scene selection)
        sendRequest(url, methodType, bodyString, speechOutput, response); //send generated request to LIFX server
    }
}

function sendRequest(url, methodType, bodyString, speechOutput, response) {
    var post_options = {
        host: 'api.lifx.com',
        port: '443',
        path: url,
        method: methodType,
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(bodyString),
            Authorization: 'Bearer ' + appToken
        }
    };
    // Set up the request
    var post_req = https.request(post_options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            if (enableFeedback) response.tell(speechOutput);
        });
    });
    post_req.on('error', function(e) {});
    // post the data
    post_req.write(bodyString);
    post_req.end();
}

function parseBrightness(intent, response, url) {
    var post_options = {
        host: 'api.lifx.com',
        port: '443',
        path: url,
        method: 'GET',
        headers: {
            Authorization: 'Bearer ' + appToken
        }
    };
    var text = "";
    var req = https.request(post_options, function(res) {
        res.setEncoding('utf8');

        res.on('data', function(chunk) {
            text += chunk;
        });

        res.on('end', function() {
            //text = text.substring(1,text.length-1);
            var obj = JSON.parse(text);
            var bright = obj[0].brightness;
            var url = urlPrefix + '/color';
            var methodType = 'PUT';
            var adjustmentSlot = intent.slots.Adjustment;
            var brightnessValue = 0.5;
            if (dimString.indexOf(String(adjustmentSlot.value).toLowerCase()) > -1) { //if dim command recognized
                if (bright >= 0.1) { //lower the brightness by 10%
                    brightnessValue = bright - 0.1;
                    speechOutput = "I have lowered the brightness by ten percent.";
                } else { //brightness too low, setting to 1%
                    brightnessValue = 0.01;
                    speechOutput = "I have set the brightness to one percent.";
                }
            }
            if (brightString.indexOf(String(adjustmentSlot.value).toLowerCase()) > -1) { //if brighten command recognized
                if (bright <= 1.0) { //raise brightness by 10%
                    brightnessValue = bright + 0.1;
                    speechOutput = "I have raised the brightness by ten percent.";
                } else { //brightness too high, setting to 100%
                    brightnessValue = 1.0;
                    speechOutput = "I have set the brightness to one hundred percent.";
                }

            }
            bodyString = JSON.stringify({
                "color": "brightness:" + brightnessValue
            });
            sendRequest(url, methodType, bodyString, speechOutput, response); //send generated request to LIFX server
        });
    });

    req.on('error', function(err) {});

    req.end();

}

function parseScenes(intent, response) {
    var post_options = {
        host: 'api.lifx.com',
        port: '443',
        path: '/v1/scenes',
        method: 'GET',
        headers: {
            Authorization: 'Bearer ' + appToken
        }
    };
	var sceneName = String(intent.slots.Scene.value).toLowerCase();
    var text = "";
    var req = https.request(post_options, function(res) {
        res.setEncoding('utf8');

        res.on('data', function(chunk) {
            text += chunk;
        });

        res.on('end', function() {
			console.log(sceneName);
            var obj = JSON.parse(text);
			var scene = obj[0].uuid;
			for(i = 0; i < Object.keys(obj).length;i++)
			{
				if(sceneName.indexOf(obj[i].name.toLowerCase()) > -1)
				{
					scene = obj[i].uuid;
					break;
				}
			}
            var url = '/v1/scenes/scene_id:' + scene + '/activate';
            var methodType = 'PUT';
            bodyString = JSON.stringify({
            });
			speechOutput = "I have set the scene to " + sceneName + ".";
            sendRequest(url, methodType, bodyString, speechOutput, response); //send generated request to LIFX server
        });
    });

    req.on('error', function(err) {});

    req.end();

}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
// Create the handler that responds to the Alexa Request.
exports.handler = function(event, context) {
    // Create an instance of the LIFX Skill.
    var skill = new LIFX();
    skill.execute(event, context);
};<commit_msg>Fixing brightness shifting<commit_after>/**************************************\
                Config
\**************************************/
var APP_ID = 'amzn1.echo-sdk-ams.app.xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; //replace with your amazon app ID
var appToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; //replace with your LIFX app token
var dimString = ["dim", "lower", "decrease", "down"]; //strings to dim the lights as setup in the utterances
var brightString = ["bright", "brighten", "increase", "raise", "up"]; //strings to brighten the lights as setup in the utterances
var enableFeedback = true; //whether or not you want Alexa to tell you she changed the lights

/**************************************\
                Globals
\**************************************/
var https = require('https');
var querystring = require('querystring');
var brightness = 0.00;
var addProcess = false;
var AlexaSkill = require('./AlexaSkill');
var urlPrefix = '/v1/lights/';
var intentEnum = {
    BRIGHTNESS: 0,
    POWER: 1,
    COLOR: 2,
    SCENE: 3
};
var currentIntent = intentEnum.BRIGHTNESS;

/**
 * LIFX is a child of AlexaSkill.
 * To read more about inheritance in JavaScript, see the link below.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance
 */
var LIFX = function() {
    AlexaSkill.call(this, APP_ID);
};
// Extend AlexaSkill
LIFX.prototype = Object.create(AlexaSkill.prototype);
LIFX.prototype.constructor = LIFX;
LIFX.prototype.eventHandlers.onSessionStarted = function(sessionStartedRequest, session) {
    console.log("LIFX onSessionStarted requestId: " + sessionStartedRequest.requestId + ", sessionId: " + session.sessionId);
    // any session init logic would go here
};
LIFX.prototype.eventHandlers.onLaunch = function(launchRequest, session, response) {
    console.log("LIFX onLaunch requestId: " + launchRequest.requestId + ", sessionId: " + session.sessionId);
    var launchText = "How would you like to control your lights?";
    response.ask(launchText);
};
LIFX.prototype.eventHandlers.onSessionEnded = function(sessionEndedRequest, session) {
    console.log("onSessionEnded requestId: " + sessionEndedRequest.requestId + ", sessionId: " + session.sessionId);
    // any session cleanup logic would go here
};
LIFX.prototype.intentHandlers = {
    AdjustBrightness: function(intent, session, response) {
        currentIntent = intentEnum.BRIGHTNESS;
        generateRequest(intent, session, response);
    },
    AdjustPower: function(intent, session, response) {
        currentIntent = intentEnum.POWER;
        generateRequest(intent, session, response);
    },
    AdjustColor: function(intent, session, response) {
        currentIntent = intentEnum.COLOR;
        generateRequest(intent, session, response);
    },
    AdjustScene: function(intent, session, response) {
        currentIntent = intentEnum.SCENE;
        generateRequest(intent, session, response);
    }
};
//Prepares the request to be sent to the LIFX server
function generateRequest(intent, session, response) {
    var intentName = String(intent.name).toLowerCase();
    var url = "";
	var selector = "/";
    var methodType = "";
    var bodyString = "";
    var speechOutput = "An error has occured.";
	var selectorFirstSlot = intent.slots.SelectorFirst;
	var selectorSecondSlot = intent.slots.SelectorSecond;
	var numSelectors = 0;
	if (selectorFirstSlot && selectorFirstSlot.value)
	{
		numSelectors = 1;
		selector = selector + 'label:' + selectorFirstSlot.value.capitalize();
		if (selectorSecondSlot && selectorSecondSlot.value)
		{
			selector = selector + ',label:' + selectorSecondSlot.value.capitalize();
			numSelectors = 2;
		}
	}
	else
	{
		selector = selector + 'all';
	}
	console.log("Selector: " + selector);
    switch (currentIntent) {

        case intentEnum.BRIGHTNESS:
            {
                url = urlPrefix + selector + '/state';
                methodType = 'PUT';
                var brightnessSlot = intent.slots.Brightness;
                var adjustmentSlot = intent.slots.Adjustment;
                var brightnessValue = 0.5;

                if (brightnessSlot && brightnessSlot.value) { //if utterance contains a specified value
                    brightnessValue = brightnessSlot.value / 100.0;
                    speechOutput = "I have set the brightness to " + (brightnessValue * 100) + " percent.";
                }
                if (adjustmentSlot && adjustmentSlot.value) { //if utterance contains a dim/brighten request
                    addProcess = true;
                    parseBrightness(intent, response, urlPrefix+selector); //gets current brightness to dim/brighten with a shift
                }
                bodyString = JSON.stringify({
                    "brightness": + brightnessValue
                });
                break;
            }
        case intentEnum.POWER:
            {
                var powerSlot = intent.slots.State
                if (powerSlot && powerSlot.value) { //if utterance contains an on/off request
                    url = urlPrefix + selector + '/state';
                    methodType = 'PUT';
                    var state = String(powerSlot.value).toLowerCase();
                    bodyString = JSON.stringify({
                        "power": state
                    });
					if(numSelectors == 1){
					speechOutput = "I have turned " + String(selectorFirstSlot.value) + " " + state + ".";
					}
					else if(numSelectors == 2){
					speechOutput = "I have turned " + String(selectorFirstSlot.value) + " and " + String(selectorSecondSlot.value) + " " + state + ".";
					}
					else{
					speechOutput = "I have turned the lights " + state + ".";
					}
					}
					else { //if no specific request, toggle the lights
                    url = urlPrefix + '/all' + '/toggle';
                    methodType = 'POST';
                    bodyString = JSON.stringify({});
                    speechOutput = "I have toggled the lights.";
                }
                break;
            }
        case intentEnum.COLOR:
            {
                url = urlPrefix + selector + '/state';
                methodType = 'PUT';
                var color = String(intent.slots.Color.value).toLowerCase();
                bodyString = JSON.stringify({
                    "color": color
                });
                speechOutput = "I have set color to " + color + ".";
                break;
            }
        case intentEnum.SCENE:
            {
				addProcess = true;
				parseScenes(intent,response);
                break;
            }
        default:
            {
                speechOutput = "That was not a valid command, please try again.";
            }
    }
    if (!addProcess) { //no additional processing required (ie no brightness shift nor scene selection)
        sendRequest(url, methodType, bodyString, speechOutput, response); //send generated request to LIFX server
    }
}

function sendRequest(url, methodType, bodyString, speechOutput, response) {
    var post_options = {
        host: 'api.lifx.com',
        port: '443',
        path: url,
        method: methodType,
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(bodyString),
            Authorization: 'Bearer ' + appToken
        }
    };
    // Set up the request
    var post_req = https.request(post_options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            if (enableFeedback) response.tell(speechOutput);
        });
    });
    post_req.on('error', function(e) {});
    // post the data
    post_req.write(bodyString);
    post_req.end();
}

function parseBrightness(intent, response, url) {
    var post_options = {
        host: 'api.lifx.com',
        port: '443',
        path: url,
        method: 'GET',
        headers: {
            Authorization: 'Bearer ' + appToken
        }
    };
    var text = "";
    var req = https.request(post_options, function(res) {
        res.setEncoding('utf8');

        res.on('data', function(chunk) {
            text += chunk;
        });

        res.on('end', function() {
            //text = text.substring(1,text.length-1);
            var obj = JSON.parse(text);
            var bright = obj[0].brightness;
            var newurl = url + '/state';
            var methodType = 'PUT';
            var adjustmentSlot = intent.slots.Adjustment;
            var brightnessValue = 0.5;
            if (dimString.indexOf(String(adjustmentSlot.value).toLowerCase()) > -1) { //if dim command recognized
                if (bright >= 0.1) { //lower the brightness by 10%
                    brightnessValue = bright - 0.1;
                    speechOutput = "I have lowered the brightness by ten percent.";
                } else { //brightness too low, setting to 1%
                    brightnessValue = 0.01;
                    speechOutput = "I have set the brightness to one percent.";
                }
            }
            if (brightString.indexOf(String(adjustmentSlot.value).toLowerCase()) > -1) { //if brighten command recognized
                if (bright <= 1.0) { //raise brightness by 10%
                    brightnessValue = bright + 0.1;
                    speechOutput = "I have raised the brightness by ten percent.";
                } else { //brightness too high, setting to 100%
                    brightnessValue = 1.0;
                    speechOutput = "I have set the brightness to one hundred percent.";
                }

            }
            bodyString = JSON.stringify({
                "brightness": + brightnessValue
            });
            sendRequest(newurl, methodType, bodyString, speechOutput, response); //send generated request to LIFX server
        });
    });

    req.on('error', function(err) {});

    req.end();

}

function parseScenes(intent, response) {
    var post_options = {
        host: 'api.lifx.com',
        port: '443',
        path: '/v1/scenes',
        method: 'GET',
        headers: {
            Authorization: 'Bearer ' + appToken
        }
    };
	var sceneName = String(intent.slots.Scene.value).toLowerCase();
    var text = "";
    var req = https.request(post_options, function(res) {
        res.setEncoding('utf8');

        res.on('data', function(chunk) {
            text += chunk;
        });

        res.on('end', function() {
			console.log(sceneName);
            var obj = JSON.parse(text);
			var scene = obj[0].uuid;
			for(i = 0; i < Object.keys(obj).length;i++)
			{
				if(sceneName.indexOf(obj[i].name.toLowerCase()) > -1)
				{
					scene = obj[i].uuid;
					break;
				}
			}
            var url = '/v1/scenes/scene_id:' + scene + '/activate';
            var methodType = 'PUT';
            bodyString = JSON.stringify({
            });
			speechOutput = "I have set the scene to " + sceneName + ".";
            sendRequest(url, methodType, bodyString, speechOutput, response); //send generated request to LIFX server
        });
    });

    req.on('error', function(err) {});

    req.end();

}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
// Create the handler that responds to the Alexa Request.
exports.handler = function(event, context) {
    // Create an instance of the LIFX Skill.
    var skill = new LIFX();
    skill.execute(event, context);
};<|endoftext|>


<commit_before>/* global Headers */
// @flow
import qs from 'qs'
import deepExtend from 'deep-extend'

type OptionsRequest = {
  abort: () => void,
  promise: Promise<*>
}

type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
type Options = {
  method: Method,
  headers?: ?{ [key: string]: string },
  onProgress?: (num: number) => mixed,
  data?: ?{ [key: string]: mixed }
}

export function ajaxOptions (options: Options): any {
  const { headers, data, ...otherOptions } = options
  const headersObject = new Headers(
    Object.assign(
      {},
      {
        'Content-Type': 'application/json'
      },
      headers
    )
  )

  return {
    ...otherOptions,
    headers: headersObject,
    body: data ? JSON.stringify(data) : null
  }
}

export function checkStatus (response: any): any {
  return response.json().then(json => {
    return response.ok ? json : Promise.reject(json)
  })
}

function ajax (url: string, options: Options): OptionsRequest {
  if (options.method === 'GET' && options.data) {
    url = `${url}?${qs.stringify(options.data)}`
    delete options.data
  }

  if (typeof fetch === 'undefined') { // eslint-disable-line
    var { fetch } = require('fetch-ponyfill')()
  }

  const xhr = fetch(url, ajaxOptions(options))
  const promise = new Promise((resolve, reject) => {
    xhr.then(checkStatus).then(resolve, error => {
      const ret = error ? error.errors : {}

      return reject(ret || {})
    })
  })

  const abort = () => {} // noop, fetch is not cancelable

  return { abort, promise }
}

export default {
  apiPath: '',
  commonOptions: {},

  get (path: string, data: ?{}, options?: {} = {}): OptionsRequest {
    return ajax(
      `${this.apiPath}${path}`,
      deepExtend({}, { method: 'GET' }, this.commonOptions, options, { data })
    )
  },

  post (path: string, data: ?{}, options?: {} = {}): OptionsRequest {
    return ajax(
      `${this.apiPath}${path}`,
      deepExtend({}, { method: 'POST' }, this.commonOptions, options, { data })
    )
  },

  put (path: string, data: ?{}, options?: {} = {}): OptionsRequest {
    return ajax(
      `${this.apiPath}${path}`,
      deepExtend({}, { method: 'PUT' }, this.commonOptions, options, { data })
    )
  },

  del (path: string, options?: {} = {}): OptionsRequest {
    return ajax(
      `${this.apiPath}${path}`,
      deepExtend({}, { method: 'DELETE' }, this.commonOptions, options)
    )
  }
}
<commit_msg>moved ajaxOptions, Headers object breaks in server side<commit_after>/* global Headers */
// @flow
import qs from 'qs'
import deepExtend from 'deep-extend'

type OptionsRequest = {
  abort: () => void,
  promise: Promise<*>
}

type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
type Options = {
  method: Method,
  headers?: ?{ [key: string]: string },
  onProgress?: (num: number) => mixed,
  data?: ?{ [key: string]: mixed }
}

export function checkStatus (response: any): any {
  return response.json().then(json => {
    return response.ok ? json : Promise.reject(json)
  })
}

function ajax (url: string, options: Options): OptionsRequest {
  if (options.method === 'GET' && options.data) {
    url = `${url}?${qs.stringify(options.data)}`
    delete options.data
  }

  if (typeof fetch === 'undefined') {
    var { fetch, Headers } = require('fetch-ponyfill')()
  }

  const { headers, data, ...otherOptions } = options

  const headersObject = new Headers(
    Object.assign(
      {},
      {
        'Content-Type': 'application/json'
      },
      headers
    )
  )

  const xhr = fetch(url, {
    ...otherOptions,
    headers: headersObject,
    body: data ? JSON.stringify(data) : null
  })

  const promise = new Promise((resolve, reject) => {
    xhr.then(checkStatus).then(resolve, error => {
      const ret = error ? error.errors : {}

      return reject(ret || {})
    })
  })

  const abort = () => {} // noop, fetch is not cancelable

  return { abort, promise }
}

export default {
  apiPath: '',
  commonOptions: {},

  get (path: string, data: ?{}, options?: {} = {}): OptionsRequest {
    return ajax(
      `${this.apiPath}${path}`,
      deepExtend({}, { method: 'GET' }, this.commonOptions, options, { data })
    )
  },

  post (path: string, data: ?{}, options?: {} = {}): OptionsRequest {
    return ajax(
      `${this.apiPath}${path}`,
      deepExtend({}, { method: 'POST' }, this.commonOptions, options, { data })
    )
  },

  put (path: string, data: ?{}, options?: {} = {}): OptionsRequest {
    return ajax(
      `${this.apiPath}${path}`,
      deepExtend({}, { method: 'PUT' }, this.commonOptions, options, { data })
    )
  },

  del (path: string, options?: {} = {}): OptionsRequest {
    return ajax(
      `${this.apiPath}${path}`,
      deepExtend({}, { method: 'DELETE' }, this.commonOptions, options)
    )
  }
}
<|endoftext|>