<commit_before>/* document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names,
     class names and ids and can be nested. For example:

       elements = document.getElementsBySelect('div#main p a.external')

     Will return an array of all 'a' elements with 'external' in their
     class attribute that are contained inside 'p' elements that are
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            try {
                elements = currentContext[h].getElementsByTagName(tagName);
            }
            catch(e) {
                elements = [];
            }
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute
   Tag
*/
<commit_msg>Fixed #10783 -- Fixed Javascript error when adding a new object in admin.<commit_after>/* document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names,
     class names and ids and can be nested. For example:

       elements = document.getElementsBySelect('div#main p a.external')

     Will return an array of all 'a' elements with 'external' in their
     class attribute that are contained inside 'p' elements that are
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) {
        // ID not found or tag with that ID not found, return false.
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            try {
                elements = currentContext[h].getElementsByTagName(tagName);
            }
            catch(e) {
                elements = [];
            }
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute
   Tag
*/
<|endoftext|>


<commit_before>/*******************************************************************************
 * bootstrap
 *
 * @author       Isaac Suttell <isaac_suttell@playstation.sony.com>
 * @file         Load application settings
 ******************************************************************************/

// Modules
var nopt = require('nopt');
var _ = require('lodash');
var fs = require('fs');
var path = require('path');

/**
 * Verbose Levels
 *
 * @constants
 * @type    {Object}
 */
var VerboseLevel = {
  'VERBOSE_DEFAULT': 0,
  'VERBOSE_NORMAL': 1,
  'VERBOSE_ALL': 2,
};

/**
 * Read the config RC File
 *
 * @param     {Object}    options
 * @return    {Object}
 */
function readRc(options) {
  options = _.extend({
    rc: path.resolve('.apprc')
  }, options);

  var rc;
  try {

    if (!fs.existsSync(options.rc)) {
      throw new Error('Unable to find ' + options.rc);
    }

    rc = fs.readFileSync(options.rc, {
      encoding: 'utf8'
    });

    try {
      rc = JSON.parse(rc);
    } catch (err) {
      throw new Error('Unable to parse ' + options.rc);
    }

    return rc;
  } catch (err) {
    return {};
  }
}

/**
 * Ensure these settings are set
 *
 * @type    {Object}
 */
var defaultOptions = {
  rc: path.resolve('.apprc'),
  env: process.env.NODE_ENV || 'production',
  port: process.env.PORT || 3000,
  instances: require('os').cpus().length
};

/**
 * Get options from the command line
 *
 * @type    {Object}
 */
var cli = nopt({
  rc: path,
  env: String,
  instances: Number,
  port: Number,
  verbose: [Number, Boolean]
}, {
  'e': '--env',
  'i': '--instances',
  'p': '--port',
  'v': '--verbose',
  'vv': '--verbose 2'
}, process.argv, 2);

// Get the command
cli.command = cli.argv.remain[0];

module.exports.extend = function(config) {

  // Ensure secret isn't being saved to repo
  if (config.secret) {
    console.warn('Secret should not be saved in the config file which is saved in the repo.');
    process.exit();
  }

  // Read machine settings
  var rc = readRc(config);

  // Extend
  config = _.extend(config, rc, cli);

  // Let the app know we're booted
  config.bootstrapped = true;

  // Ensure secret is present
  if (!config.secret) {
    console.error('Unable to find secret.');
    process.exit();
  }

  // Resolve all paths
  for (var folder in config.folders) {
    if (config.folders.hasOwnProperty(folder)) {
      config.folders[folder] = path.resolve(config.folders[folder]);
    }
  }

  if (config.verbose > VerboseLevel.VERBOSE_DEFAULT) {
    console.info('Bootstrap Successful');
  }

  return config;

};
<commit_msg>switched to merge instead of extend for config<commit_after>/*******************************************************************************
 * bootstrap
 *
 * @author       Isaac Suttell <isaac_suttell@playstation.sony.com>
 * @file         Load application settings
 ******************************************************************************/

// Modules
var nopt = require('nopt');
var _ = require('lodash');
var fs = require('fs');
var path = require('path');

/**
 * Verbose Levels
 *
 * @constants
 * @type    {Object}
 */
var VerboseLevel = module.exports.VerboseLevel = {
  'VERBOSE_DEFAULT': 0,
  'VERBOSE_NORMAL': 1,
  'VERBOSE_ALL': 2,
};

/**
 * Read the config RC File
 *
 * @param     {Object}    options
 * @return    {Object}
 */
function readRc(options) {
  options = _.extend({
    rc: path.resolve('.apprc')
  }, options);

  var rc;
  try {

    if (!fs.existsSync(options.rc)) {
      throw new Error('Unable to find ' + options.rc);
    }

    rc = fs.readFileSync(options.rc, {
      encoding: 'utf8'
    });

    try {
      rc = JSON.parse(rc);
    } catch (err) {
      throw new Error('Unable to parse ' + options.rc);
    }

    return rc;
  } catch (err) {
    return {};
  }
}

/**
 * Ensure these settings are set
 *
 * @type    {Object}
 */
var defaultOptions = {
  rc: path.resolve('.apprc'),
  env: process.env.NODE_ENV || 'production',
  port: process.env.PORT || 3000,
  instances: require('os').cpus().length
};

/**
 * Get options from the command line
 *
 * @type    {Object}
 */
var cli = nopt({
  rc: path,
  env: String,
  instances: Number,
  port: Number,
  verbose: [Number, Boolean]
}, {
  'e': '--env',
  'i': '--instances',
  'p': '--port',
  'v': '--verbose',
  'vv': '--verbose 2'
}, process.argv, 2);

// Get the command
cli.command = cli.argv.remain[0];

module.exports.extend = function(config) {

  // Ensure secret isn't being saved to repo
  if (config.secret) {
    console.warn('Secret should not be saved in the config file which is saved in the repo.');
    process.exit();
  }

  // Read machine settings
  var rc = readRc(config);

  // Extend
  config = _.merge(config, rc, cli);

  // Let the app know we're booted
  config.bootstrapped = true;

  // Ensure secret is present
  if (!config.secret) {
    console.error('Unable to find secret.');
    process.exit();
  }

  // Resolve all paths
  for (var folder in config.folders) {
    if (config.folders.hasOwnProperty(folder)) {
      config.folders[folder] = path.resolve(config.folders[folder]);
    }
  }

  if (config.verbose > VerboseLevel.VERBOSE_DEFAULT) {
    console.info('Bootstrap Successful');
  }

  return config;

};
<|endoftext|>


<commit_before>import toFunctionCall from "./helpers/ast/to-function-call";
import toReference from "./helpers/ast/to-reference";

import getOption from "./helpers/get-option";
import iDOMMethod from "./helpers/idom-method";
import attrsToAttrCalls from "./helpers/attributes-to-attr-calls";
import buildChildren from "./helpers/build-children";
import extractOpenArguments from "./helpers/extract-open-arguments";
import findOtherJSX from "./helpers/find-other-jsx";
import flattenExpressions from "./helpers/flatten-expressions";
import statementsWithReturnLast from "./helpers/statements-with-return-last";

import { setupInjector } from "./helpers/inject";
import injectJSXWrapper from "./helpers/runtime/jsx-wrapper";

export default function ({ Plugin, types: t }) {
  return new Plugin("incremental-dom", { visitor : {
    Program: setupInjector,

    JSXElement: {
      enter(node) {
        let inAssignment = false;
        let inAttribute = false;
        let inCallExpression = false;
        let inCollection = false;
        let inReturnStatement = false;
        let containingJSXElement;
        let last = node;

        this.findParent((path) => {
          if (path.isJSXElement()) {
            containingJSXElement = path;
            return true;
          }
          if (path.isArrowFunctionExpression()) {
            inReturnStatement = inReturnStatement || !t.isBlockStatement(path.node.body);
            return true;
          }
          if (path.isFunction() || path.isProgram()) {
            return true;
          }
          if (path.isSequenceExpression()) {
            const expressions = path.node.expressions;
            const index = expressions.indexOf(last);
            if (index !== expressions.length - 1) {
              return true;
            }
          }
          if (path.isJSXAttribute()) {
            inAttribute = true;
          } else if (path.isAssignmentExpression() || path.isVariableDeclarator()) {
            inAssignment = true;
          } else if (path.isArrayExpression() || path.isObjectExpression()) {
            inCollection = true;
          } else if (path.isReturnStatement()) {
            inReturnStatement = true;
          } else if (path.isCallExpression()) {
            inCallExpression = true;
          }
          last = path.node;
        });

        // Values are useless if they aren't assigned.
        // ```
        //   var a = 1;
        //   <div /> // Useless JSX node
        // ```
        if (!(inReturnStatement || inAssignment || inCallExpression || containingJSXElement)) {
          throw this.errorWithNode("Unused JSX Elements aren't supported.");
        }

        const containerNeedsWrapper = (containingJSXElement) ?
          containingJSXElement.getData("containerNeedsWrapper") || containingJSXElement.getData("needsWrapper") :
          false;
        let needsWrapper = inAttribute || inAssignment || inCollection || inCallExpression;
        if (!containingJSXElement && !needsWrapper) {
          // Determine if there are JSXElements in a higher scope.
          needsWrapper = findOtherJSX(this);
        }

        // Tie a child JSXElement's eager declarations with the parent's, so
        // so all declarations come before the element.
        const eagerDeclarators = (containingJSXElement) ?
          containingJSXElement.getData("eagerDeclarators") :
          [];
        const staticAttrs = (containingJSXElement) ?
          containingJSXElement.getData("staticAttrs") :
          [];

        this.setData("containerNeedsWrapper", containerNeedsWrapper);
        this.setData("containingJSXElement", containingJSXElement);
        this.setData("eagerDeclarators", eagerDeclarators);
        this.setData("needsWrapper", needsWrapper);
        this.setData("staticAttrs", staticAttrs);
      },

      exit(node, parent, scope, file) {
        const {
          containerNeedsWrapper,
          containingJSXElement,
          eagerDeclarators,
          staticAttrs,
          needsWrapper,
          key
        } = this.data;

        const eager = needsWrapper || containerNeedsWrapper;
        const hoist = getOption(file, "hoist");

        const explicitReturn = t.isReturnStatement(parent);
        const implicitReturn = t.isArrowFunctionExpression(parent);

        // Filter out empty children, and transform JSX expressions
        // into normal expressions.
        const openingElement = node.openingElement;
        const closingElement = node.closingElement;
        const children = buildChildren(t, scope, file, node.children, eagerDeclarators, { eager });

        let elements = [ openingElement, ...children ];
        if (closingElement) { elements.push(closingElement); }

        // If we're inside a JSX node, flattening expressions
        // may force us into an unwanted function scope.
        if (t.isJSXElement(parent)) {
          return elements;
        }

        // Expressions Containers must contain an expression and not statements.
        // This will be flattened out into statements later.
        if (containingJSXElement && !needsWrapper) {
          const sequence = t.sequenceExpression(elements);
          // Mark this sequence as a JSX Element so we can avoid an unnecessary
          // renderArbitrary call.
          sequence._iDOMwasJSX = true;
          return sequence;
        }

        // Transform (recursively) any sequence expressions into a series of
        // statements.
        elements = flattenExpressions(t, elements);

        // Ensure the last statement returns the DOM element.
        if (explicitReturn || implicitReturn || needsWrapper) {
          elements = statementsWithReturnLast(t, elements);
        }

        if (!containingJSXElement) {
          if (eagerDeclarators.length) {
            // Find the closest statement, and insert our eager declarations
            // before it.
            const parentStatement = this.findParent((path) => path.isStatement());
            const [path] = parentStatement.insertBefore(t.variableDeclaration(
              "let",
              eagerDeclarators
            ));
            // Add our eager declarations to the scopes tracked bindings.
            scope.registerBinding("let", path);
          }
        }

        if (hoist && staticAttrs.length) {
          staticAttrs.forEach((attrs) => {
            const declaration = t.variableDeclaration("let", [attrs.declarator]);
            const key = attrs.key;
            const identifierKey = t.isIdentifier(key.value);
            const binding = identifierKey && scope.getBinding(key.value.name);

            if (identifierKey) {
              let hoisted;
              if (eager) {
                hoisted = declaration;
              } else {
                hoisted = t.expressionStatement(t.assignmentExpression(
                  "=",
                  t.memberExpression(
                    attrs.declarator.id,
                    t.literal(key.index),
                    true
                  ),
                  key.value
                ));
              }

              const parent = (binding) ? binding.path.parentPath : this;
              if (parent.isArrowFunctionExpression() && this.parentPath === parent) {
                elements.unshift(hoisted);
              } else if (parent.isFunction()) {
                parent.get("body").unshiftContainer("body", hoisted);
              } else if (binding) {
                const statement = binding.path.findParent((path) => path.isStatement());
                statement.insertAfter(hoisted);
              } else {
                elements.unshift(hoisted);
              }
            }

            if (!(binding && eager)) {
              const programScope = scope.getProgramParent();
              programScope.path.unshiftContainer("body", declaration);
            }
          });
        }

        if (needsWrapper) {
          // Create a wrapper around our element, and mark it as a one so later
          // child expressions can identify and "render" it.
          const jsxWrapperRef = injectJSXWrapper(t, file);
          const wrapper = toFunctionCall(t, jsxWrapperRef, [
            t.functionExpression(null, [], t.blockStatement(elements))
          ]);
          wrapper._iDOMwasJSX = true;
          return wrapper;
        }

        // This is the main JSX element. Replace the return statement
        // with all the nested calls, returning the main JSX element.
        if (implicitReturn) {
          this.parentPath.replaceWith(t.arrowFunctionExpression(
            parent.params,
            t.blockStatement(elements),
            parent.async
          ));
        } else if (explicitReturn) {
          this.parentPath.replaceWithMultiple(elements);
        } else {
          return elements;
        }
      }
    },

    JSXOpeningElement: {
      exit(node, parent, scope, file) {
        const tag = toReference(t, node.name);

        const JSXElement = this.parentPath;
        // Only eagerly evaluate our attributes if we will be wrapping the element.
        const eager = JSXElement.getData("needsWrapper") || JSXElement.getData("containerNeedsWrapper");
        const eagerDeclarators = JSXElement.getData("eagerDeclarators");
        const hoist = getOption(file, "hoist");
        const staticAttrs = JSXElement.getData("staticAttrs");

        const {
          key,
          keyIndex,
          statics,
          attrs,
          attributeDeclarators,
          hasSpread
        } = extractOpenArguments(t, scope, node.attributes, { eager, hoist });

        // Push any eager attribute declarators onto the element's list of
        // eager declarations.
        eagerDeclarators.push(...attributeDeclarators);

        // Only push arguments if they're needed
        const args = [tag];
        if (key || statics) {
          args.push(key || t.literal(null));
        }
        if (statics) {
          let staticsArray = t.arrayExpression(statics);
          if (hoist) {
            const ref = scope.generateUidIdentifier("statics");
            staticAttrs.push({
              declarator: t.variableDeclarator(ref, staticsArray),
              key: {
                index: keyIndex,
                value: key
              }
            });
            staticsArray = ref;
          }

          args.push(staticsArray);
        }

        // If there is a spread element, we need to use
        // the elementOpenStart/elementOpenEnd syntax.
        // This allows spreads to be transformed into
        // attr(name, value) calls.
        if (hasSpread) {
          const attrCalls = attrsToAttrCalls(t, file, attrs);

          const expressions = [
            toFunctionCall(t, iDOMMethod(file, "elementOpenStart"), args),
            ...attrCalls,
            toFunctionCall(t, iDOMMethod(file, "elementOpenEnd"), [tag])
          ];
          if (node.selfClosing) {
            expressions.push(toFunctionCall(t, iDOMMethod(file, "elementClose"), [tag]));
          }

          return t.sequenceExpression(expressions);
        }

        if (attrs) {
          // Only push key and statics if they have not
          // already been pushed.
          if (!statics) {
            if (!key) {
              args.push(t.literal(null));
            }
            args.push(t.literal(null));
          }

          args.push(...attrs);
        }

        const elementFunction = (node.selfClosing) ? "elementVoid" : "elementOpen";
        return toFunctionCall(t, iDOMMethod(file, elementFunction), args);
      }
    },

    JSXClosingElement: {
      exit(node, parent, scope, file) {
        return toFunctionCall(t, iDOMMethod(file, "elementClose"), [toReference(t, node.name)]);
      }
    },

    JSXNamespacedName: function() {
      throw this.errorWithNode("JSX Namespaces aren't supported.");
    }
  }});
}
<commit_msg>Cleanup<commit_after>import toFunctionCall from "./helpers/ast/to-function-call";
import toReference from "./helpers/ast/to-reference";

import getOption from "./helpers/get-option";
import iDOMMethod from "./helpers/idom-method";
import attrsToAttrCalls from "./helpers/attributes-to-attr-calls";
import buildChildren from "./helpers/build-children";
import extractOpenArguments from "./helpers/extract-open-arguments";
import findOtherJSX from "./helpers/find-other-jsx";
import flattenExpressions from "./helpers/flatten-expressions";
import statementsWithReturnLast from "./helpers/statements-with-return-last";

import { setupInjector } from "./helpers/inject";
import injectJSXWrapper from "./helpers/runtime/jsx-wrapper";

export default function ({ Plugin, types: t }) {
  return new Plugin("incremental-dom", { visitor : {
    Program: setupInjector,

    JSXElement: {
      enter(node) {
        let inAssignment = false;
        let inAttribute = false;
        let inCallExpression = false;
        let inCollection = false;
        let inReturnStatement = false;
        let containingJSXElement;
        let last = node;

        this.findParent((path) => {
          if (path.isJSXElement()) {
            containingJSXElement = path;
            return true;
          }
          if (path.isArrowFunctionExpression()) {
            inReturnStatement = inReturnStatement || !t.isBlockStatement(path.node.body);
            return true;
          }
          if (path.isFunction() || path.isProgram()) {
            return true;
          }
          if (path.isSequenceExpression()) {
            const expressions = path.node.expressions;
            const index = expressions.indexOf(last);
            if (index !== expressions.length - 1) {
              return true;
            }
          }
          if (path.isJSXAttribute()) {
            inAttribute = true;
          } else if (path.isAssignmentExpression() || path.isVariableDeclarator()) {
            inAssignment = true;
          } else if (path.isArrayExpression() || path.isObjectExpression()) {
            inCollection = true;
          } else if (path.isReturnStatement()) {
            inReturnStatement = true;
          } else if (path.isCallExpression()) {
            inCallExpression = true;
          }
          last = path.node;
        });

        // Values are useless if they aren't assigned.
        // ```
        //   var a = 1;
        //   <div /> // Useless JSX node
        // ```
        if (!(inReturnStatement || inAssignment || inCallExpression || containingJSXElement)) {
          throw this.errorWithNode("Unused JSX Elements aren't supported.");
        }

        const containerNeedsWrapper = (containingJSXElement) ?
          containingJSXElement.getData("containerNeedsWrapper") || containingJSXElement.getData("needsWrapper") :
          false;
        let needsWrapper = inAttribute || inAssignment || inCollection || inCallExpression;
        if (!containingJSXElement && !needsWrapper) {
          // Determine if there are JSXElements in a higher scope.
          needsWrapper = findOtherJSX(this);
        }

        // Tie a child JSXElement's eager declarations with the parent's, so
        // so all declarations come before the element.
        const eagerDeclarators = (containingJSXElement) ?
          containingJSXElement.getData("eagerDeclarators") :
          [];
        const staticAttrs = (containingJSXElement) ?
          containingJSXElement.getData("staticAttrs") :
          [];

        this.setData("containerNeedsWrapper", containerNeedsWrapper);
        this.setData("containingJSXElement", containingJSXElement);
        this.setData("eagerDeclarators", eagerDeclarators);
        this.setData("needsWrapper", needsWrapper);
        this.setData("staticAttrs", staticAttrs);
      },

      exit(node, parent, scope, file) {
        const {
          containerNeedsWrapper,
          containingJSXElement,
          eagerDeclarators,
          staticAttrs,
          needsWrapper,
          key
        } = this.data;

        const eager = needsWrapper || containerNeedsWrapper;
        const hoist = getOption(file, "hoist");

        const explicitReturn = t.isReturnStatement(parent);
        const implicitReturn = t.isArrowFunctionExpression(parent);

        // Filter out empty children, and transform JSX expressions
        // into normal expressions.
        const openingElement = node.openingElement;
        const closingElement = node.closingElement;
        const children = buildChildren(t, scope, file, node.children, eagerDeclarators, { eager });

        let elements = [ openingElement, ...children ];
        if (closingElement) { elements.push(closingElement); }

        // If we're inside a JSX node, flattening expressions
        // may force us into an unwanted function scope.
        if (t.isJSXElement(parent)) {
          return elements;
        }

        // Expressions Containers must contain an expression and not statements.
        // This will be flattened out into statements later.
        if (containingJSXElement && !needsWrapper) {
          const sequence = t.sequenceExpression(elements);
          // Mark this sequence as a JSX Element so we can avoid an unnecessary
          // renderArbitrary call.
          sequence._iDOMwasJSX = true;
          return sequence;
        }

        // Transform (recursively) any sequence expressions into a series of
        // statements.
        elements = flattenExpressions(t, elements);

        // Ensure the last statement returns the DOM element.
        if (explicitReturn || implicitReturn || needsWrapper) {
          elements = statementsWithReturnLast(t, elements);
        }

        if (!containingJSXElement) {
          if (eagerDeclarators.length) {
            // Find the closest statement, and insert our eager declarations
            // before it.
            const parentStatement = this.getStatementParent();
            const [path] = parentStatement.insertBefore(t.variableDeclaration(
              "let",
              eagerDeclarators
            ));
            // Add our eager declarations to the scopes tracked bindings.
            scope.registerBinding("let", path);
          }
        }

        if (hoist && staticAttrs.length) {
          staticAttrs.forEach((attrs) => {
            const declaration = t.variableDeclaration("let", [attrs.declarator]);
            const key = attrs.key;
            const identifierKey = t.isIdentifier(key.value);
            const binding = identifierKey && scope.getBinding(key.value.name);

            if (identifierKey) {
              let hoisted;
              if (eager) {
                hoisted = declaration;
              } else {
                hoisted = t.expressionStatement(t.assignmentExpression(
                  "=",
                  t.memberExpression(
                    attrs.declarator.id,
                    t.literal(key.index),
                    true
                  ),
                  key.value
                ));
              }

              const parent = (binding) ? binding.path.parentPath : this.parentPath;
              if (parent.isArrowFunctionExpression() && this.parentPath === parent) {
                elements.unshift(hoisted);
              } else if (parent.isFunction()) {
                parent.get("body").unshiftContainer("body", hoisted);
              } else if (binding) {
                const statement = binding.path.getStatementParent();
                statement.insertAfter(hoisted);
              } else {
                elements.unshift(hoisted);
              }
            }

            if (!(binding && eager)) {
              const programScope = scope.getProgramParent();
              programScope.path.unshiftContainer("body", declaration);
            }
          });
        }

        if (needsWrapper) {
          // Create a wrapper around our element, and mark it as a one so later
          // child expressions can identify and "render" it.
          const jsxWrapperRef = injectJSXWrapper(t, file);
          const wrapper = toFunctionCall(t, jsxWrapperRef, [
            t.functionExpression(null, [], t.blockStatement(elements))
          ]);
          wrapper._iDOMwasJSX = true;
          return wrapper;
        }

        // This is the main JSX element. Replace the return statement
        // with all the nested calls, returning the main JSX element.
        if (implicitReturn) {
          this.parentPath.replaceWith(t.arrowFunctionExpression(
            parent.params,
            t.blockStatement(elements),
            parent.async
          ));
        } else if (explicitReturn) {
          this.parentPath.replaceWithMultiple(elements);
        } else {
          return elements;
        }
      }
    },

    JSXOpeningElement: {
      exit(node, parent, scope, file) {
        const tag = toReference(t, node.name);

        const JSXElement = this.parentPath;
        // Only eagerly evaluate our attributes if we will be wrapping the element.
        const eager = JSXElement.getData("needsWrapper") || JSXElement.getData("containerNeedsWrapper");
        const eagerDeclarators = JSXElement.getData("eagerDeclarators");
        const hoist = getOption(file, "hoist");
        const staticAttrs = JSXElement.getData("staticAttrs");

        const {
          key,
          keyIndex,
          statics,
          attrs,
          attributeDeclarators,
          hasSpread
        } = extractOpenArguments(t, scope, node.attributes, { eager, hoist });

        // Push any eager attribute declarators onto the element's list of
        // eager declarations.
        eagerDeclarators.push(...attributeDeclarators);

        // Only push arguments if they're needed
        const args = [tag];
        if (key || statics) {
          args.push(key || t.literal(null));
        }
        if (statics) {
          let staticsArray = t.arrayExpression(statics);
          if (hoist) {
            const ref = scope.generateUidIdentifier("statics");
            staticAttrs.push({
              declarator: t.variableDeclarator(ref, staticsArray),
              key: {
                index: keyIndex,
                value: key
              }
            });
            staticsArray = ref;
          }

          args.push(staticsArray);
        }

        // If there is a spread element, we need to use
        // the elementOpenStart/elementOpenEnd syntax.
        // This allows spreads to be transformed into
        // attr(name, value) calls.
        if (hasSpread) {
          const attrCalls = attrsToAttrCalls(t, file, attrs);

          const expressions = [
            toFunctionCall(t, iDOMMethod(file, "elementOpenStart"), args),
            ...attrCalls,
            toFunctionCall(t, iDOMMethod(file, "elementOpenEnd"), [tag])
          ];
          if (node.selfClosing) {
            expressions.push(toFunctionCall(t, iDOMMethod(file, "elementClose"), [tag]));
          }

          return t.sequenceExpression(expressions);
        }

        if (attrs) {
          // Only push key and statics if they have not
          // already been pushed.
          if (!statics) {
            if (!key) {
              args.push(t.literal(null));
            }
            args.push(t.literal(null));
          }

          args.push(...attrs);
        }

        const elementFunction = (node.selfClosing) ? "elementVoid" : "elementOpen";
        return toFunctionCall(t, iDOMMethod(file, elementFunction), args);
      }
    },

    JSXClosingElement: {
      exit(node, parent, scope, file) {
        return toFunctionCall(t, iDOMMethod(file, "elementClose"), [toReference(t, node.name)]);
      }
    },

    JSXNamespacedName: function() {
      throw this.errorWithNode("JSX Namespaces aren't supported.");
    }
  }});
}
<|endoftext|>


<commit_before>/**
 *   Copyright 2017 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
import React, { Component, PropTypes } from 'react';

if (typeof window !== 'undefined') {
  require('pdfjs-dist/build/pdf.combined');
  require('pdfjs-dist/web/compatibility');
}

class SaikuPdf extends Component {
  constructor(props) {
    super(props);
    this.onDocumentComplete = this.onDocumentComplete.bind(this);
    this.onPageComplete = this.onPageComplete.bind(this);
  }

  static propTypes = {
    content: PropTypes.string,
    file: PropTypes.string,
    loading: PropTypes.any,
    page: PropTypes.number,
    scale: PropTypes.number,
    rotate: PropTypes.number,
    onDocumentComplete: PropTypes.func,
    onPageComplete: PropTypes.func,
    style: PropTypes.object
  };

  static defaultProps = {
    page: 1,
    scale: 1.0,
    loading:
Loading PDF...

  };

  state = {
    pdf: null,
    page: null
  };

  componentDidMount() {
    this.loadPDFDocument(this.props);
    this.renderPdf();
  }

  componentWillReceiveProps(nextProps) {
    const { pdf } = this.state;

    if ((nextProps.file && nextProps.file !== this.props.file) ||
      (nextProps.content && nextProps.content !== this.props.content)) {
      this.loadPDFDocument(nextProps);
    }

    if (pdf && (((nextProps.page && nextProps.page !== this.props.page) ||
      (nextProps.scale && nextProps.scale !== this.props.scale)) ||
      (nextProps.rotate && nextProps.rotate !== this.props.rotate))) {
      this.setState({ page: null });
      pdf.getPage(nextProps.page).then(this.onPageComplete);
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      nextState.pdf !== this.state.pdf ||
      nextState.page !== this.state.page ||
      nextProps.width !== this.props.width ||
      nextProps.scale !== this.props.scale
    );
  }

  onDocumentComplete(pdf) {
    this.setState({ pdf });

    const { onDocumentComplete } = this.props;

    if (typeof onDocumentComplete === 'function') {
      onDocumentComplete(pdf);
    }

    pdf.getPage(this.props.page).then(this.onPageComplete);
  }

  onPageComplete(page) {
    this.setState({ page });
    this.renderPdf();

    const { onPageComplete } = this.props;

    if (typeof onPageComplete === 'function') {
      onPageComplete(page.pageIndex + 1);
    }
  }

  loadByteArray(byteArray) {
    window.PDFJS.getDocument(byteArray).then(this.onDocumentComplete);
  }

  loadPDFDocument(props) {
    const hasFile = !!props.file;
    const hasContent = !!props.file;

    if (hasFile) {
      if (typeof props.file === 'string') {
        return window.PDFJS.getDocument(props.file)
          .then(this.onDocumentComplete);
      }

      // is a File object
      const reader = new FileReader();

      reader.onloadend = () => {
        this.loadByteArray(new Uint8Array(reader.result));
      }

      reader.readAsArrayBuffer(props.file);
    }
    else if (hasContent) {
      const bytes = window.atob(props.content);
      const byteLength = bytes.length;
      const byteArray = new Uint8Array(new ArrayBuffer(byteLength));

      for (let i = 0; i < byteLength; i++) {
        byteArray[i] = bytes.charCodeAt(i);
      }

      this.loadByteArray(byteArray);
    }
    else {
      throw new Error('Saiku PDFjs works with a file (URL) or content ' +
        '(base64). At least one needs to be provided!');
    }
  }

  renderPdf() {
    const { page } = this.state;

    if (page) {
      let { canvas } = this.refs;

      // compatible with react 0.13
      if (canvas.getDOMNode) {
        canvas = canvas.getDOMNode();
      }

      const canvasContext = canvas.getContext('2d');
      const { scale, rotate } = this.props;
      const viewport = page.getViewport(scale, rotate);

      canvas.height = viewport.height;
      canvas.width = viewport.width;
      page.render({ canvasContext, viewport });
    }
  }

  render() {
    const { loading, style } = this.props;
    const { page } = this.state;

    return page
      ? <canvas style={style} ref="canvas" />
      : loading ||
Loading PDF...
;
  }
}

export default SaikuPdf;
<commit_msg>Update component<commit_after>/**
 *   Copyright 2017 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
import React, { Component, PropTypes } from 'react';

if (typeof window !== 'undefined') {
  require('pdfjs-dist/build/pdf.combined');
  require('pdfjs-dist/web/compatibility');
}

class SaikuPdf extends Component {
  constructor(props) {
    super(props);
    this.onDocumentComplete = this.onDocumentComplete.bind(this);
    this.onDocumentError = this.onDocumentError.bind(this);
    this.onPageComplete = this.onPageComplete.bind(this);
    this.onPageError = this.onPageError.bind(this);
  }

  static propTypes = {
    content: PropTypes.string,
    file: PropTypes.string,
    error: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.node
    ]),
    loading: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.node
    ]),
    noData: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.node
    ]),
    page: PropTypes.number,
    scale: PropTypes.number,
    width: PropTypes.number,
    rotate: PropTypes.number,
    onDocumentComplete: PropTypes.func,
    onDocumentError: PropTypes.func,
    onPageComplete: PropTypes.func,
    onPageError: PropTypes.func,
    style: PropTypes.object
  };

  static defaultProps = {
    page: 1,
    scale: 1.0,
    error: 'Failed to load PDF file.',
    loading: 'Loading PDF...',
    noData: 'No PDF file specified.'
  };

  state = {
    pdf: null,
    page: null
  };

  componentDidMount() {
    this.loadPDFDocument(this.props);
    this.renderPdf();
  }

  componentWillReceiveProps(nextProps) {
    const { pdf } = this.state;

    if ((nextProps.file && nextProps.file !== this.props.file) ||
      (nextProps.content && nextProps.content !== this.props.content)) {
      this.loadPDFDocument(nextProps);
    }

    if (pdf && (((nextProps.page && nextProps.page !== this.props.page) ||
      (nextProps.scale && nextProps.scale !== this.props.scale)) ||
      (nextProps.rotate && nextProps.rotate !== this.props.rotate))) {
      this.setState({ page: null });
      pdf.getPage(nextProps.page)
        .then(this.onPageComplete)
        .catch(this.onPageError);
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      nextState.pdf !== this.state.pdf ||
      nextState.page !== this.state.page ||
      nextProps.scale !== this.props.scale ||
      nextProps.width !== this.props.width ||
      nextProps.rotate !== this.props.rotate
    );
  }

  onDocumentComplete(pdf) {
    this.setState({ pdf });

    const { onDocumentComplete } = this.props;

    if (typeof onDocumentComplete === 'function') {
      onDocumentComplete(pdf.numPages);
    }

    pdf.getPage(this.props.page)
      .then(this.onPageComplete)
      .catch(this.onPageError);
  }

  onDocumentError(error) {
    this.setState({ pdf: false });

    const { onDocumentError } = this.props;

    if (typeof onDocumentError === 'function') {
      onDocumentError(error);
    }
  }

  onPageComplete(page) {
    this.setState({ page });
    this.renderPdf();

    const { onPageComplete } = this.props;

    if (typeof onPageComplete === 'function') {
      onPageComplete(page.pageIndex + 1);
    }
  }

  onPageError(error) {
    this.setState({ pdf: false });

    const { onPageError } = this.props;

    if (typeof onPageError === 'function') {
      onPageError(error);
    }
  }

  getPageScale(page = this.state.page) {
    const { scale, width } = this.props;

    // be default, we'll render page at 100% * scale width.
    let pageScale = 1;

    // if width is defined, calculate the scale of the page
    // so it could be of desired width.
    if (width) {
      pageScale = width / page.getViewport(scale).width;
    }

    return scale * pageScale;
  }

  loadByteArray(byteArray) {
    window.PDFJS.getDocument(byteArray)
      .then(this.onDocumentComplete)
      .catch(this.onDocumentError);
  }

  loadPDFDocument(props) {
    const hasFile = !!props.file;
    const hasContent = !!props.file;

    if (hasFile) {
      if (typeof props.file === 'string') {
        return window.PDFJS.getDocument(props.file)
          .then(this.onDocumentComplete);
      }

      // is a File object
      const reader = new FileReader();

      reader.onloadend = () => {
        this.loadByteArray(new Uint8Array(reader.result));
      }

      reader.readAsArrayBuffer(props.file);
    }
    else if (hasContent) {
      const bytes = window.atob(props.content);
      const byteLength = bytes.length;
      const byteArray = new Uint8Array(new ArrayBuffer(byteLength));

      for (let i = 0; i < byteLength; i++) {
        byteArray[i] = bytes.charCodeAt(i);
      }

      this.loadByteArray(byteArray);
    }
    else {
      throw new Error('Saiku PDFjs works with a file (URL) or content ' +
        '(base64). At least one needs to be provided!');
    }
  }

  renderNoData() {
    return (

{this.props.noData}

    );
  }

  renderError() {
    return (

{this.props.error}

    );
  }

  renderLoader() {
    return (

{this.props.loading}

    );
  }

  renderPdf() {
    const { page } = this.state;

    if (page) {
      let { canvas } = this.refs;

      // compatible with react 0.13
      if (canvas.getDOMNode) {
        canvas = canvas.getDOMNode();
      }

      const pixelRatio = window.devicePixelRatio || 1;
      const canvasContext = canvas.getContext('2d');
      const viewport = page.getViewport(this.getPageScale() * pixelRatio);

      canvas.height = viewport.height;
      canvas.width = viewport.width;
      canvas.style.height = `${viewport.height / pixelRatio}px`;
      canvas.style.width = `${viewport.width / pixelRatio}px`;
      page.render({ canvasContext, viewport });
    }
  }

  render() {
    const { file, style } = this.props;
    const { pdf, page } = this.state;

    if (!file) {
      return this.renderNoData();
    }

    if (pdf === false || page === false) {
      return this.renderError();
    }

    if (pdf === null || page === null) {
      return this.renderLoader();
    }

    return (
      <canvas style={style} ref="canvas" />
    );
  }
}

export default SaikuPdf;
<|endoftext|>


<commit_before>var yaml = require('js-yaml')
  , fs = require('fs')
  , path = require('path');

var Config = function (peak, options) {
  this.peak = peak;
  this.file_path = path.join(this.peak.path, '.peakconfig.yml');

  this.config = {};
  this.options_argument = options || {};

  this.load_defaults();
  this.load_file();
}

Config.prototype = {

  load_defaults: function () {
    this.config.output_path = '.peak';
    this.config.port = 1111;
  },

  load_file: function () {
    var file;
    if (fs.existsSync(this.file_path)) {
      file = yaml.safeLoad(fs.readFileSync(this.file_path, 'utf8'));
      for (var opt in file) this.config[opt] = file[opt];
    }
  },

  options: function (action) {
    var options = {};

    for (option in this.config) {
      options[option] = this.config[option];
    }

    if (typeof options[action] === 'object') {
      for (option in options[action]) options[option] = options[action][option];
    }

    for (option in this.options_argument) {
      if (this.options_argument[option]) options[option] = this.options_argument[option];
    }

    if (!options.ignore_paths instanceof Array) {
      options.ignore_paths = [];
    }

    if (options.ignore_paths.indexOf(options.output_path) == -1) {
      options.ignore_paths.push(options.output_path);
    }

    return options;
  }

}

module.exports = Config;
<commit_msg>Do not setup ignore_paths on generate action; set default index here.<commit_after>var yaml = require('js-yaml')
  , fs = require('fs')
  , path = require('path');

var Config = function (peak, options) {
  this.peak = peak;
  this.file_path = path.join(this.peak.path, '.peakconfig.yml');

  this.config = {};
  this.options_argument = options || {};

  this.load_defaults();
  this.load_file();
}

Config.prototype = {

  load_defaults: function () {
    this.config.output_path = '.peak';
    this.config.port = 1111;
    this.config.index = 'index.jade';
  },

  load_file: function () {
    var file;
    if (fs.existsSync(this.file_path)) {
      file = yaml.safeLoad(fs.readFileSync(this.file_path, 'utf8'));
      for (var opt in file) this.config[opt] = file[opt];
    }
  },

  options: function (action) {
    var options = {};

    for (option in this.config) {
      options[option] = this.config[option];
    }

    if (typeof options[action] === 'object') {
      for (option in options[action]) options[option] = options[action][option];
    }

    for (option in this.options_argument) {
      if (this.options_argument[option] &&
        typeof this.options_argument[option] !== 'function') options[option] = this.options_argument[option];
    }

    if (action) {

      if (!options.ignore_paths || !options.ignore_paths instanceof Array) {
        options.ignore_paths = [];
      }

      if (options.ignore_paths.indexOf(options.output_path) == -1) {
        options.ignore_paths.push(options.output_path);
      }

    }

    return options;
  }

}

module.exports = Config;
<|endoftext|>


<commit_before>var yaml = require('js-yaml'),
    fs = require('fs');

exports.load = function() {
    return yaml.safeLoad(fs.readFileSync('./apollo.yml', 'utf-8'));
};
<commit_msg>Remove unused js file<commit_after><|endoftext|>


<commit_before>/*
 * arrive.js
 * v2.2.0
 * https://github.com/uzairfarooq/arrive
 * MIT licensed
 *
 * Copyright (c) 2014-2015 Uzair Farooq
 */

var Arrive = (function(window, $, undefined) {

  "use strict";

  if(!window.MutationObserver || typeof HTMLElement === 'undefined'){
    return; //for unsupported browsers
  }

  var arriveUniqueId = 0;

  var utils = (function() {
    var matches = HTMLElement.prototype.matches || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector
                  || HTMLElement.prototype.msMatchesSelector;

    return {
      matchesSelector: function(elem, selector) {
        return elem instanceof HTMLElement && matches.call(elem, selector);
      },
      // to enable function overloading - By John Resig (MIT Licensed)
      addMethod: function (object, name, fn) {
        var old = object[ name ];
        object[ name ] = function(){
          if ( fn.length == arguments.length )
            return fn.apply( this, arguments );
          else if ( typeof old == 'function' )
            return old.apply( this, arguments );
        };
      }
    };
  })();

  // Class to maintain state of all registered events of a single type
  var EventsBucket = (function() {
    var EventsBucket = function() {
      // holds all the events

      this._eventsBucket    = [];
      // function to be called while adding an event, the function should do the event initialization/registration
      this._beforeAdding    = null;
      // function to be called while removing an event, the function should do the event destruction
      this._beforeRemoving  = null;
    };

    EventsBucket.prototype.addEvent = function(target, selector, options, callback) {
      var newEvent = {
        target:             target,
        selector:           selector,
        options:            options,
        callback:           callback,
        firedElems:         []
      };

      if (this._beforeAdding) {
        this._beforeAdding(newEvent);
      }

      this._eventsBucket.push(newEvent);
      return newEvent;
    };

    EventsBucket.prototype.removeEvent = function(compareFunction) {
      for (var i=this._eventsBucket.length - 1, registeredEvent; registeredEvent = this._eventsBucket[i]; i--) {
        if (compareFunction(registeredEvent)) {
          if (this._beforeRemoving) {
              this._beforeRemoving(registeredEvent);
          }
          this._eventsBucket.splice(i, 1);
        }
      }
    };

    EventsBucket.prototype.beforeAdding = function(beforeAdding) {
      this._beforeAdding = beforeAdding;
    };

    EventsBucket.prototype.beforeRemoving = function(beforeRemoving) {
      this._beforeRemoving = beforeRemoving;
    };

    return EventsBucket;
  })();

  /**
   * @constructor
   * General class for binding/unbinding arrive and leave events
   */
  var MutationEvents = function(getObserverConfig, defaultOptions, onMutation) {
    var eventsBucket    = new EventsBucket(),
        me              = this;

    // actual event registration before adding it to bucket
    eventsBucket.beforeAdding(function(registrationData) {
      var
        target    = registrationData.target,
        selector  = registrationData.selector,
        callback  = registrationData.callback,
        observer;

      // mutation observer does not work on window or document
      if (target === window.document || target === window)
        target = document.getElementsByTagName("html")[0];

      // Create an observer instance
      observer = new MutationObserver(function(e) {
        onMutation.call(this, e, registrationData);
      });

      var config = getObserverConfig(registrationData.options);

      observer.observe(target, config);

      registrationData.observer = observer;
      registrationData.me = me;
    });

    // cleanup/unregister before removing an event
    eventsBucket.beforeRemoving(function (eventData) {
      eventData.observer.disconnect();
    });

    function toArray(elements) {
      // check if object is an array (or array like object)
      // Note: window object has .length property but it's not array of elements so don't consider it an array
      if (typeof elements.length !== "number" || elements === window) {
        elements = [elements];
      }
      return elements;
    }

    this.bindEvent = function(selector, options, callback) {
      if (typeof callback === "undefined") {
        callback = options;
        options = defaultOptions;
      } else {
        options = mergeOptions(defaultOptions, options);
      }

      var elements = toArray(this);

      if (options.existing) {
        var existing = [],
            i;

        for (i = 0; i < elements.length; i++) {
          var nodes = elements[i].querySelectorAll(selector);
          for (var j = 0; j < nodes.length; j++) {
            existing.push(nodes[j]);
          }
        }
        if (options.onceOnly && existing.length) {
          return callback.call(existing[0]);
        }
        for (i = 0; i < existing.length; i++) {
          callback.call(existing[i]);
        }
      }

      for (i = 0; i < elements.length; i++) {
        eventsBucket.addEvent(elements[i], selector, options, callback);
      }
    };

    this.unbindEvent = function() {
      var elements = toArray(this);
      eventsBucket.removeEvent(function(eventObj) {
        for (var i = 0; i < elements.length; i++) {
          if (this === undefined || eventObj.target === elements[i]) {
            return true;
          }
        }
        return false;
      });
    };

    this.unbindEventWithSelectorOrCallback = function(selector) {
      var elements = toArray(this),
          callback = selector,
          compareFunction;

      if (typeof selector === "function") {
        compareFunction = function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if ((this === undefined || eventObj.target === elements[i]) && eventObj.callback === callback) {
              return true;
            }
          }
          return false;
        };
      }
      else {
        compareFunction = function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if ((this === undefined || eventObj.target === elements[i]) && eventObj.selector === selector) {
              return true;
            }
          }
          return false;
        };
      }
      eventsBucket.removeEvent(compareFunction);
    };

    this.unbindEventWithSelectorAndCallback = function(selector, callback) {
      var elements = toArray(this);
      eventsBucket.removeEvent(function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if ((this === undefined || eventObj.target === elements[i]) && eventObj.selector === selector && eventObj.callback === callback) {
              return true;
            }
          }
          return false;
      });
    };

    return this;
  };

  function checkNode(node, registrationData, callbacksToBeCalled) {
    // check a single node to see if it matches the selector
    if (utils.matchesSelector(node, registrationData.selector)) {
      if(node._id === undefined) {
        node._id = arriveUniqueId++;
      }
      // make sure the arrive event is not already fired for the element
      if (registrationData.firedElems.indexOf(node._id) == -1) {

        if (registrationData.options.onceOnly) {
          if (registrationData.firedElems.length === 0) {
            // On first callback, unbind event.
            registrationData.me.unbindEventWithSelectorAndCallback.call(
              registrationData.target, registrationData.selector, registrationData.callback);
          } else {
            // Ignore multiple mutations which may have been queued before the event was unbound.
            return;
          }
        }

        registrationData.firedElems.push(node._id);
        callbacksToBeCalled.push({ callback: registrationData.callback, elem: node });
      }
    }
  }

  // traverse through all descendants of a node to check if event should be fired for any descendant
  function checkChildNodesRecursively(nodes, registrationData, callbacksToBeCalled) {
    // check each new node if it matches the selector
    for (var i=0, node; node = nodes[i]; i++) {
        checkNode(node, registrationData, callbacksToBeCalled);

        if (node.childNodes.length > 0) {
            checkChildNodesRecursively(node.childNodes, registrationData, callbacksToBeCalled);
        }
    }
  }

  function callCallbacks(callbacksToBeCalled) {
    for (var i = 0, cb; cb = callbacksToBeCalled[i]; i++) {
      cb.callback.call(cb.elem);
    }
  }

  function onArriveMutation(mutations, registrationData) {
    mutations.forEach(function( mutation ) {
      var newNodes    = mutation.addedNodes,
          targetNode = mutation.target,
          callbacksToBeCalled = [];

      // If new nodes are added
      if( newNodes !== null && newNodes.length > 0 ) {
        checkChildNodesRecursively(newNodes, registrationData, callbacksToBeCalled);
      }
      else if (mutation.type === "attributes") {
        checkNode(targetNode, registrationData, callbacksToBeCalled);
      }

      callCallbacks(callbacksToBeCalled);
    });
  }

  function onLeaveMutation(mutations, registrationData) {
    mutations.forEach(function( mutation ) {
      var removedNodes  = mutation.removedNodes,
          targetNode   = mutation.target,
          callbacksToBeCalled = [];

      if( removedNodes !== null && removedNodes.length > 0 ) {
        checkChildNodesRecursively(removedNodes, registrationData, callbacksToBeCalled);
      }

      callCallbacks(callbacksToBeCalled);
    });
  }

  function getArriveObserverConfig(options) {
    var config = {
          attributes: false,
          childList: true,
          subtree: true
        };

    if (options.fireOnAttributesModification) {
      config.attributes = true;
    }

    return config;
  }
  function getLeaveObserverConfig(options) {
    var config = {
          childList: true,
          subtree: true
        };

    return config;
  }

  function mergeOptions(defaultOpts, userOpts){
      // Overwrites default options with user-defined options.
      var options = {},
          attrName;
      for (attrName in defaultOpts) {
        options[attrName] = defaultOpts[attrName];
      }
      for (attrName in userOpts) {
        options[attrName] = userOpts[attrName];
      }
      return options;
  }

  // Default options
  var arriveDefaultOptions = {
        fireOnAttributesModification: false,
        onceOnly: false
      },
      leaveDefaultOptions = {};

  var arriveEvents = new MutationEvents(getArriveObserverConfig, arriveDefaultOptions, onArriveMutation),
      leaveEvents  = new MutationEvents(getLeaveObserverConfig, leaveDefaultOptions, onLeaveMutation);

  function exposeUnbindApi(eventObj, exposeTo, funcName) {
    // expose unbindArrive function with overriding
    utils.addMethod(exposeTo, funcName, eventObj.unbindEvent);
    utils.addMethod(exposeTo, funcName, eventObj.unbindEventWithSelectorOrCallback);
    utils.addMethod(exposeTo, funcName, eventObj.unbindEventWithSelectorAndCallback);
  }

  /*** expose APIs ***/
  function exposeApi(exposeTo) {
    exposeTo.arrive = arriveEvents.bindEvent;
    exposeUnbindApi(arriveEvents, exposeTo, "unbindArrive");

    exposeTo.leave = leaveEvents.bindEvent;
    exposeUnbindApi(leaveEvents, exposeTo, "unbindLeave");
  }

  if ($) {
    exposeApi($.fn);
  }
  exposeApi(HTMLElement.prototype);
  exposeApi(NodeList.prototype);
  exposeApi(HTMLCollection.prototype);
  exposeApi(HTMLDocument.prototype);
  exposeApi(Window.prototype);

  var Arrive = {};
  // expose functions to unbind all arrive/leave events
  exposeUnbindApi(arriveEvents, Arrive, "unbindAllArrive");
  exposeUnbindApi(leaveEvents, Arrive, "unbindAllLeave");

  return Arrive;

})(this, typeof jQuery === 'undefined' ? null : jQuery, undefined);
<commit_msg>Change comment<commit_after>/*
 * arrive.js
 * v2.2.0
 * https://github.com/uzairfarooq/arrive
 * MIT licensed
 *
 * Copyright (c) 2014-2015 Uzair Farooq
 */

