<commit_before>(function(e){if(typeof module!=="undefined"&&module&&module.exports){module.exports=e()}else if(typeof define==="function"&&define.amd){define(e)}else{P=e()}})(function(){"use strict";var e=h(typeof process)&&process!=null&&{}.toString.call(process)==="[object process]",n=typeof setImmediate==="function",t=h(typeof MutationObserver)&&MutationObserver||h(typeof WebKitMutationObserver)&&WebKitMutationObserver,i=new v,r=i,o=false,u=0,a=e?g:t?x(m):T(m),l=[],s=T(_),f,c,p=h.call,d=h.apply;r.next=i;function v(){this.task=null;this.domain=null;this.a=null;this.b=null;this.next=null}function h(e){return e==="object"||e==="function"}function _(){if(l.length){throw l.shift()}}function m(){while(i!==r){i=i.next;var e=i.task;if(u>=1024){r.next=r.next.next}else{++u}if(i.domain){b(i.domain,e,i.a,i.b,void 0);i.domain=null}else{e(i.a,i.b)}i.task=null;i.a=null;i.b=null}o=false}function y(){i.task=null;i.domain=null;i.a=null;i.b=null;a()}function b(e,n,t,i,r){if(e._disposed){return}e.enter();n(t,i,r);e.exit()}function w(n,t,l,s){var f=r.next;if(f===i){f=new v;r.next=f;f.next=i}else{--u}r=f;f.task=t;f.a=l;f.b=s;if(n&&e){f.domain=process.domain}if(!o){o=true;a()}}function g(){var e=process.domain;if(e){if(!c)c=(1,require)("domain");c.active=process.domain=null}if(o&&n){setImmediate(m)}else{process.nextTick(m)}if(e){c.active=process.domain=e}}function x(e){var n=1;var i=document.createTextNode("");var r=new t(e);r.observe(i,{characterData:true});return function(){n=-n;i.data=n}}function T(e){return function(){var n=setTimeout(i,0);var t=setInterval(i,50);function i(){clearTimeout(n);clearInterval(t);e()}}}if(e){f=function(e){y();throw e}}else{f=function(e){l.push(e);s()}}function j(e,n){try{e.call()}catch(t){n(t)}}function k(e){w(true,j,e,f)}function O(e,n){for(var t=0,i=e.length;t<i;++t){if(t in e){n(e[t],t)}}}function I(e){k(function(){if(K.onerror){K.onerror.call(null,e)}else{throw e}})}var M=0;var E=1;var A=2;function K(e){return e instanceof G?e:q(new G,e,false)}function S(n,t,i){if(n._state){return n}n._state=t;n._value=i;if(t===A&&e){n._domain=process.domain}if(n._pending){N(n)}return n}function W(e,n){if(n._state){return n}n._state=e._state;n._value=e._value;n._domain=e._domain;if(n._pending){N(n)}return n}function q(e,n,t){if(e._state){return e}if(n instanceof G){if(n===e){S(e,A,new TypeError("You can't resolve a promise with itself"))}else if(n._state){W(n,e)}else{P(e,n)}}else if(n!==Object(n)){S(e,E,n)}else if(t){D(e,n)}else{w(true,D,e,n)}return e}function D(e,n){var t,i;try{i=n.then}catch(r){S(e,A,r);return}if(typeof i==="function"){t=B(e);try{p.call(i,n,t.resolve,t.reject)}catch(o){t.reject(o)}}else{S(e,E,n)}}function N(e){var n=e._pending;e._pending=null;if(n instanceof G){w(false,Y,e,n);return}for(var t=0,i=n.length;t<i;++t){w(false,Y,e,n[t])}}function P(e,n){if(!n._pending){n._pending=e}else if(n._pending instanceof G){n._pending=[n._pending,e]}else{n._pending.push(e)}}function Y(e,n){var t=e._state===E?n._cb:n._eb;n._cb=null;n._eb=null;if(!t){W(e,n);return}var i=e._domain||n._domain;if(i){n._domain=null;b(i,z,t,n,e._value)}else{z(t,n,e._value)}}function z(e,n,t){var i;try{i=e(t)}catch(r){S(n,A,r);return}q(n,i,true)}function B(e){var n=false;return{promise:e,resolve:function(t){if(!n){n=true;q(e,t,false)}},reject:function(t){if(!n){n=true;S(e,A,t)}}}}K.defer=C;function C(){return B(new G)}K.reject=F;function F(e){return S(new G,A,e)}function G(){this._state=0;this._value=void 0;this._domain=null;this._cb=null;this._eb=null;this._pending=null}G.prototype.then=function(n,t){var i=new G;i._cb=typeof n==="function"?n:null;i._eb=typeof t==="function"?t:null;i._domain=e?process.domain:null;if(this._state===M){P(i,this)}else{w(false,Y,this,i)}return i};G.prototype.done=function(e,n){var t=this;if(e||n){t=t.then(e,n)}t.then(null,I)};G.prototype.fail=function(e){return this.then(null,e)};G.prototype._always=function(e){return this.then(e,e)};G.prototype.spread=function(e,n){return this.then(e&&function(t){return J(t).then(function(n){return d.call(e,void 0,n)},n)},n)};G.prototype.timeout=function(e,n){var t=this;var i=new G;if(t._state!==M){W(t,i)}else{var r=setTimeout(function(){S(i,A,new Error(n||"Timed out after "+e+" ms"))},e);t._always(function(){clearTimeout(r);W(t,i)})}return i};G.prototype.delay=function(e){var n=C();this.then(function(t){setTimeout(function(){n.resolve(t)},e)},n.reject);return n.promise};G.prototype.inspect=function(){switch(this._state){case M:return{state:"pending"};case E:return{state:"fulfilled",value:this._value};case A:return{state:"rejected",reason:this._value};default:throw new TypeError("invalid state")}};K.allSettled=H;function H(e){var n=0;var t=new G;var i=new Array(e.length);O(e,function(e,r){var o=K(e);if(o._state===M){++n;o._always(function(){i[r]=o.inspect();if(--n===0){S(t,E,i)}})}else{i[r]=o.inspect()}});if(n===0){S(t,E,i)}return t}K.all=J;function J(e){var n=0;var t=C();var i=new Array(e.length);O(e,function(e,r){var o=K(e);if(o._state===E){i[r]=o._value}else{++n;o.then(function(e){i[r]=e;if(--n===0){t.resolve(i)}},t.reject)}});if(n===0){t.resolve(i)}return t.promise}K.promised=L;function L(e){function n(n){return d.apply(e,n)}return function(){return J([this,J(arguments)]).then(n)}}K.onerror=null;K.nextTick=k;return K});<commit_msg>Minify<commit_after>(function(e){if(typeof module!=="undefined"&&module&&module.exports){module.exports=e()}else if(typeof define==="function"&&define.amd){define(e)}else{P=e()}})(function(){"use strict";var e=i(),n,t=null;function r(e){var n=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(e)||/at ([^ ]+):(\d+):(?:\d+)$/.exec(e)||/.*@(.+):(\d+)$/.exec(e);return n?{fileName:n[1],lineNumber:Number(n[2])}:null}function i(){var e=(new Error).stack;if(!e){return 0}var t=e.split("\n");var i=t[0].indexOf("@")>0?t[1]:t[2];var a=r(i);if(!a){return 0}n=a.fileName;return a.lineNumber}function a(e,n){var t=e.split("\n");var r=[];for(var i=n|0,a=t.length;i<a;++i){var l=t[i];if(l&&!u(l)&&!o(l)){r.push(l)}}return r.join("\n")}function u(e){return e.indexOf("(module.js:")!==-1||e.indexOf("(node.js:")!==-1}function o(t){var i=r(t);return!!i&&i.fileName===n&&i.lineNumber>=e&&i.lineNumber<=on}var l="\nFrom previous event:\n";function f(e){if(e instanceof Error&&e.stack&&e.stack.indexOf(l)===-1){var n=[a(e.stack,0)];var r=t;var i=512;while(r&&--i){var u=r.stack&&a(r.stack,2);if(u){n.push(u)}r=r.parent}var o=n.join(l);e.stack=o}}var s=T(typeof process)&&process!=null&&{}.toString.call(process)==="[object process]",c=typeof setImmediate==="function",p=T(typeof MutationObserver)&&MutationObserver||T(typeof WebKitMutationObserver)&&WebKitMutationObserver,v=new j,d=v,h=false,_=0,m=s?$:p?A(N):K(N),y=[],b=K(E),w,g,k=T.call,x=T.apply;d.next=v;function j(){this.task=null;this.a=null;this.b=null;this.domain=null;this.trace=null;this.next=null}function T(e){return e==="object"||e==="function"}function E(){if(y.length){throw y.shift()}}function N(){while(v!==d){v=v.next;if(_>=1024){d.next=d.next.next}else{++_}t=v.trace;if(v.domain){S(v.domain,v.task,v.a,v.b,void 0);v.domain=null}else{(1,v.task)(v.a,v.b)}v.task=null;v.a=null;v.b=null;v.trace=null}h=false;t=null}function O(){v.task=null;v.a=null;v.b=null;v.domain=null;v.trace=null;m()}function S(e,n,t,r,i){if(e._disposed){return}e.enter();n(t,r,i);e.exit()}function I(e,n,r){var i=s?process.domain:null;var a=B.longStackSupport?{parent:t,stack:(new Error).stack}:null;M(e,n,r,i,a)}function M(e,n,t,r,i){var a=d.next;if(a===v){a=new j;d.next=a;a.next=v}else{--_}d=a;a.task=e;a.a=n;a.b=t;a.domain=r;a.trace=i;if(!h){h=true;m()}}function $(){var e=process.domain;if(e){if(!g)g=(1,require)("domain");g.active=process.domain=null}if(h&&c){setImmediate(N)}else{process.nextTick(N)}if(e){g.active=process.domain=e}}function A(e){var n=1;var t=document.createTextNode("");var r=new p(e);r.observe(t,{characterData:true});return function(){n=-n;t.data=n}}function K(e){return function(){var n=setTimeout(r,0);var t=setInterval(r,50);function r(){clearTimeout(n);clearInterval(t);e()}}}if(s){w=function(e){O();throw e}}else{w=function(e){y.push(e);b()}}function W(e,n){try{e.call()}catch(t){n(t)}}function q(e){I(W,e,w)}function D(e,n){for(var t=0,r=e.length;t<r;++t){if(t in e){n(e[t],t)}}}function F(e){q(function(){if(B.onerror){B.onerror.call(null,e)}else{throw e}})}var P=0;var Y=1;var z=2;function B(e){return e instanceof nn?e:J(new nn,e,false)}B.longStackSupport=false;function C(e,n){if(e._state){return}e._state=Y;e._value=n;if(e._pending){Q(e)}}function G(e,n){if(e._state){return}if(t){f(n)}e._state=z;e._value=n;if(s){e._domain=process.domain}if(e._pending){Q(e)}}function H(e,n){if(n._state){return}n._state=e._state;n._value=e._value;n._domain=e._domain;if(n._pending){Q(n)}}function J(e,n,t){if(e._state){return e}if(n instanceof nn){if(n===e){G(e,new TypeError("You can't resolve a promise with itself"))}else if(n._state){H(n,e)}else{R(e,n)}}else if(n!==Object(n)){C(e,n)}else if(t){L(e,n)}else{I(L,e,n)}return e}function L(e,n){var t,r;try{r=n.then}catch(i){G(e,i);return}if(typeof r==="function"){t=X(e);try{k.call(r,n,t.resolve,t.reject)}catch(a){t.reject(a)}}else{C(e,n)}}function Q(e){var n=e._pending;e._pending=null;if(n instanceof nn){M(U,e,n,null,n._trace);return}for(var t=0,r=n.length;t<r;++t){M(U,e,n[t],null,n[t]._trace)}}function R(e,n){if(!n._pending){n._pending=e}else if(n._pending instanceof nn){n._pending=[n._pending,e]}else{n._pending.push(e)}}function U(e,n){var t=e._state===Y?n._cb:n._eb;n._cb=null;n._eb=null;if(!t){H(e,n);return}var r=e._domain||n._domain;if(r){n._domain=null;S(r,V,t,n,e._value)}else{V(t,n,e._value)}}function V(e,n,t){var r;try{r=e(t)}catch(i){G(n,i);return}J(n,r,true)}function X(e){var n=false;return{promise:e,resolve:function(t){if(!n){n=true;J(e,t,false)}},reject:function(t){if(!n){n=true;G(e,t)}}}}B.defer=Z;function Z(){return X(new nn)}B.reject=en;function en(e){var n=new nn;G(n,e);return n}function nn(){this._state=0;this._value=void 0;this._domain=null;this._cb=null;this._eb=null;this._pending=null;this._trace=null}nn.prototype.then=function(e,n){var r=new nn;if(B.longStackSupport){r._trace={parent:t,stack:(new Error).stack}}r._cb=typeof e==="function"?e:null;r._eb=typeof n==="function"?n:null;if(s){r._domain=process.domain}if(this._state===P){R(r,this)}else{M(U,this,r,null,r._trace)}return r};nn.prototype.done=function(e,n){var t=this;if(e||n){t=t.then(e,n)}t.then(null,F)};nn.prototype.fail=function(e){return this.then(null,e)};nn.prototype._always=function(e){return this.then(e,e)};nn.prototype.spread=function(e,n){return this.then(e&&function(t){return an(t).then(function(n){return x.call(e,void 0,n)},n)},n)};function tn(e,n){if(t){var r=t;return setTimeout(function(){t=r;e();t=null},n)}return setTimeout(e,n)}nn.prototype.timeout=function(e,n){var t=this;var r=new nn;if(t._state!==P){H(t,r)}else{var i=tn(function(){G(r,new Error(n||"Timed out after "+e+" ms"))},e);t._always(function(){clearTimeout(i);H(t,r)})}return r};nn.prototype.delay=function(e){var n=Z();this.then(function(t){tn(function(){n.resolve(t)},e)},n.reject);return n.promise};nn.prototype.inspect=function(){switch(this._state){case P:return{state:"pending"};case Y:return{state:"fulfilled",value:this._value};case z:return{state:"rejected",reason:this._value};default:throw new TypeError("invalid state")}};B.allSettled=rn;function rn(e){var n=new nn;if(typeof e.length!=="number"){G(n,new TypeError("input not array-like"));return n}var t=0;var r=new Array(e.length);D(e,function(e,i){var a=B(e);if(a._state===P){++t;a._always(function(){r[i]=a.inspect();if(--t===0){C(n,r)}})}else{r[i]=a.inspect()}});if(t===0){C(n,r)}return n}B.all=an;function an(e){var n=Z();if(typeof e.length!=="number"){n.reject(new TypeError("input not array-like"));return n.promise}var t=0;var r=new Array(e.length);D(e,function(e,i){var a=B(e);if(a._state===Y){r[i]=a._value}else{++t;a.then(function(e){r[i]=e;if(--t===0){n.resolve(r)}},n.reject)}});if(t===0){n.resolve(r)}return n.promise}B.promised=un;function un(e){function n(n){return x.apply(e,n)}return function(){return an([this,an(arguments)]).then(n)}}B.onerror=null;B.nextTick=q;var on=i();return B});<|endoftext|>