var Arrive = (function(window, $, undefined) {

  "use strict";

  if(!window.MutationObserver || typeof HTMLElement === 'undefined'){
    return; //for unsupported browsers
  }

  var arriveUniqueId = 0;

  var utils = (function() {
    var matches = HTMLElement.prototype.matches || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector
                  || HTMLElement.prototype.msMatchesSelector;

    return {
      matchesSelector: function(elem, selector) {
        return elem instanceof HTMLElement && matches.call(elem, selector);
      },
      // to enable function overloading - By John Resig (MIT Licensed)
      addMethod: function (object, name, fn) {
        var old = object[ name ];
        object[ name ] = function(){
          if ( fn.length == arguments.length )
            return fn.apply( this, arguments );
          else if ( typeof old == 'function' )
            return old.apply( this, arguments );
        };
      }
    };
  })();

  // Class to maintain state of all registered events of a single type
  var EventsBucket = (function() {
    var EventsBucket = function() {
      // holds all the events

      this._eventsBucket    = [];
      // function to be called while adding an event, the function should do the event initialization/registration
      this._beforeAdding    = null;
      // function to be called while removing an event, the function should do the event destruction
      this._beforeRemoving  = null;
    };

    EventsBucket.prototype.addEvent = function(target, selector, options, callback) {
      var newEvent = {
        target:             target,
        selector:           selector,
        options:            options,
        callback:           callback,
        firedElems:         []
      };

      if (this._beforeAdding) {
        this._beforeAdding(newEvent);
      }

      this._eventsBucket.push(newEvent);
      return newEvent;
    };

    EventsBucket.prototype.removeEvent = function(compareFunction) {
      for (var i=this._eventsBucket.length - 1, registeredEvent; registeredEvent = this._eventsBucket[i]; i--) {
        if (compareFunction(registeredEvent)) {
          if (this._beforeRemoving) {
              this._beforeRemoving(registeredEvent);
          }
          this._eventsBucket.splice(i, 1);
        }
      }
    };

    EventsBucket.prototype.beforeAdding = function(beforeAdding) {
      this._beforeAdding = beforeAdding;
    };

    EventsBucket.prototype.beforeRemoving = function(beforeRemoving) {
      this._beforeRemoving = beforeRemoving;
    };

    return EventsBucket;
  })();

  /**
   * @constructor
   * General class for binding/unbinding arrive and leave events
   */
  var MutationEvents = function(getObserverConfig, defaultOptions, onMutation) {
    var eventsBucket    = new EventsBucket(),
        me              = this;

    // actual event registration before adding it to bucket
    eventsBucket.beforeAdding(function(registrationData) {
      var
        target    = registrationData.target,
        selector  = registrationData.selector,
        callback  = registrationData.callback,
        observer;

      // mutation observer does not work on window or document
      if (target === window.document || target === window)
        target = document.getElementsByTagName("html")[0];

      // Create an observer instance
      observer = new MutationObserver(function(e) {
        onMutation.call(this, e, registrationData);
      });

      var config = getObserverConfig(registrationData.options);

      observer.observe(target, config);

      registrationData.observer = observer;
      registrationData.me = me;
    });

    // cleanup/unregister before removing an event
    eventsBucket.beforeRemoving(function (eventData) {
      eventData.observer.disconnect();
    });

    function toArray(elements) {
      // check if object is an array (or array like object)
      // Note: window object has .length property but it's not array of elements so don't consider it an array
      if (typeof elements.length !== "number" || elements === window) {
        elements = [elements];
      }
      return elements;
    }

    this.bindEvent = function(selector, options, callback) {
      if (typeof callback === "undefined") {
        callback = options;
        options = defaultOptions;
      } else {
        options = mergeOptions(defaultOptions, options);
      }

      var elements = toArray(this);

      if (options.existing) {
        var existing = [],
            i;

        for (i = 0; i < elements.length; i++) {
          var nodes = elements[i].querySelectorAll(selector);
          for (var j = 0; j < nodes.length; j++) {
            existing.push(nodes[j]);
          }
        }
        if (options.onceOnly && existing.length) {
          return callback.call(existing[0]);
        }
        for (i = 0; i < existing.length; i++) {
          callback.call(existing[i]);
        }
      }

      for (i = 0; i < elements.length; i++) {
        eventsBucket.addEvent(elements[i], selector, options, callback);
      }
    };

    this.unbindEvent = function() {
      var elements = toArray(this);
      eventsBucket.removeEvent(function(eventObj) {
        for (var i = 0; i < elements.length; i++) {
          if (this === undefined || eventObj.target === elements[i]) {
            return true;
          }
        }
        return false;
      });
    };

    this.unbindEventWithSelectorOrCallback = function(selector) {
      var elements = toArray(this),
          callback = selector,
          compareFunction;

      if (typeof selector === "function") {
        compareFunction = function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if ((this === undefined || eventObj.target === elements[i]) && eventObj.callback === callback) {
              return true;
            }
          }
          return false;
        };
      }
      else {
        compareFunction = function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if ((this === undefined || eventObj.target === elements[i]) && eventObj.selector === selector) {
              return true;
            }
          }
          return false;
        };
      }
      eventsBucket.removeEvent(compareFunction);
    };

    this.unbindEventWithSelectorAndCallback = function(selector, callback) {
      var elements = toArray(this);
      eventsBucket.removeEvent(function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if ((this === undefined || eventObj.target === elements[i]) && eventObj.selector === selector && eventObj.callback === callback) {
              return true;
            }
          }
          return false;
      });
    };

    return this;
  };

  function checkNode(node, registrationData, callbacksToBeCalled) {
    // check a single node to see if it matches the selector
    if (utils.matchesSelector(node, registrationData.selector)) {
      if(node._id === undefined) {
        node._id = arriveUniqueId++;
      }
      // make sure the arrive event is not already fired for the element
      if (registrationData.firedElems.indexOf(node._id) == -1) {

        if (registrationData.options.onceOnly) {
          if (registrationData.firedElems.length === 0) {
            // On first callback, unbind event.
            registrationData.me.unbindEventWithSelectorAndCallback.call(
              registrationData.target, registrationData.selector, registrationData.callback);
          } else {
            // Ignore multiple mutations which may have been queued before the event was unbound.
            return;
          }
        }

        registrationData.firedElems.push(node._id);
        callbacksToBeCalled.push({ callback: registrationData.callback, elem: node });
      }
    }
  }

  // traverse through all descendants of a node to check if event should be fired for any descendant
  function checkChildNodesRecursively(nodes, registrationData, callbacksToBeCalled) {
    // check each new node if it matches the selector
    for (var i=0, node; node = nodes[i]; i++) {
        checkNode(node, registrationData, callbacksToBeCalled);

        if (node.childNodes.length > 0) {
            checkChildNodesRecursively(node.childNodes, registrationData, callbacksToBeCalled);
        }
    }
  }

  function callCallbacks(callbacksToBeCalled) {
    for (var i = 0, cb; cb = callbacksToBeCalled[i]; i++) {
      cb.callback.call(cb.elem);
    }
  }

  function onArriveMutation(mutations, registrationData) {
    mutations.forEach(function( mutation ) {
      var newNodes    = mutation.addedNodes,
          targetNode = mutation.target,
          callbacksToBeCalled = [];

      // If new nodes are added
      if( newNodes !== null && newNodes.length > 0 ) {
        checkChildNodesRecursively(newNodes, registrationData, callbacksToBeCalled);
      }
      else if (mutation.type === "attributes") {
        checkNode(targetNode, registrationData, callbacksToBeCalled);
      }

      callCallbacks(callbacksToBeCalled);
    });
  }

  function onLeaveMutation(mutations, registrationData) {
    mutations.forEach(function( mutation ) {
      var removedNodes  = mutation.removedNodes,
          targetNode   = mutation.target,
          callbacksToBeCalled = [];

      if( removedNodes !== null && removedNodes.length > 0 ) {
        checkChildNodesRecursively(removedNodes, registrationData, callbacksToBeCalled);
      }

      callCallbacks(callbacksToBeCalled);
    });
  }

  function getArriveObserverConfig(options) {
    var config = {
          attributes: false,
          childList: true,
          subtree: true
        };

    if (options.fireOnAttributesModification) {
      config.attributes = true;
    }

    return config;
  }
  function getLeaveObserverConfig(options) {
    var config = {
          childList: true,
          subtree: true
        };

    return config;
  }

  function mergeOptions(defaultOpts, userOpts){
      // Overwrites default options with user-defined options.
      var options = {},
          attrName;
      for (attrName in defaultOpts) {
        options[attrName] = defaultOpts[attrName];
      }
      for (attrName in userOpts) {
        options[attrName] = userOpts[attrName];
      }
      return options;
  }

  // Default options
  var arriveDefaultOptions = {
        fireOnAttributesModification: false,
        onceOnly: false
      },
      leaveDefaultOptions = {};

  var arriveEvents = new MutationEvents(getArriveObserverConfig, arriveDefaultOptions, onArriveMutation),
      leaveEvents  = new MutationEvents(getLeaveObserverConfig, leaveDefaultOptions, onLeaveMutation);

  function exposeUnbindApi(eventObj, exposeTo, funcName) {
    // expose unbind function with function overriding
    utils.addMethod(exposeTo, funcName, eventObj.unbindEvent);
    utils.addMethod(exposeTo, funcName, eventObj.unbindEventWithSelectorOrCallback);
    utils.addMethod(exposeTo, funcName, eventObj.unbindEventWithSelectorAndCallback);
  }

  /*** expose APIs ***/
  function exposeApi(exposeTo) {
    exposeTo.arrive = arriveEvents.bindEvent;
    exposeUnbindApi(arriveEvents, exposeTo, "unbindArrive");

    exposeTo.leave = leaveEvents.bindEvent;
    exposeUnbindApi(leaveEvents, exposeTo, "unbindLeave");
  }

  if ($) {
    exposeApi($.fn);
  }
  exposeApi(HTMLElement.prototype);
  exposeApi(NodeList.prototype);
  exposeApi(HTMLCollection.prototype);
  exposeApi(HTMLDocument.prototype);
  exposeApi(Window.prototype);

  var Arrive = {};
  // expose functions to unbind all arrive/leave events
  exposeUnbindApi(arriveEvents, Arrive, "unbindAllArrive");
  exposeUnbindApi(leaveEvents, Arrive, "unbindAllLeave");

  return Arrive;

})(this, typeof jQuery === 'undefined' ? null : jQuery, undefined);
<|endoftext|>