<commit_before>// @flow weak

import isStatelessComponent from './isStatelessComponent';
import remove from './remove';

function isPathReactClass(path) {
  if (path.matchesPattern('React.Component') ||
    path.matchesPattern('React.PureComponent')) {
    return true;
  }

  const node = path.node;

  if (node && (node.name === 'Component' || node.name === 'PureComponent')) {
    return true;
  }

  return false;
}

function isReactClass(superClass, scope) {
  if (!superClass.node) {
    return false;
  }

  let answer = false;

  if (isPathReactClass(superClass)) {
    answer = true;
  } else if (superClass.node.name) { // Check for inheritance
    const className = superClass.node.name;
    const binding = scope.getBinding(className);
    if (!binding) {
      answer = false;
    } else {
      superClass = binding.path.get('superClass');

      if (isPathReactClass(superClass)) {
        answer = true;
      }
    }
  }

  return answer;
}

export default function ({ template, types }) {
  return {
    visitor: {
      Program(programPath, state) {
        let ignoreFilenames;

        if (state.opts.ignoreFilenames) {
          ignoreFilenames = new RegExp(state.opts.ignoreFilenames.join('|'), 'gi');
        } else {
          ignoreFilenames = undefined;
        }

        const globalOptions = {
          visitedKey: `transform-react-remove-prop-types${Date.now()}`,
          wrapperIfTemplate: template(`
            if (process.env.NODE_ENV !== "production") {
              NODE;
            }
          `),
          mode: state.opts.mode || 'remove',
          ignoreFilenames,
          types,
          removeImport: state.opts.removeImport || false,
        };

        // On program start, do an explicit traversal up front for this plugin.
        programPath.traverse({
          ObjectProperty: {
            exit(path) {
              const node = path.node;

              if (node.computed || node.key.name !== 'propTypes') {
                return;
              }

              const parent = path.findParent((currentNode) => {
                if (currentNode.type !== 'CallExpression') {
                  return false;
                }

                return currentNode.get('callee').node.name === 'createReactClass';
              });

              if (parent) {
                remove(path, globalOptions, {
                  type: 'createClass',
                });
              }
            },
          },
          // Here to support stage-1 transform-class-properties.
          ClassProperty(path) {
            const {
              node,
              scope,
            } = path;

            if (node.key.name === 'propTypes') {
              const pathClassDeclaration = scope.path;

              if (isReactClass(pathClassDeclaration.get('superClass'), scope)) {
                remove(path, globalOptions, {
                  type: 'class static',
                  pathClassDeclaration,
                });
              }
            }
          },
          AssignmentExpression(path) {
            const {
              node,
              scope,
            } = path;

            if (node.left.computed || !node.left.property || node.left.property.name !== 'propTypes') {
              return;
            }

            const className = node.left.object.name;
            const binding = scope.getBinding(className);

            if (!binding) {
              return;
            }

            if (binding.path.isClassDeclaration()) {
              const superClass = binding.path.get('superClass');

              if (isReactClass(superClass, scope)) {
                remove(path, globalOptions, {
                  type: 'class assign',
                });
              }
            } else if (isStatelessComponent(binding.path)) {
              remove(path, globalOptions, {
                type: 'stateless',
              });
            }
          },
        });

        programPath.scope.crawl();

        if (globalOptions.removeImport && globalOptions.mode === 'remove') {
          programPath.traverse({
            ImportDeclaration(path) {
              const { source, specifiers } = path.node;
              if (source.value !== 'prop-types') {
                return;
              }
              const haveUsedSpecifiers = specifiers.some((specifier) => {
                const importedIdentifierName = specifier.local.name;
                const { referencePaths } = path.scope.getBinding(importedIdentifierName);
                return referencePaths.length > 0;
              });

              if (!haveUsedSpecifiers) {
                path.remove();
              }
              path.stop();
            },
          });
        }
      },
    },
  };
}
<commit_msg>Crawl if removeImport<commit_after>// @flow weak

import isStatelessComponent from './isStatelessComponent';
import remove from './remove';

function isPathReactClass(path) {
  if (path.matchesPattern('React.Component') ||
    path.matchesPattern('React.PureComponent')) {
    return true;
  }

  const node = path.node;

  if (node && (node.name === 'Component' || node.name === 'PureComponent')) {
    return true;
  }

  return false;
}

function isReactClass(superClass, scope) {
  if (!superClass.node) {
    return false;
  }

  let answer = false;

  if (isPathReactClass(superClass)) {
    answer = true;
  } else if (superClass.node.name) { // Check for inheritance
    const className = superClass.node.name;
    const binding = scope.getBinding(className);
    if (!binding) {
      answer = false;
    } else {
      superClass = binding.path.get('superClass');

      if (isPathReactClass(superClass)) {
        answer = true;
      }
    }
  }

  return answer;
}

export default function ({ template, types }) {
  return {
    visitor: {
      Program(programPath, state) {
        let ignoreFilenames;

        if (state.opts.ignoreFilenames) {
          ignoreFilenames = new RegExp(state.opts.ignoreFilenames.join('|'), 'gi');
        } else {
          ignoreFilenames = undefined;
        }

        const globalOptions = {
          visitedKey: `transform-react-remove-prop-types${Date.now()}`,
          wrapperIfTemplate: template(`
            if (process.env.NODE_ENV !== "production") {
              NODE;
            }
          `),
          mode: state.opts.mode || 'remove',
          ignoreFilenames,
          types,
          removeImport: state.opts.removeImport || false,
        };

        // On program start, do an explicit traversal up front for this plugin.
        programPath.traverse({
          ObjectProperty: {
            exit(path) {
              const node = path.node;

              if (node.computed || node.key.name !== 'propTypes') {
                return;
              }

              const parent = path.findParent((currentNode) => {
                if (currentNode.type !== 'CallExpression') {
                  return false;
                }

                return currentNode.get('callee').node.name === 'createReactClass';
              });

              if (parent) {
                remove(path, globalOptions, {
                  type: 'createClass',
                });
              }
            },
          },
          // Here to support stage-1 transform-class-properties.
          ClassProperty(path) {
            const {
              node,
              scope,
            } = path;

            if (node.key.name === 'propTypes') {
              const pathClassDeclaration = scope.path;

              if (isReactClass(pathClassDeclaration.get('superClass'), scope)) {
                remove(path, globalOptions, {
                  type: 'class static',
                  pathClassDeclaration,
                });
              }
            }
          },
          AssignmentExpression(path) {
            const {
              node,
              scope,
            } = path;

            if (node.left.computed || !node.left.property || node.left.property.name !== 'propTypes') {
              return;
            }

            const className = node.left.object.name;
            const binding = scope.getBinding(className);

            if (!binding) {
              return;
            }

            if (binding.path.isClassDeclaration()) {
              const superClass = binding.path.get('superClass');

              if (isReactClass(superClass, scope)) {
                remove(path, globalOptions, {
                  type: 'class assign',
                });
              }
            } else if (isStatelessComponent(binding.path)) {
              remove(path, globalOptions, {
                type: 'stateless',
              });
            }
          },
        });

        if (globalOptions.removeImport && globalOptions.mode === 'remove') {
          programPath.scope.crawl();

          programPath.traverse({
            ImportDeclaration(path) {
              const { source, specifiers } = path.node;
              if (source.value !== 'prop-types') {
                return;
              }
              const haveUsedSpecifiers = specifiers.some((specifier) => {
                const importedIdentifierName = specifier.local.name;
                const { referencePaths } = path.scope.getBinding(importedIdentifierName);
                return referencePaths.length > 0;
              });

              if (!haveUsedSpecifiers) {
                path.remove();
              }
              path.stop();
            },
          });
        }
      },
    },
  };
}
<|endoftext|>


<commit_before>'use strict';
/**
 * @file Define initial handlers,
 *
 * Trade grant_tokens for access_tokens.
 *
 */
var Anyfetch = require('anyfetch');
var async = require('async');
var restify = require('restify');
var rarity = require('rarity');
var url = require('url');

var CancelError = require('../../index.js').CancelError;
var TempToken = require('../../models/temp-token.js');
var Token = require('../../models/token.js');

/**
 * The user is redirected to this handler after getting access to his provider.
 *
 * @param {Object} req Request object from the client
 * @param {Object} res Response we want to return
 * @param {Function} next Callback to call once res has been populated.
 */