<commit_before>import Features from './features';
import withFeatures from './with-features';
import configureFeature from './configure-feature';
import createRouteMiddleware from './create-route-middleware';
import getIsEnabled from './get-is-enabled';
import getEnabled from './get-enabled';
import isFeatureIncluded from './is-feature-included';
import updateFeaturesWithQuery from './update-features-with-query';

export { FeatureToggles } from './feature-toggles';
export { Feature } from './feature';

export {
  Features,
  withFeatures,
  configureFeature,
  createRouteMiddleware,
  getIsEnabled,
  getEnabled,
  isFeatureIncluded,
  updateFeaturesWithQuery
};
<commit_msg>Update index.js<commit_after>import withFeatures from './with-features';
import configureFeature from './configure-feature';
import createRouteMiddleware from './create-route-middleware';
import getIsEnabled from './get-is-enabled';
import getEnabled from './get-enabled';
import isFeatureIncluded from './is-feature-included';
import updateFeaturesWithQuery from './update-features-with-query';

export { FeatureToggles } from './feature-toggles';
export { Feature } from './feature';

export {
  withFeatures,
  configureFeature,
  createRouteMiddleware,
  getIsEnabled,
  getEnabled,
  isFeatureIncluded,
  updateFeaturesWithQuery
};
<|endoftext|>