module.exports = function(retrieveTokens, config) {
  return function(req, res, next) {
    if(!req.ANYFETCH_SESSION.code) {
      console.warn("ERR: Missing code cookie.");
      return next(new restify.MissingParameterError("Missing code cookie."));
    }

    var returnTo = process.env.MANAGER_URL || "https://manager.anyfetch.com";
    async.waterfall([
      function retrieveTempToken(cb) {
        TempToken.findOne({anyfetchCode: req.ANYFETCH_SESSION.code}, cb);
      },
      function retrieveDataFromProvider(tempToken, cb) {
        if(!tempToken) {
          return cb(new Error("Unable to retrieve provider preData."));
        }

        returnTo = tempToken.returnTo;

        // Retrieve data from provider
        retrieveTokens(req.params, tempToken.data, rarity.carry([tempToken], cb));
      },
      function createAccessToken(tempToken, accountName, providerData, cb) {
        if(typeof accountName !== "string") {
          console.warn("Error: String attempt as accountName");
        }

        // Create a new anyfetch access-token with our grant
        Anyfetch.getAccessToken(config.appId, config.appSecret, tempToken.anyfetchCode, rarity.carry([accountName, providerData, tempToken], cb));
      },
      function setAccountName(accountName, providerData, tempToken, anyfetchAccessToken, cb) {
        var anyfetchClient = new Anyfetch(anyfetchAccessToken);
        anyfetchClient.postAccountName(accountName, rarity.carryAndSlice([accountName, providerData, tempToken, anyfetchAccessToken], 5, cb));
      },
      function createNewToken(accountName, providerData, tempToken, anyfetchAccessToken, cb) {
        // Create new token
        var token = new Token({
          anyfetchToken: anyfetchAccessToken,
          data: providerData,
          accountName: accountName
        });

        token.save(rarity.carryAndSlice([anyfetchAccessToken, tempToken], 4, cb));
      },
      function removeTempToken(anyfetchAccessToken, tempToken, cb) {
        tempToken.remove(rarity.carryAndSlice([anyfetchAccessToken], 3, cb));
      },
      function updateCompany(anyfetchAccessToken, cb) {
        var anyfetchClient = new Anyfetch(anyfetchAccessToken);
        anyfetchClient.postCompanyUpdate(cb);
      }
    ], function sendResponse(err) {
      if(err && !(err instanceof CancelError)) {
        console.warn("ERR:", err);
        res.send(500);
        return next(err);
      }

      var urlObj = url.parse(returnTo);
      urlObj.query.state = (err instanceof CancelError) ? 'canceled' : 'success';
      returnTo = url.format(urlObj);

      res.send(302, null, {
        location: returnTo
      });

      next();
    });
  };
};
<commit_msg>Fix a bug with URL parse and format<commit_after>'use strict';
/**
 * @file Define initial handlers,
 *
 * Trade grant_tokens for access_tokens.
 *
 */
var Anyfetch = require('anyfetch');
var async = require('async');
var restify = require('restify');
var rarity = require('rarity');
var url = require('url');

var CancelError = require('../../index.js').CancelError;
var TempToken = require('../../models/temp-token.js');
var Token = require('../../models/token.js');

/**
 * The user is redirected to this handler after getting access to his provider.
 *
 * @param {Object} req Request object from the client
 * @param {Object} res Response we want to return
 * @param {Function} next Callback to call once res has been populated.
 */
module.exports = function(retrieveTokens, config) {
  return function(req, res, next) {
    if(!req.ANYFETCH_SESSION.code) {
      console.warn("ERR: Missing code cookie.");
      return next(new restify.MissingParameterError("Missing code cookie."));
    }

    var returnTo = process.env.MANAGER_URL || "https://manager.anyfetch.com";
    async.waterfall([
      function retrieveTempToken(cb) {
        TempToken.findOne({anyfetchCode: req.ANYFETCH_SESSION.code}, cb);
      },
      function retrieveDataFromProvider(tempToken, cb) {
        if(!tempToken) {
          return cb(new Error("Unable to retrieve provider preData."));
        }

        returnTo = tempToken.returnTo;

        // Retrieve data from provider
        retrieveTokens(req.params, tempToken.data, rarity.carry([tempToken], cb));
      },
      function createAccessToken(tempToken, accountName, providerData, cb) {
        if(typeof accountName !== "string") {
          console.warn("Error: String attempt as accountName");
        }

        // Create a new anyfetch access-token with our grant
        Anyfetch.getAccessToken(config.appId, config.appSecret, tempToken.anyfetchCode, rarity.carry([accountName, providerData, tempToken], cb));
      },
      function setAccountName(accountName, providerData, tempToken, anyfetchAccessToken, cb) {
        var anyfetchClient = new Anyfetch(anyfetchAccessToken);
        anyfetchClient.postAccountName(accountName, rarity.carryAndSlice([accountName, providerData, tempToken, anyfetchAccessToken], 5, cb));
      },
      function createNewToken(accountName, providerData, tempToken, anyfetchAccessToken, cb) {
        // Create new token
        var token = new Token({
          anyfetchToken: anyfetchAccessToken,
          data: providerData,
          accountName: accountName
        });

        token.save(rarity.carryAndSlice([anyfetchAccessToken, tempToken], 4, cb));
      },
      function removeTempToken(anyfetchAccessToken, tempToken, cb) {
        tempToken.remove(rarity.carryAndSlice([anyfetchAccessToken], 3, cb));
      },
      function updateCompany(anyfetchAccessToken, cb) {
        var anyfetchClient = new Anyfetch(anyfetchAccessToken);
        anyfetchClient.postCompanyUpdate(cb);
      }
    ], function sendResponse(err) {
      if(err && !(err instanceof CancelError)) {
        console.warn("ERR:", err);
        res.send(500);
        return next(err);
      }

      var urlObj = url.parse(returnTo, true);
      delete urlObj.search;
      urlObj.query.state = (err instanceof CancelError) ? 'canceled' : 'success';
      returnTo = url.format(urlObj);

      res.send(302, null, {
        location: returnTo
      });

      next();
    });
  };
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

// nS - No Space
// lC - Lowercase

import cheerio from 'cheerio';
import colors from 'colors';
import fs from 'fs';
import program from 'commander';
import replace from 'node-replace';
import shell from 'shelljs';
import pjson from '../package.json';
import path from 'path';
import { foldersAndFiles } from './config/foldersAndFiles';
import { filesToModifyContent } from './config/filesToModifyContent';
import { bundleIdentifiers } from './config/bundleIdentifiers';

const devTestRNProject = ''; // For Development eg '/Users/junedomingo/Desktop/RN49'
const __dirname = devTestRNProject || process.cwd();
const projectName = pjson.name;
const replaceOptions = {
  recursive: true,
  silent: true,
};

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
}

function replaceContent(regex, replacement, paths) {
  replace({
    regex,
    replacement,
    paths,
    ...replaceOptions,
  });

  for (const filePath of paths) {
    console.log(`${filePath.replace(__dirname, '')} ${colors.green('MODIFIED')}`);
  }
}

const deletePreviousBundleDirectory = ({ oldBundleNameDir, shouldDelete }) => {
  if (shouldDelete) {
    const dir = oldBundleNameDir.replace(/\./g, '/');
    const deleteDirectory = shell.rm('-rf', dir);
    Promise.resolve(deleteDirectory);
    console.log('Done removing previous bundle directory.'.green);
  } else {
    Promise.resolve();
    console.log('Bundle directory was not changed. Keeping...'.yellow);
  }
};

const cleanBuilds = () => {
  const deleteDirectories = shell.rm('-rf', [
    path.join(__dirname, 'ios/build/*'),
    path.join(__dirname, 'android/.gradle/*'),
    path.join(__dirname, 'android/app/build/*'),
    path.join(__dirname, 'android/build/*'),
  ]);
  Promise.resolve(deleteDirectories);
  console.log('Done removing builds.'.green);
};

const loadAppConfig = () => {
  return readFile(path.join(__dirname, 'app.json')).then(data => JSON.parse(data));
}

loadAppConfig()
  .then(appConfig => {
    const currentAppName = appConfig.name;
    const nS_CurrentAppName = currentAppName.replace(/\s/g, '');
    const lC_Ns_CurrentAppName = nS_CurrentAppName.toLowerCase();

    program
      .version('2.4.1')
      .arguments('<newName>')
      .option('-b, --bundleID [value]', 'Set custom bundle identifier eg. "com.junedomingo.travelapp"')
      .action(newName => {
        const nS_NewName = newName.replace(/\s/g, '');
        const pattern = /^([\p{Letter}\p{Number}])+([\p{Letter}\p{Number}\s]+)$/u;
        const lC_Ns_NewAppName = nS_NewName.toLowerCase();
        const bundleID = program.bundleID ? program.bundleID.toLowerCase() : null;
        let newBundlePath;
        const listOfFoldersAndFiles = foldersAndFiles(currentAppName, newName);
        const listOfFilesToModifyContent = filesToModifyContent(currentAppName, newName, projectName);

        if (bundleID) {
          newBundlePath = bundleID.replace(/\./g, '/');
          const id = bundleID.split('.');
          const validBundleID = /^([a-zA-Z]([a-zA-Z0-9_])*\.)+[a-zA-Z]([a-zA-Z0-9_])*$/u;
          if (id.length < 2) {
            return console.log(
              'Invalid Bundle Identifier. Add something like "com.travelapp" or "com.junedomingo.travelapp"'
            );
          }
          if (!validBundleID.test(bundleID)) {
            return console.log('Invalid Bundle Identifier. It must have at least two segments (one or more dots). Each segment must start with a letter. All characters must be alphanumeric or an underscore [a-zA-Z0-9_]')
          }
        }

        if (!pattern.test(newName)) {
          return console.log(
            `"${newName}" is not a valid name for a project. Please use a valid identifier name (alphanumeric and space).`
          );
        }

        if (newName === currentAppName || newName === nS_CurrentAppName || newName === lC_Ns_CurrentAppName) {
          return console.log('Please try a different name.');
        }

        // Move files and folders from ./config/foldersAndFiles.js
        const resolveFoldersAndFiles = new Promise(resolve => {
          listOfFoldersAndFiles.forEach((element, index) => {
            const dest = element.replace(new RegExp(nS_CurrentAppName, 'i'), nS_NewName);
            let itemsProcessed = 1;
            const successMsg = `/${dest} ${colors.green('RENAMED')}`;

            setTimeout(() => {
              itemsProcessed += index;

              if (fs.existsSync(path.join(__dirname, element)) || !fs.existsSync(path.join(__dirname, element))) {
                const move = shell.exec(
                  `git mv -k "${path.join(__dirname, element)}" "${path.join(__dirname, dest)}"`
                );

                if (move.code === 0) {
                  console.log(successMsg);
                } else if (move.code === 128) {
                  // if "outside repository" error occured
                  if (shell.mv('-f', path.join(__dirname, element), path.join(__dirname, dest)).code === 0) {
                    console.log(successMsg);
                  } else {
                    console.log("Ignore above error if this file doesn't exist");
                  }
                }
              }

              if (itemsProcessed === listOfFoldersAndFiles.length) {
                resolve();
              }
            }, 200 * index);
          });
        });

        // Modify file content from ./config/filesToModifyContent.js
        const resolveFilesToModifyContent = () =>
          new Promise(resolve => {
            let filePathsCount = 0;
            let itemsProcessed = 0;
            listOfFilesToModifyContent.map(file => {
              filePathsCount += file.paths.length;

              file.paths.map((filePath, index) => {
                const newPaths = [];

                setTimeout(() => {
                  itemsProcessed++;
                  if (fs.existsSync(path.join(__dirname, filePath))) {
                    newPaths.push(path.join(__dirname, filePath));
                    replaceContent(file.regex, file.replacement, newPaths);
                  }
                  if (itemsProcessed === filePathsCount) {
                    resolve();
                  }
                }, 200 * index);
              });
            });
          });

        const resolveJavaFiles = () =>
          new Promise(resolve => {
            readFile(path.join(__dirname, 'android/app/src/main/AndroidManifest.xml')).then(data => {
              const $ = cheerio.load(data);
              const currentBundleID = $('manifest').attr('package');
              const newBundleID = program.bundleID ? bundleID : `com.${lC_Ns_NewAppName}`;
              const javaFileBase = '/android/app/src/main/java';
              const newJavaPath = `${javaFileBase}/${newBundleID.replace(/\./g, '/')}`;
              const currentJavaPath = `${javaFileBase}/${currentBundleID.replace(/\./g, '/')}`;

              if (bundleID) {
                newBundlePath = newJavaPath;
              } else {
                newBundlePath = newBundleID.replace(/\./g, '/').toLowerCase();
                newBundlePath = `${javaFileBase}/${newBundlePath}`;
              }

              const fullCurrentBundlePath = path.join(__dirname, currentJavaPath);
              const fullNewBundlePath = path.join(__dirname, newBundlePath);

              // Create new bundle folder if doesn't exist yet
              if (!fs.existsSync(fullNewBundlePath)) {
                shell.mkdir('-p', fullNewBundlePath);
                const move = shell.exec(`git mv -k "${fullCurrentBundlePath}/"* "${fullNewBundlePath}"`);
                const successMsg = `${newBundlePath} ${colors.green('BUNDLE INDENTIFIER CHANGED')}`;

                if (move.code === 0) {
                  console.log(successMsg);
                } else if (move.code === 128) {
                  // if "outside repository" error occured
                  if (shell.mv('-f', fullCurrentBundlePath + '/*', fullNewBundlePath).code === 0) {
                    console.log(successMsg);
                  } else {
                    console.log(`Error moving: "${currentJavaPath}" "${newBundlePath}"`);
                  }
                }
              }

              const vars = {
                currentBundleID,
                newBundleID,
                newBundlePath,
                javaFileBase,
                currentJavaPath,
                newJavaPath,
              };
              resolve(vars);
            });
          });

        const resolveBundleIdentifiers = params =>
          new Promise(resolve => {
            let filePathsCount = 0;
            const { currentBundleID, newBundleID, newBundlePath, javaFileBase, currentJavaPath, newJavaPath } = params;

            bundleIdentifiers(
              currentAppName,
              newName,
              projectName,
              currentBundleID,
              newBundleID,
              newBundlePath
            ).map(file => {
              filePathsCount += file.paths.length - 1;
              let itemsProcessed = 0;

              file.paths.map((filePath, index) => {
                const newPaths = [];
                if (fs.existsSync(path.join(__dirname, filePath))) {
                  newPaths.push(path.join(__dirname, filePath));

                  setTimeout(() => {
                    itemsProcessed += index;
                    replaceContent(file.regex, file.replacement, newPaths);
                    if (itemsProcessed === filePathsCount) {
                      const oldBundleNameDir = path.join(__dirname, javaFileBase, currentBundleID);
                      resolve({ oldBundleNameDir, shouldDelete: !newJavaPath.includes(currentJavaPath) });
                    }
                  }, 200 * index);
                }
              });
            });
          });

        const rename = () => {
          resolveFoldersAndFiles
            .then(resolveFilesToModifyContent)
            .then(resolveJavaFiles)
            .then(resolveBundleIdentifiers)
            .then(deletePreviousBundleDirectory)
            .then(cleanBuilds)
            .then(() => console.log(`APP SUCCESSFULLY RENAMED TO "${newName}"! 🎉 🎉 🎉`.green))
            .then(() => {
              if (fs.existsSync(path.join(__dirname, 'ios', 'Podfile'))) {
                console.log(
                  `${colors.yellow('Podfile has been modified, please run "pod install" inside ios directory.')}`
                );
              }
            })
            .then(() =>
              console.log(
                `${colors.yellow(
                  'Please make sure to run "watchman watch-del-all" and "npm start --reset-cache" before running the app. '
                )}`
              )
            );
        };

        rename();
      })
      .parse(process.argv);
    if (!process.argv.slice(2).length) program.outputHelp();
  })
  .catch(err => {
    if (err.code === 'ENOENT') return console.log('Directory should be created using "react-native init"');

    return console.log('Something went wrong: ', err);
  });
<commit_msg>Use lib version from package.json<commit_after>#!/usr/bin/env node

// nS - No Space
// lC - Lowercase

import cheerio from 'cheerio';
import colors from 'colors';
import fs from 'fs';
import program from 'commander';
import replace from 'node-replace';
import shell from 'shelljs';
import pjson from '../package.json';
import path from 'path';
import { foldersAndFiles } from './config/foldersAndFiles';
import { filesToModifyContent } from './config/filesToModifyContent';
import { bundleIdentifiers } from './config/bundleIdentifiers';

const devTestRNProject = ''; // For Development eg '/Users/junedomingo/Desktop/RN49'
const __dirname = devTestRNProject || process.cwd();
const projectName = pjson.name;
const projectVersion = pjson.version;
const replaceOptions = {
  recursive: true,
  silent: true,
};

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
}

function replaceContent(regex, replacement, paths) {
  replace({
    regex,
    replacement,
    paths,
    ...replaceOptions,
  });

  for (const filePath of paths) {
    console.log(`${filePath.replace(__dirname, '')} ${colors.green('MODIFIED')}`);
  }
}

const deletePreviousBundleDirectory = ({ oldBundleNameDir, shouldDelete }) => {
  if (shouldDelete) {
    const dir = oldBundleNameDir.replace(/\./g, '/');
    const deleteDirectory = shell.rm('-rf', dir);
    Promise.resolve(deleteDirectory);
    console.log('Done removing previous bundle directory.'.green);
  } else {
    Promise.resolve();
    console.log('Bundle directory was not changed. Keeping...'.yellow);
  }
};

const cleanBuilds = () => {
  const deleteDirectories = shell.rm('-rf', [
    path.join(__dirname, 'ios/build/*'),
    path.join(__dirname, 'android/.gradle/*'),
    path.join(__dirname, 'android/app/build/*'),
    path.join(__dirname, 'android/build/*'),
  ]);
  Promise.resolve(deleteDirectories);
  console.log('Done removing builds.'.green);
};

const loadAppConfig = () => {
  return readFile(path.join(__dirname, 'app.json')).then(data => JSON.parse(data));
}

loadAppConfig()
  .then(appConfig => {
    const currentAppName = appConfig.name;
    const nS_CurrentAppName = currentAppName.replace(/\s/g, '');
    const lC_Ns_CurrentAppName = nS_CurrentAppName.toLowerCase();

    program
      .version(projectVersion)
      .arguments('<newName>')
      .option('-b, --bundleID [value]', 'Set custom bundle identifier eg. "com.junedomingo.travelapp"')
      .action(newName => {
        const nS_NewName = newName.replace(/\s/g, '');
        const pattern = /^([\p{Letter}\p{Number}])+([\p{Letter}\p{Number}\s]+)$/u;
        const lC_Ns_NewAppName = nS_NewName.toLowerCase();
        const bundleID = program.bundleID ? program.bundleID.toLowerCase() : null;
        let newBundlePath;
        const listOfFoldersAndFiles = foldersAndFiles(currentAppName, newName);
        const listOfFilesToModifyContent = filesToModifyContent(currentAppName, newName, projectName);

        if (bundleID) {
          newBundlePath = bundleID.replace(/\./g, '/');
          const id = bundleID.split('.');
          const validBundleID = /^([a-zA-Z]([a-zA-Z0-9_])*\.)+[a-zA-Z]([a-zA-Z0-9_])*$/u;
          if (id.length < 2) {
            return console.log(
              'Invalid Bundle Identifier. Add something like "com.travelapp" or "com.junedomingo.travelapp"'
            );
          }
          if (!validBundleID.test(bundleID)) {
            return console.log('Invalid Bundle Identifier. It must have at least two segments (one or more dots). Each segment must start with a letter. All characters must be alphanumeric or an underscore [a-zA-Z0-9_]')
          }
        }

        if (!pattern.test(newName)) {
          return console.log(
            `"${newName}" is not a valid name for a project. Please use a valid identifier name (alphanumeric and space).`
          );
        }

        if (newName === currentAppName || newName === nS_CurrentAppName || newName === lC_Ns_CurrentAppName) {
          return console.log('Please try a different name.');
        }

        // Move files and folders from ./config/foldersAndFiles.js
        const resolveFoldersAndFiles = new Promise(resolve => {
          listOfFoldersAndFiles.forEach((element, index) => {
            const dest = element.replace(new RegExp(nS_CurrentAppName, 'i'), nS_NewName);
            let itemsProcessed = 1;
            const successMsg = `/${dest} ${colors.green('RENAMED')}`;

            setTimeout(() => {
              itemsProcessed += index;

              if (fs.existsSync(path.join(__dirname, element)) || !fs.existsSync(path.join(__dirname, element))) {
                const move = shell.exec(
                  `git mv -k "${path.join(__dirname, element)}" "${path.join(__dirname, dest)}"`
                );

                if (move.code === 0) {
                  console.log(successMsg);
                } else if (move.code === 128) {
                  // if "outside repository" error occured
                  if (shell.mv('-f', path.join(__dirname, element), path.join(__dirname, dest)).code === 0) {
                    console.log(successMsg);
                  } else {
                    console.log("Ignore above error if this file doesn't exist");
                  }
                }
              }

              if (itemsProcessed === listOfFoldersAndFiles.length) {
                resolve();
              }
            }, 200 * index);
          });
        });

        // Modify file content from ./config/filesToModifyContent.js
        const resolveFilesToModifyContent = () =>
          new Promise(resolve => {
            let filePathsCount = 0;
            let itemsProcessed = 0;
            listOfFilesToModifyContent.map(file => {
              filePathsCount += file.paths.length;

              file.paths.map((filePath, index) => {
                const newPaths = [];

                setTimeout(() => {
                  itemsProcessed++;
                  if (fs.existsSync(path.join(__dirname, filePath))) {
                    newPaths.push(path.join(__dirname, filePath));
                    replaceContent(file.regex, file.replacement, newPaths);
                  }
                  if (itemsProcessed === filePathsCount) {
                    resolve();
                  }
                }, 200 * index);
              });
            });
          });

        const resolveJavaFiles = () =>
          new Promise(resolve => {
            readFile(path.join(__dirname, 'android/app/src/main/AndroidManifest.xml')).then(data => {
              const $ = cheerio.load(data);
              const currentBundleID = $('manifest').attr('package');
              const newBundleID = program.bundleID ? bundleID : `com.${lC_Ns_NewAppName}`;
              const javaFileBase = '/android/app/src/main/java';
              const newJavaPath = `${javaFileBase}/${newBundleID.replace(/\./g, '/')}`;
              const currentJavaPath = `${javaFileBase}/${currentBundleID.replace(/\./g, '/')}`;

              if (bundleID) {
                newBundlePath = newJavaPath;
              } else {
                newBundlePath = newBundleID.replace(/\./g, '/').toLowerCase();
                newBundlePath = `${javaFileBase}/${newBundlePath}`;
              }

              const fullCurrentBundlePath = path.join(__dirname, currentJavaPath);
              const fullNewBundlePath = path.join(__dirname, newBundlePath);

              // Create new bundle folder if doesn't exist yet
              if (!fs.existsSync(fullNewBundlePath)) {
                shell.mkdir('-p', fullNewBundlePath);
                const move = shell.exec(`git mv -k "${fullCurrentBundlePath}/"* "${fullNewBundlePath}"`);
                const successMsg = `${newBundlePath} ${colors.green('BUNDLE INDENTIFIER CHANGED')}`;

                if (move.code === 0) {
                  console.log(successMsg);
                } else if (move.code === 128) {
                  // if "outside repository" error occured
                  if (shell.mv('-f', fullCurrentBundlePath + '/*', fullNewBundlePath).code === 0) {
                    console.log(successMsg);
                  } else {
                    console.log(`Error moving: "${currentJavaPath}" "${newBundlePath}"`);
                  }
                }
              }

              const vars = {
                currentBundleID,
                newBundleID,
                newBundlePath,
                javaFileBase,
                currentJavaPath,
                newJavaPath,
              };
              resolve(vars);
            });
          });

        const resolveBundleIdentifiers = params =>
          new Promise(resolve => {
            let filePathsCount = 0;
            const { currentBundleID, newBundleID, newBundlePath, javaFileBase, currentJavaPath, newJavaPath } = params;

            bundleIdentifiers(
              currentAppName,
              newName,
              projectName,
              currentBundleID,
              newBundleID,
              newBundlePath
            ).map(file => {
              filePathsCount += file.paths.length - 1;
              let itemsProcessed = 0;

              file.paths.map((filePath, index) => {
                const newPaths = [];
                if (fs.existsSync(path.join(__dirname, filePath))) {
                  newPaths.push(path.join(__dirname, filePath));

                  setTimeout(() => {
                    itemsProcessed += index;
                    replaceContent(file.regex, file.replacement, newPaths);
                    if (itemsProcessed === filePathsCount) {
                      const oldBundleNameDir = path.join(__dirname, javaFileBase, currentBundleID);
                      resolve({ oldBundleNameDir, shouldDelete: !newJavaPath.includes(currentJavaPath) });
                    }
                  }, 200 * index);
                }
              });
            });
          });

        const rename = () => {
          resolveFoldersAndFiles
            .then(resolveFilesToModifyContent)
            .then(resolveJavaFiles)
            .then(resolveBundleIdentifiers)
            .then(deletePreviousBundleDirectory)
            .then(cleanBuilds)
            .then(() => console.log(`APP SUCCESSFULLY RENAMED TO "${newName}"! 🎉 🎉 🎉`.green))
            .then(() => {
              if (fs.existsSync(path.join(__dirname, 'ios', 'Podfile'))) {
                console.log(
                  `${colors.yellow('Podfile has been modified, please run "pod install" inside ios directory.')}`
                );
              }
            })
            .then(() =>
              console.log(
                `${colors.yellow(
                  'Please make sure to run "watchman watch-del-all" and "npm start --reset-cache" before running the app. '
                )}`
              )
            );
        };

        rename();
      })
      .parse(process.argv);
    if (!process.argv.slice(2).length) program.outputHelp();
  })
  .catch(err => {
    if (err.code === 'ENOENT') return console.log('Directory should be created using "react-native init"');

    return console.log('Something went wrong: ', err);
  });
<|endoftext|>


<commit_before>'use strict';

const { API_KEY } = process.env;
if (!API_KEY) {
  console.error('API_KEY not found in env vars');
  process.exit(1);
}

const rawPlaylistUrl = process.argv[2];
const playlistUrl = rawPlaylistUrl && rawPlaylistUrl.trim();
if (!playlistUrl) {
  console.log('Usage: index.js [playlistUrl]\n');
  console.log('Missing argument: playlistUrl');
  process.exit(1);
}

const abbreviate = require('number-abbreviate');
const playList = require('./playlist');

async function main() {
  const playListId = playList.getPlaylistId(playlistUrl);
  if (!playListId) {
    console.error('Looks like an invalid playlist url 😵');
    process.exit(1);
  }
  try {
    const videosList = await playList.getSortedPlaylist(playListId);
    videosList.forEach(prettyPrintVideo);
  } catch (error) {
    if (error.response) {
      console.error(error.response.data);
    } else {
      console.error(error);
    }
    process.exit(1);
  }
}

function prettyPrintVideo(video, index) {
  const views = abbreviate(video.statistics.viewCount, 1);
  const likes = abbreviate(video.statistics.likeCount, 1);
  console.log(
    `${index + 1}. ${video.snippet.title} [👀  ${views} / 👍  ${likes}]`
  );
  console.log(`\thttps://www.youtube.com/watch?v=${video.id}`);
  console.log();
}

main();
<commit_msg>add shebang to index.js<commit_after>#! /usr/bin/env node

'use strict';

const { API_KEY } = process.env;
if (!API_KEY) {
  console.error('API_KEY not found in env vars');
  process.exit(1);
}

const rawPlaylistUrl = process.argv[2];
const playlistUrl = rawPlaylistUrl && rawPlaylistUrl.trim();
if (!playlistUrl) {
  console.log('Usage: index.js [playlistUrl]\n');
  console.log('Missing argument: playlistUrl');
  process.exit(1);
}

const abbreviate = require('number-abbreviate');
const playList = require('./playlist');

async function main() {
  const playListId = playList.getPlaylistId(playlistUrl);
  if (!playListId) {
    console.error('Looks like an invalid playlist url 😵');
    process.exit(1);
  }
  try {
    const videosList = await playList.getSortedPlaylist(playListId);
    videosList.forEach(prettyPrintVideo);
  } catch (error) {
    if (error.response) {
      console.error(error.response.data);
    } else {
      console.error(error);
    }
    process.exit(1);
  }
}

function prettyPrintVideo(video, index) {
  const views = abbreviate(video.statistics.viewCount, 1);
  const likes = abbreviate(video.statistics.likeCount, 1);
  console.log(
    `${index + 1}. ${video.snippet.title} [👀  ${views} / 👍  ${likes}]`
  );
  console.log(`\thttps://www.youtube.com/watch?v=${video.id}`);
  console.log();
}

main();
<|endoftext|>


<commit_before>const hash = require('object-hash');

function cache(func, options) {
  return (root, args, context) => {
    if (!context.resolverCache) {
      throw new Error('Missing resolverCache property on the Graphql context.');
    }

    const key = `${hash(root)}:${hash(args)}`;
    const executeAndCache = () =>
      Promise.resolve(func(root, args, context)).then(value =>
        context.resolverCache.set(key, value, options)
      );

    return (
      context.resolverCache
        .get(key)
        .then(value => (value ? value : executeAndCache()))
        // Error
        .catch(() => executeAndCache())
    );
  };
}

module.exports = cache;
<commit_msg>Fix cache key and return value on first call<commit_after>const hash = require('object-hash');

const toSafeObject = obj => JSON.parse(JSON.stringify(obj || {}));

function cache(func, options) {
  return (root, args, context) => {
    if (!context.resolverCache) {
      throw new Error('Missing resolverCache property on the Graphql context.');
    }

    const key = `${hash(func)}:${hash(toSafeObject(root))}:${hash(toSafeObject(args))}`;
    const executeAndCache = () =>
      Promise.resolve(func(root, args, context)).then((value) => {
        context.resolverCache.set(key, value, options);
        return value;
      });

    return (
      context.resolverCache
        .get(key)
        .then(value => (value ? value : executeAndCache()))
        // Error
        .catch(() => executeAndCache())
    );
  };
}

module.exports = cache;
<|endoftext|>


<commit_before>var Promise = require('promise');
var shexjs = require("shex");
var n3 = require("n3");

var DefaultBase = "";

function Validator(schemaText, dataText, callbacks, options) {
    this.callbacks = callbacks;
    this.options = options;

    this.updateSchema(location.origin + '/schema.shex', schemaText);
    this.updateData(dataText);

    // console.log("validator has instantiated");
    // console.log("callbacks:\n",callbacks);
    // console.log("options:\n",options);

}

Validator.prototype = {
    updateSchema: function (base, schemaText) {
        this.schema = parseSchema(base ,schemaText);
        // this.schema = schemaParser.parseSchema(schemaText);
        this.schema.done(this.callbacks.schemaParsed, this.callbacks.schemaParseError);
        // var _schema = shexjs.Parser.construct(DefaultBase).parse(schemaText);
        // console.log('UPDATING THE FUCKIGN Schema',this.schema, _schema);
    },
    updateData: function (dataText) {
        this.data = parseData(dataText);
        // this.data = dataParser.parseData(dataText);
        this.data.done(this.callbacks.dataParsed, this.callbacks.dataParseError);
    },
    findShapes: function () {
        var _this = this;
        return Promise.all([this.schema, this.data]).then(function (a) {
            console.log('showing shapes');
            console.log(this.schema);
            console.log(this.data);
        });
    },
    validate: function(startingNodes) {
        var _this = this;
        console.log('validate function',_this);
        return Promise.all([this.schema, this.data, this.options]).then(function (a) {
            console.log(a);
            var node = Object.keys(a[2].resourceShapeMap)[0];
            var result = shexjs.Validator.construct(a[0].schema).validate(a[1].db, node, a[2].resourceShapeMap[node]);
            console.log('callbacks in validator',_this.callbacks);
            // console.log('validation results:',result);
            // return validator.validate(
            //     a[0].schema,                       // Schema
            //     a[0].resolver,
            //     startingNodes,      // Starting Node
            //     a[1].db,                       // db
            //     a[1].resolver,
            //     _this.options.closedShapes,
            //     _this.callbacks.validationResult);
            return cleanResult(result, _this.callbacks.validationResult)
        });
    }
};

module.exports.Validator = Validator;

function parseData(dataText){
    return new Promise(function (resolve, reject) {

        var db = n3.Store();
        n3.Parser({documentIRI: DefaultBase, format: "text/turtle"}).parse(dataText, function (error, triple, prefixes) {
            console.log('db', db);
            console.log('DB');
            if (error) {
                // throw Error("error parsing " + data + ": " + error);
                reject(parseN3Error(error));
            } else if (triple) {
                db.addTriple(triple)
            // console.log(triple.subject, triple.predicate, triple.object, '.');
            } else {
                resolve({db: db, triples:db.getTriples()});
            }
        });

    });
}

function parseSchema(base, schemaText) {
    return new Promise(function (resolve, reject) {
        var schema;
        try {
            schema = shexjs.Parser.construct(base).parse(schemaText);
        }
        catch (e) {
            reject(e);
        }
        resolve({schema: schema, shapes: schema.shapes});

    });
};

function cleanResult(result, callback){
    console.log('validation result', result);
    var errors = [];
    var solutions = [];
    if (result.type == 'Failure'){
        errors = result.errors;
    } else {
        solutions = result.solution.solutions;
    }
    console.log('errors',errors,'passed',errors.length === 0);
    var clean_result = {
            errors: errors,
            matches: solutions,
            startingResource: 'startingResource',
            passed: errors.length === 0,
            full_result:result
        };
    console.log('clean_result',clean_result);
    return callback(clean_result);
}

function parseN3Error(error) {
    var line = error.message.match(/line [0-9]*/g);

    line = (line && line.length > 0 && line[0].length > 5)?Number(line[0].substr(5)):null;

    return {
        message: error.message,
        line: line,
        column: 0
    }
}
<commit_msg>testing changes<commit_after>var Promise = require('promise');
var shexjs = require("shex");
var n3 = require("n3");

var DefaultBase = "";

function Validator(schemaText, dataText, callbacks, options) {
    this.callbacks = callbacks;
    this.options = options;

    this.updateSchema(location.origin + '/schema.shex', schemaText);
    this.updateData(dataText);

    // console.log("validator has instantiated");
    // console.log("callbacks:\n",callbacks);
    // console.log("options:\n",options);

}

Validator.prototype = {
    updateSchema: function (base, schemaText) {
        this.schema = parseSchema(base ,schemaText);
        // this.schema = schemaParser.parseSchema(schemaText);
        this.schema.done(this.callbacks.schemaParsed, this.callbacks.schemaParseError);
        // var _schema = shexjs.Parser.construct(DefaultBase).parse(schemaText);
        // console.log('UPDATING THE FUCKIGN Schema',this.schema, _schema);
    },
    updateData: function (dataText) {
        this.data = parseData(dataText);
        // this.data = dataParser.parseData(dataText);
        this.data.done(this.callbacks.dataParsed, this.callbacks.dataParseError);
    },
    findShapes: function () {
        var _this = this;
        return Promise.all([this.schema, this.data]).then(function (a) {
            console.log('showing shapes');
            console.log(this.schema);
            console.log(this.data);
        });
    },
    validate: function(startingNodes) {
        var _this = this;
        console.log('validate function',_this);
        return Promise.all([this.schema, this.data, this.options]).then(function (a) {
            console.log(a);
            var node = Object.keys(a[2].resourceShapeMap)[0];
            var result = shexjs.Validator.construct(a[0].schema).validate(a[1].db, node, a[2].resourceShapeMap[node]);
            console.log('callbacks in validator',_this.callbacks);
            // console.log('validation results:',result);
            // return validator.validate(
            //     a[0].schema,                       // Schema
            //     a[0].resolver,
            //     startingNodes,      // Starting Node
            //     a[1].db,                       // db
            //     a[1].resolver,
            //     _this.options.closedShapes,
            //     _this.callbacks.validationResult);
            return cleanResult(result, _this.callbacks.validationResult)
        });
    }
};

module.exports.Validator = Validator;

function parseData(dataText){
    console.log('split data');
    console.log(dataText.split("\n"));
    return new Promise(function (resolve, reject) {

        var db = n3.Store();
        n3.Parser({documentIRI: DefaultBase, format: "text/turtle"}).parse(dataText, function (error, triple, prefixes) {
            console.log('db', db);
            console.log('DB');
            if (error) {
                // throw Error("error parsing " + data + ": " + error);
                reject(parseN3Error(error));
            } else if (triple) {
                db.addTriple(triple)
            // console.log(triple.subject, triple.predicate, triple.object, '.');
            } else {
                resolve({db: db, triples:db.getTriples()});
            }
        });

    });
}

function parseSchema(base, schemaText) {
    return new Promise(function (resolve, reject) {
        var schema;
        try {
            schema = shexjs.Parser.construct(base).parse(schemaText);
        }
        catch (e) {
            reject(e);
        }
        resolve({schema: schema, shapes: schema.shapes});

    });
};

function cleanResult(result, callback){
    console.log('validation result', result);
    var errors = [];
    var solutions = [];
    if (result.type == 'Failure'){
        errors = result.errors;
    } else {
        solutions = result.solution.solutions;
    }
    console.log('errors',errors,'passed',errors.length === 0);
    var clean_result = {
            errors: errors,
            matches: solutions,
            startingResource: 'startingResource',
            passed: errors.length === 0,
            full_result:result
        };
    console.log('clean_result',clean_result);
    return callback(clean_result);
}

function parseN3Error(error) {
    var line = error.message.match(/line [0-9]*/g);

    line = (line && line.length > 0 && line[0].length > 5)?Number(line[0].substr(5)):null;

    return {
        message: error.message,
        line: line,
        column: 0
    }
}
<|endoftext|>


<commit_before>import campusMap from './map_component'
import MapCtrl from './map_controller';

import campusMapControls from './controls/map-controls_component';
import MapControlsCtrl from './controls/map-controls_controller';

import MapDetailCtrl from './detail/map-detail_controller';

import MAP_SETTINGS from './constants/map-settings_constant';
import MAP_ICONS from './constants/map-icons_constant';

// development only
//
import templates from './_templates';
//
// ----------------

export default angular.module('campusMap', [])
	.run(templates)
  .controller('MapCtrl', MapCtrl)
  .controller('MapControlsCtrl', MapControlsCtrl)
  .controller('MapDetailCtrl', MapDetailCtrl)
  .component('campusMap', campusMap)
  .component('campusMapControls', campusMapControls)
  .constant('MAP_SETTINGS', MAP_SETTINGS)
  .constant('MAP_ICONS', MAP_ICONS)
 //  .factory('BuildingResource', ['$resource', function($resource) {
	//   return $resource('https://virtualtour-cms.herokuapp.com/api/v1/buildings/:id');
	// }])
  .factory('CategoryResource', ['$resource', function($resource) {
	  return $resource('https://virtualtour-cms.herokuapp.com/api/v1/categories/:id');
	}])
 //  .factory('LocationResource', ['$resource', function($resource) {
	//   return $resource('https://virtualtour-cms.herokuapp.com/api/v1/locations/:id');
	// }])
  .factory('CollectionResource', ['$resource', function($resource) {
	  return $resource('https://virtualtour-cms.herokuapp.com/api/v1/feature-collections/:id');
	}])
  .factory('FeatureResource', ['$resource', function($resource) {
	  return $resource('https://virtualtour-cms.herokuapp.com/api/v1/features/:id');
	}])<commit_msg>Remove remaining $resources factories<commit_after>import campusMap from './map_component'
import MapCtrl from './map_controller';

import campusMapControls from './controls/map-controls_component';
import MapControlsCtrl from './controls/map-controls_controller';

import MapDetailCtrl from './detail/map-detail_controller';

import MAP_SETTINGS from './constants/map-settings_constant';
import MAP_ICONS from './constants/map-icons_constant';

// development only
//
import templates from './_templates';
//
// ----------------

export default angular.module('campusMap', [])
	.run(templates)
  .controller('MapCtrl', MapCtrl)
  .controller('MapControlsCtrl', MapControlsCtrl)
  .controller('MapDetailCtrl', MapDetailCtrl)
  .component('campusMap', campusMap)
  .component('campusMapControls', campusMapControls)
  .constant('MAP_SETTINGS', MAP_SETTINGS)
  .constant('MAP_ICONS', MAP_ICONS)
 //  .factory('BuildingResource', ['$resource', function($resource) {
	//   return $resource('https://virtualtour-cms.herokuapp.com/api/v1/buildings/:id');
	// }])
 //  .factory('CategoryResource', ['$resource', function($resource) {
	//   return $resource('https://virtualtour-cms.herokuapp.com/api/v1/categories/:id');
	// }])
 //  .factory('LocationResource', ['$resource', function($resource) {
	//   return $resource('https://virtualtour-cms.herokuapp.com/api/v1/locations/:id');
	// }])
 //  .factory('CollectionResource', ['$resource', function($resource) {
	//   return $resource('https://virtualtour-cms.herokuapp.com/api/v1/feature-collections/:id');
	// }])
 //  .factory('FeatureResource', ['$resource', function($resource) {
	//   return $resource('https://virtualtour-cms.herokuapp.com/api/v1/features/:id');
	// }])<|endoftext|>


<commit_before>// regeneratorRuntime is needed for async await
import 'babel-polyfill'

import { getRandomId } from './utils'

const mainMethods = [
  'build',
  'configure',
  'connect',
  'console',
  'check',
  'create',
  'deploy',
  'dump',
  'exec',
  'get',
  'init',
  'install',
  'map',
  'push',
  'read',
  'replace',
  'run',
  'set',
  'start',
  'write'
]
const subModules = mainMethods.map(method => require(`./methods/${method}`))
const collectionNames = ['servers', 'types']

class Teleport {
  constructor (program) {
    // welcome
    console.log('\n\n** Welcome to teleport node-side ! **\n'.bold)
    // bind methods from sub modules
    subModules.forEach(module =>
      Object.keys(module).forEach(key => {
        this[key] = module[key].bind(this)
      })
    )
    // bind program
    this.program = program
    const app = this.app = {}
    this.setAppEnvironment()
    // level is saying
    // if you are actually working in a project, the app itself,
    // or in somewhere not defined yet
    this.level = null
    const project = this.project = {}
    // determine where we are
    this.currentDir = process.cwd()
    // if we are inside of the app folder itself better is to leave, because
    // we don't have anything to do here
    this.isAppDir = this.currentDir === app.dir.replace(/\/$/, '')
    if (this.isAppDir) {
      this.consoleWarn(`You are in the ${app.package.name} folder... Better is to exit :)`)
      process.exit()
    }
    // if we want to create something, then we return because we are not in a project yet
    if (typeof program.create !== 'undefined') {
      // in the case where no project name was given, we need to invent one based on a uniq ID
      if (typeof program.name !== 'string') {
        this.consoleWarn('You didn\'t mention any particular name, we are going to give you one')
        program.name = `app-${getRandomId()}`
      }
      this.level = 'project'
      return
    }
    // if it is not a create method, it means that we are either in a scope or in a
    // project to do something
    this.currentConfig = this.getConfig(this.currentDir)
    // split given where we are
    if (this.currentConfig || typeof this.program.init !== 'undefined') {
      this.level = 'project'
      project.dir = this.currentDir
      this.setProjectEnvironment()
    }
    // exit else
    if (!this.level) {
      this.consoleWarn('You are not in a project folder')
      process.exit()
    }
  }

  launch () {
    // unpack
    const { program } = this
    // we can pass args to the cli, either object, or direct values or nothing
    this.kwarg = null
    if (typeof program.kwarg === 'string') {
      this.kwarg = program.kwarg[0] === '{'
      ? JSON.parse(program.kwarg)
      : program.kwarg
    }
    // it is maybe a call of a main mainMethods
    const programmedMethod = mainMethods.find(method => program[method])
    if (this[programmedMethod]) {
      // check for mapping ? let's see if there is already a collections of arg defined
      if (typeof program.collections === 'undefined') {
        // so there is no clear mapping to collections
        // but maybe there are some pluralized args
        // suggesting that the method has to be done
        // with a map protocol
        const collectionSlugs = []
        collectionNames.forEach(collectionName => {
          const value = program[collectionName]
          if (typeof value === 'string') {
            if (value === 'all') {
              collectionSlugs.push(`${collectionName}ByName`)
            } else {
              collectionSlugs.push(`${collectionName}ByName[${value}]`)
            }
          }
        })
        const collections = collectionSlugs.join(',')
        // if collections is not empty, so yes, it is mapping
        // method request, do it and return in that case
        if (collections !== '') {
          program.collections = collections
          program.method = programmedMethod
          this.map()
          return
        }
      }
      // if no collection, it is a simple unit call
      // call it
      this[programmedMethod]()
      return
    }
    // default return
    this.consoleWarn('Welcome to teleport... But you didn\'t specify any particular command !')
  }

  pass () {}
}

export default Teleport
<commit_msg>remove axit when we are in the app<commit_after>// regeneratorRuntime is needed for async await
import 'babel-polyfill'

import { getRandomId } from './utils'

const mainMethods = [
  'build',
  'configure',
  'connect',
  'console',
  'check',
  'create',
  'deploy',
  'dump',
  'exec',
  'get',
  'init',
  'install',
  'map',
  'push',
  'read',
  'replace',
  'run',
  'set',
  'start',
  'write'
]
const subModules = mainMethods.map(method => require(`./methods/${method}`))
const collectionNames = ['servers', 'types']

class Teleport {
  constructor (program) {
    // welcome
    console.log('\n\n** Welcome to teleport node-side ! **\n'.bold)
    // bind methods from sub modules
    subModules.forEach(module =>
      Object.keys(module).forEach(key => {
        this[key] = module[key].bind(this)
      })
    )
    // bind program
    this.program = program
    const app = this.app = {}
    this.setAppEnvironment()
    // level is saying
    // if you are actually working in a project, the app itself,
    // or in somewhere not defined yet
    this.level = null
    const project = this.project = {}
    // determine where we are
    this.currentDir = process.cwd()
    // if we want to create something, then we return because we are not in a project yet
    if (typeof program.create !== 'undefined') {
      // in the case where no project name was given, we need to invent one based on a uniq ID
      if (typeof program.name !== 'string') {
        this.consoleWarn('You didn\'t mention any particular name, we are going to give you one')
        program.name = `app-${getRandomId()}`
      }
      this.level = 'project'
      return
    }
    // if it is not a create method, it means that we are either in a scope or in a
    // project to do something
    this.currentConfig = this.getConfig(this.currentDir)
    // split given where we are
    if (this.currentConfig || typeof this.program.init !== 'undefined') {
      this.level = 'project'
      project.dir = this.currentDir
      this.setProjectEnvironment()
    }
    // exit else
    if (!this.level) {
      this.consoleWarn('You are not in a project folder')
      process.exit()
    }
  }

  launch () {
    // unpack
    const { program } = this
    // we can pass args to the cli, either object, or direct values or nothing
    this.kwarg = null
    if (typeof program.kwarg === 'string') {
      this.kwarg = program.kwarg[0] === '{'
      ? JSON.parse(program.kwarg)
      : program.kwarg
    }
    // it is maybe a call of a main mainMethods
    const programmedMethod = mainMethods.find(method => program[method])
    if (this[programmedMethod]) {
      // check for mapping ? let's see if there is already a collections of arg defined
      if (typeof program.collections === 'undefined') {
        // so there is no clear mapping to collections
        // but maybe there are some pluralized args
        // suggesting that the method has to be done
        // with a map protocol
        const collectionSlugs = []
        collectionNames.forEach(collectionName => {
          const value = program[collectionName]
          if (typeof value === 'string') {
            if (value === 'all') {
              collectionSlugs.push(`${collectionName}ByName`)
            } else {
              collectionSlugs.push(`${collectionName}ByName[${value}]`)
            }
          }
        })
        const collections = collectionSlugs.join(',')
        // if collections is not empty, so yes, it is mapping
        // method request, do it and return in that case
        if (collections !== '') {
          program.collections = collections
          program.method = programmedMethod
          this.map()
          return
        }
      }
      // if no collection, it is a simple unit call
      // call it
      this[programmedMethod]()
      return
    }
    // default return
    this.consoleWarn('Welcome to teleport... But you didn\'t specify any particular command !')
  }

  pass () {}
}

export default Teleport
<|endoftext|>


<commit_before>var _ = require( "lodash" );
var Monologue = require( "monologue.js" );
var when = require( "when" );
var connectionFn = require( "./connectionFsm.js" );
var topologyFn = require( "./topology.js" );
var postal = require( "postal" );
var uuid = require( "node-uuid" );
var dispatch = postal.channel( "rabbit.dispatch" );
var responses = postal.channel( "rabbit.responses" );
var signal = postal.channel( "rabbit.ack" );

var unhandledStrategies = {
	nackOnUnhandled: function( message ) {
		message.nack();
	},
	rejectOnUnhandled: function( message ) {
		message.reject();
	},
	customOnUnhandled: function() {}
};
var returnedStrategies = {
	customOnReturned: function() {}
};
unhandledStrategies.onUnhandled = unhandledStrategies.nackOnUnhandled;
returnedStrategies.onReturned = returnedStrategies.customOnReturned;

var serializers = {
	"application/json": {
		deserialize: function( bytes, encoding ) {
			return JSON.parse( bytes.toString( encoding || "utf8" ) );
		},
		serialize: function( object ) {
			return new Buffer( JSON.stringify( object ), "utf8" );
		}
	},
	"application/octet-stream": {
		deserialize: function( bytes ) {
			return bytes;
		},
		serialize: function( bytes ) {
			return bytes;
		}
	},
	"text/plain": {
		deserialize: function( bytes, encoding ) {
			return bytes.toString( encoding || "utf8" );
		},
		serialize: function( string ) {
			return new Buffer( string, "utf8" );
		}
	}
};

var Broker = function() {
	this.connections = {};
	this.hasHandles = false;
	this.autoNack = false;
	this.serializers = serializers;
	this.configurations = {};
	_.bindAll( this );
};

Broker.prototype.addConnection = function( options ) {
    var self = this

    return when.promise( function( resolve, reject ) {
	    var name = options ? ( options.name || "default" ) : "default";
	    options = options || {};
	    options.name = name;
	    options.retryLimit = options.retryLimit || 3;
	    options.failAfter = options.failAfter || 60;
	    var connection;

	    if ( !self.connections[ name ] ) {
	        connection = connectionFn( options );
	        var topology = topologyFn( connection, options || {}, serializers, unhandledStrategies, returnedStrategies );
	        connection.on( "connected", function() {
	            self.emit( "connected", connection );
                self.emit( connection.name + ".connection.opened", connection );
                self.setAckInterval( 500 );
                return resolve( topology )
	        } );
	        connection.on( "closed", function() {
                self.emit( "closed", connection );
                self.emit( connection.name + ".connection.closed", connection );
                return reject( new Error( "connection closed" ) )
	        } );
	        connection.on( "failed", function( err ) {
                self.emit( "failed", connection );
                self.emit( name + ".connection.failed", err );
                return reject( err )
	        } );
	        connection.on( "unreachable", function() {
                self.emit( "unreachable", connection );
                self.emit( name + ".connection.unreachable" );
                self.clearAckInterval();
                return reject( new Error( "connection unreachable" ) )
	        } );
	        connection.on( "return", function(raw) {
                self.emit( "return", raw);
	        } );
            self.connections[ name ] = topology;
	    } else {
            connection = self.connections[ name ];
            connection.connection.connect();
            resolve( connection );
	    }
    } )
};

Broker.prototype.addExchange = function( name, type, options, connectionName ) {
	connectionName = connectionName || "default";
	if ( _.isObject( name ) ) {
		options = name;
		connectionName = type;
	} else {
		options.name = name;
		options.type = type;
	}
	return this.connections[ connectionName ].createExchange( options );
};

Broker.prototype.addQueue = function( name, options, connectionName ) {
	connectionName = connectionName || "default";
	options.name = name;
	if ( options.subscribe && !this.hasHandles ) {
		console.warn( "Subscription to '" + name + "' was started without any handlers. This will result in lost messages!" );
	}
	return this.connections[ connectionName ].createQueue( options, connectionName );
};

Broker.prototype.addSerializer = function( contentType, serializer ) {
	serializers[ contentType ] = serializer;
};

Broker.prototype.batchAck = function() {
	signal.publish( "ack", {} );
};

Broker.prototype.bindExchange = function( source, target, keys, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].createBinding( { source: source, target: target, keys: keys } );
};

Broker.prototype.bindQueue = function( source, target, keys, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].createBinding(
		{ source: source, target: target, keys: keys, queue: true },
		connectionName
	);
};

Broker.prototype.clearAckInterval = function() {
	clearInterval( this.ackIntervalId );
};

Broker.prototype.closeAll = function( reset ) {
	// COFFEE IS FOR CLOSERS
	var closers = _.map( this.connections, function( connection ) {
		return this.close( connection.name, reset );
	}.bind( this ) );
	return when.all( closers );
};

Broker.prototype.close = function( connectionName, reset ) {
	connectionName = connectionName || "default";
	var connection = this.connections[ connectionName ].connection;
	if ( !_.isUndefined( connection ) ) {
		if( reset ) {
			this.connections[ connectionName ].reset();
		}
		return connection.close( reset );
	} else {
		return when( true );
	}
};

Broker.prototype.deleteExchange = function( name, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].deleteExchange( name );
};

Broker.prototype.deleteQueue = function( name, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].deleteQueue( name );
};

Broker.prototype.getExchange = function( name, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].channels[ "exchange:" + name ];
};

Broker.prototype.getQueue = function( name, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].channels[ "queue:" + name ];
};

Broker.prototype.handle = function( messageType, handler, queueName, context ) {
	this.hasHandles = true;
	var options;
	if( _.isString( messageType ) ) {
		options = {
			type: messageType,
			queue: queueName || "*",
			context: context,
			autoNack: this.autoNack,
			handler: handler
		}
	} else {
		options = messageType;
		options.autoNack = options.autoNack === false ? false : true;
		options.queue = options.queue || (options.type ? '*' : '#');
		options.handler = options.handler || handler;
	}
	var parts = [];
	if( options.queue === "#" ) {
		parts.push( "#" );
	} else {
		parts.push( options.queue.replace( /[.]/g, "-" ) );
		if( options.type !== "" ) {
			parts.push( options.type || "#" );
		}
	}

	var target = parts.join( "." );
	var subscription = dispatch.subscribe( target, options.handler.bind( options.context ) );
	if ( options.autoNack ) {
		subscription.catch( function( err, msg ) {
			console.log( "Handler for '" + target + "' failed with:", err.stack );
			msg.nack();
		} );
	}
	subscription.remove = subscription.unsubscribe;
	return subscription;
};

Broker.prototype.ignoreHandlerErrors = function() {
	this.autoNack = false;
};

Broker.prototype.nackOnError = function() {
	this.autoNack = true;
};

Broker.prototype.nackUnhandled = function() {
	unhandledStrategies.onUnhandled = unhandledStrategies.nackOnUnhandled;
};

Broker.prototype.onUnhandled = function( handler ) {
	unhandledStrategies.onUnhandled = unhandledStrategies.customOnUnhandled = handler;
};

Broker.prototype.rejectUnhandled = function() {
	unhandledStrategies.onUnhandled = unhandledStrategies.rejectOnUnhandled;
};

Broker.prototype.onReturned = function( handler ) {
	returnedStrategies.onReturned = returnedStrategies.customOnReturned = handler;
};

Broker.prototype.publish = function( exchangeName, type, message, routingKey, correlationId, connectionName, sequenceNo ) {
	var timestamp = Date.now();
	var options;
	if ( _.isObject( type ) ) {
		options = type;
		connectionName = message || options.connectionName || "default";
	} else {
		connectionName = connectionName || message.connectionName || "default";
		options = {
			appId: this.appId,
			type: type,
			body: message,
			routingKey: routingKey,
			correlationId: correlationId,
			sequenceNo: sequenceNo,
			timestamp: timestamp,
			headers: {},
			connectionName: connectionName
		};
	}
	var connection = this.connections[ connectionName ].options;
	if( connection.publishTimeout ) {
		options.connectionPublishTimeout = connection.publishTimeout;
	}
	return this.getExchange( exchangeName, connectionName )
		.publish( options );
};

Broker.prototype.request = function( exchangeName, options, connectionName ) {
	connectionName = connectionName || options.connectionName || 'default';
	var requestId = uuid.v1();
	options.messageId = requestId;
	options.connectionName = connectionName;
	var connection = this.connections[ connectionName ].options;
	var exchange = this.getExchange( exchangeName, connectionName );
	var publishTimeout = options.timeout || exchange.publishTimeout || connection.publishTimeout || 500;
	var replyTimeout = options.replyTimeout || exchange.replyTimeout || connection.replyTimeout || ( publishTimeout * 2 );

	return when.promise( function( resolve, reject, notify ) {
		var timeout = setTimeout( function() {
			subscription.unsubscribe();
			reject( new Error( "No reply received within the configured timeout of " + replyTimeout + " ms" ) );
		}, replyTimeout );
		var subscription = responses.subscribe( requestId, function( message ) {
			if ( message.properties.headers[ "sequence_end" ] ) { // jshint ignore:line
				clearTimeout( timeout );
				resolve( message );
				subscription.unsubscribe();
			} else {
				notify( message );
			}
		} );
		this.publish( exchangeName, options );

	}.bind( this ) );
};

Broker.prototype.reset = function() {
	this.connections = {};
	this.configurations = {};
};

Broker.prototype.retry = function( connectionName ) {
	connectionName = connectionName || "default";
	var config = this.configurations[ connectionName ];
	return this.configure( config );
};

Broker.prototype.setAckInterval = function( interval ) {
	if ( this.ackIntervalId ) {
		this.clearAckInterval();
	}
	this.ackIntervalId = setInterval( this.batchAck, interval );
};

Broker.prototype.shutdown = function() {
	return this.closeAll( true )
		.then( function() {
			this.clearAckInterval();
		}.bind( this ) );
};

Broker.prototype.startSubscription = function( queueName, exclusive, connectionName ) {
	if ( !this.hasHandles ) {
		console.warn( "Subscription to '" + queueName + "' was started without any handlers. This will result in lost messages!" );
	}
	if( _.isString( exclusive ) ) {
		connectionName = exclusive;
		exclusive = false;
	}
	var queue = this.getQueue( queueName, connectionName );
	if ( queue ) {
		queue.subscribe( queue, exclusive );
		return queue;
	} else {
		throw new Error( "No queue named '" + queueName + "' for connection '" + connectionName + "'. Subscription failed." );
	}
};

Broker.prototype.stopSubscription = function( queueName, connectionName ) {
	var queue = this.getQueue( queueName, connectionName );
	if( queue ) {
		queue.unsubscribe();
		return queue;
	} else {
		throw new Error( "No queue named '" + queueName + "' for connection '" + connectionName + "'. Unsubscribe failed." );
	}
}

require( "./config.js" )( Broker );

Monologue.mixInto( Broker );

var broker = new Broker();

module.exports = broker;
<commit_msg>src/index.js: minor syntax fix<commit_after>var _ = require( "lodash" );
var Monologue = require( "monologue.js" );
var when = require( "when" );
var connectionFn = require( "./connectionFsm.js" );
var topologyFn = require( "./topology.js" );
var postal = require( "postal" );
var uuid = require( "node-uuid" );
var dispatch = postal.channel( "rabbit.dispatch" );
var responses = postal.channel( "rabbit.responses" );
var signal = postal.channel( "rabbit.ack" );

var unhandledStrategies = {
	nackOnUnhandled: function( message ) {
		message.nack();
	},
	rejectOnUnhandled: function( message ) {
		message.reject();
	},
	customOnUnhandled: function() {}
};
var returnedStrategies = {
	customOnReturned: function() {}
};
unhandledStrategies.onUnhandled = unhandledStrategies.nackOnUnhandled;
returnedStrategies.onReturned = returnedStrategies.customOnReturned;

var serializers = {
	"application/json": {
		deserialize: function( bytes, encoding ) {
			return JSON.parse( bytes.toString( encoding || "utf8" ) );
		},
		serialize: function( object ) {
			return new Buffer( JSON.stringify( object ), "utf8" );
		}
	},
	"application/octet-stream": {
		deserialize: function( bytes ) {
			return bytes;
		},
		serialize: function( bytes ) {
			return bytes;
		}
	},
	"text/plain": {
		deserialize: function( bytes, encoding ) {
			return bytes.toString( encoding || "utf8" );
		},
		serialize: function( string ) {
			return new Buffer( string, "utf8" );
		}
	}
};

var Broker = function() {
	this.connections = {};
	this.hasHandles = false;
	this.autoNack = false;
	this.serializers = serializers;
	this.configurations = {};
	_.bindAll( this );
};

Broker.prototype.addConnection = function( options ) {
    var self = this

    return when.promise( function( resolve, reject ) {
	    var name = options ? ( options.name || "default" ) : "default";
	    options = options || {};
	    options.name = name;
	    options.retryLimit = options.retryLimit || 3;
	    options.failAfter = options.failAfter || 60;
	    var connection;

	    if ( !self.connections[ name ] ) {
	        connection = connectionFn( options );
	        var topology = topologyFn( connection, options || {}, serializers, unhandledStrategies, returnedStrategies );
	        connection.on( "connected", function() {
	            self.emit( "connected", connection );
                self.emit( connection.name + ".connection.opened", connection );
                self.setAckInterval( 500 );
                return resolve( topology )
	        } );
	        connection.on( "closed", function() {
                self.emit( "closed", connection );
                self.emit( connection.name + ".connection.closed", connection );
                return reject( new Error( "connection closed" ) )
	        } );
	        connection.on( "failed", function( err ) {
                self.emit( "failed", connection );
                self.emit( name + ".connection.failed", err );
                return reject( err )
	        } );
	        connection.on( "unreachable", function() {
                self.emit( "unreachable", connection );
                self.emit( name + ".connection.unreachable" );
                self.clearAckInterval();
                return reject( new Error( "connection unreachable" ) )
	        } );
	        connection.on( "return", function(raw) {
                self.emit( "return", raw );
	        } );
            self.connections[ name ] = topology;
	    } else {
            connection = self.connections[ name ];
            connection.connection.connect();
            resolve( connection );
	    }
    } )
};

Broker.prototype.addExchange = function( name, type, options, connectionName ) {
	connectionName = connectionName || "default";
	if ( _.isObject( name ) ) {
		options = name;
		connectionName = type;
	} else {
		options.name = name;
		options.type = type;
	}
	return this.connections[ connectionName ].createExchange( options );
};

Broker.prototype.addQueue = function( name, options, connectionName ) {
	connectionName = connectionName || "default";
	options.name = name;
	if ( options.subscribe && !this.hasHandles ) {
		console.warn( "Subscription to '" + name + "' was started without any handlers. This will result in lost messages!" );
	}
	return this.connections[ connectionName ].createQueue( options, connectionName );
};

Broker.prototype.addSerializer = function( contentType, serializer ) {
	serializers[ contentType ] = serializer;
};

Broker.prototype.batchAck = function() {
	signal.publish( "ack", {} );
};

Broker.prototype.bindExchange = function( source, target, keys, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].createBinding( { source: source, target: target, keys: keys } );
};

Broker.prototype.bindQueue = function( source, target, keys, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].createBinding(
		{ source: source, target: target, keys: keys, queue: true },
		connectionName
	);
};

Broker.prototype.clearAckInterval = function() {
	clearInterval( this.ackIntervalId );
};

Broker.prototype.closeAll = function( reset ) {
	// COFFEE IS FOR CLOSERS
	var closers = _.map( this.connections, function( connection ) {
		return this.close( connection.name, reset );
	}.bind( this ) );
	return when.all( closers );
};

Broker.prototype.close = function( connectionName, reset ) {
	connectionName = connectionName || "default";
	var connection = this.connections[ connectionName ].connection;
	if ( !_.isUndefined( connection ) ) {
		if( reset ) {
			this.connections[ connectionName ].reset();
		}
		return connection.close( reset );
	} else {
		return when( true );
	}
};

Broker.prototype.deleteExchange = function( name, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].deleteExchange( name );
};

Broker.prototype.deleteQueue = function( name, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].deleteQueue( name );
};

Broker.prototype.getExchange = function( name, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].channels[ "exchange:" + name ];
};

Broker.prototype.getQueue = function( name, connectionName ) {
	connectionName = connectionName || "default";
	return this.connections[ connectionName ].channels[ "queue:" + name ];
};

Broker.prototype.handle = function( messageType, handler, queueName, context ) {
	this.hasHandles = true;
	var options;
	if( _.isString( messageType ) ) {
		options = {
			type: messageType,
			queue: queueName || "*",
			context: context,
			autoNack: this.autoNack,
			handler: handler
		}
	} else {
		options = messageType;
		options.autoNack = options.autoNack === false ? false : true;
		options.queue = options.queue || (options.type ? '*' : '#');
		options.handler = options.handler || handler;
	}
	var parts = [];
	if( options.queue === "#" ) {
		parts.push( "#" );
	} else {
		parts.push( options.queue.replace( /[.]/g, "-" ) );
		if( options.type !== "" ) {
			parts.push( options.type || "#" );
		}
	}

	var target = parts.join( "." );
	var subscription = dispatch.subscribe( target, options.handler.bind( options.context ) );
	if ( options.autoNack ) {
		subscription.catch( function( err, msg ) {
			console.log( "Handler for '" + target + "' failed with:", err.stack );
			msg.nack();
		} );
	}
	subscription.remove = subscription.unsubscribe;
	return subscription;
};

Broker.prototype.ignoreHandlerErrors = function() {
	this.autoNack = false;
};

Broker.prototype.nackOnError = function() {
	this.autoNack = true;
};

Broker.prototype.nackUnhandled = function() {
	unhandledStrategies.onUnhandled = unhandledStrategies.nackOnUnhandled;
};

Broker.prototype.onUnhandled = function( handler ) {
	unhandledStrategies.onUnhandled = unhandledStrategies.customOnUnhandled = handler;
};

Broker.prototype.rejectUnhandled = function() {
	unhandledStrategies.onUnhandled = unhandledStrategies.rejectOnUnhandled;
};

Broker.prototype.onReturned = function( handler ) {
	returnedStrategies.onReturned = returnedStrategies.customOnReturned = handler;
};

Broker.prototype.publish = function( exchangeName, type, message, routingKey, correlationId, connectionName, sequenceNo ) {
	var timestamp = Date.now();
	var options;
	if ( _.isObject( type ) ) {
		options = type;
		connectionName = message || options.connectionName || "default";
	} else {
		connectionName = connectionName || message.connectionName || "default";
		options = {
			appId: this.appId,
			type: type,
			body: message,
			routingKey: routingKey,
			correlationId: correlationId,
			sequenceNo: sequenceNo,
			timestamp: timestamp,
			headers: {},
			connectionName: connectionName
		};
	}
	var connection = this.connections[ connectionName ].options;
	if( connection.publishTimeout ) {
		options.connectionPublishTimeout = connection.publishTimeout;
	}
	return this.getExchange( exchangeName, connectionName )
		.publish( options );
};

Broker.prototype.request = function( exchangeName, options, connectionName ) {
	connectionName = connectionName || options.connectionName || 'default';
	var requestId = uuid.v1();
	options.messageId = requestId;
	options.connectionName = connectionName;
	var connection = this.connections[ connectionName ].options;
	var exchange = this.getExchange( exchangeName, connectionName );
	var publishTimeout = options.timeout || exchange.publishTimeout || connection.publishTimeout || 500;
	var replyTimeout = options.replyTimeout || exchange.replyTimeout || connection.replyTimeout || ( publishTimeout * 2 );

	return when.promise( function( resolve, reject, notify ) {
		var timeout = setTimeout( function() {
			subscription.unsubscribe();
			reject( new Error( "No reply received within the configured timeout of " + replyTimeout + " ms" ) );
		}, replyTimeout );
		var subscription = responses.subscribe( requestId, function( message ) {
			if ( message.properties.headers[ "sequence_end" ] ) { // jshint ignore:line
				clearTimeout( timeout );
				resolve( message );
				subscription.unsubscribe();
			} else {
				notify( message );
			}
		} );
		this.publish( exchangeName, options );

	}.bind( this ) );
};

Broker.prototype.reset = function() {
	this.connections = {};
	this.configurations = {};
};

Broker.prototype.retry = function( connectionName ) {
	connectionName = connectionName || "default";
	var config = this.configurations[ connectionName ];
	return this.configure( config );
};

Broker.prototype.setAckInterval = function( interval ) {
	if ( this.ackIntervalId ) {
		this.clearAckInterval();
	}
	this.ackIntervalId = setInterval( this.batchAck, interval );
};

Broker.prototype.shutdown = function() {
	return this.closeAll( true )
		.then( function() {
			this.clearAckInterval();
		}.bind( this ) );
};

Broker.prototype.startSubscription = function( queueName, exclusive, connectionName ) {
	if ( !this.hasHandles ) {
		console.warn( "Subscription to '" + queueName + "' was started without any handlers. This will result in lost messages!" );
	}
	if( _.isString( exclusive ) ) {
		connectionName = exclusive;
		exclusive = false;
	}
	var queue = this.getQueue( queueName, connectionName );
	if ( queue ) {
		queue.subscribe( queue, exclusive );
		return queue;
	} else {
		throw new Error( "No queue named '" + queueName + "' for connection '" + connectionName + "'. Subscription failed." );
	}
};

Broker.prototype.stopSubscription = function( queueName, connectionName ) {
	var queue = this.getQueue( queueName, connectionName );
	if( queue ) {
		queue.unsubscribe();
		return queue;
	} else {
		throw new Error( "No queue named '" + queueName + "' for connection '" + connectionName + "'. Unsubscribe failed." );
	}
}

require( "./config.js" )( Broker );

Monologue.mixInto( Broker );

var broker = new Broker();

module.exports = broker;
<|endoftext|>