<commit_before>'use strict';

/* Dependencies. */
var has = require('has');
var extend = require('extend');
var bail = require('bail');
var vfile = require('vfile');
var trough = require('trough');
var string = require('x-is-string');
var func = require('x-is-function');
var array = require('isarray');

/* Expose a frozen processor. */
module.exports = unified().freeze();

var slice = [].slice;

/* Process pipeline. */
var pipeline = trough().use(pipelineParse).use(pipelineRun).use(pipelineStringify);

function pipelineParse(p, ctx) {
  ctx.tree = p.parse(ctx.file);
}

function pipelineRun(p, ctx, next) {
  p.run(ctx.tree, ctx.file, done);

  function done(err, tree, file) {
    if (err) {
      next(err);
    } else {
      ctx.tree = tree;
      ctx.file = file;
      next();
    }
  }
}

function pipelineStringify(p, ctx) {
  ctx.file.contents = p.stringify(ctx.tree, ctx.file);
}

/* Function to create the first processor. */
function unified() {
  var attachers = [];
  var transformers = trough();
  var namespace = {};
  var frozen = false;

  /* Data management. */
  processor.data = data;

  /* Lock. */
  processor.freeze = freeze;

  /* Plug-ins. */
  processor.attachers = attachers;
  processor.use = use;

  /* API. */
  processor.parse = parse;
  processor.stringify = stringify;
  processor.run = run;
  processor.runSync = runSync;
  processor.process = process;
  processor.processSync = processSync;

  /* Expose. */
  return processor;

  /* Create a new processor based on the processor
   * in the current scope. */
  function processor() {
    var destination = unified();
    var length = attachers.length;
    var index = -1;

    while (++index < length) {
      destination.use.apply(null, attachers[index]);
    }

    destination.data(extend(true, {}, namespace));

    return destination;
  }

  /* Freeze: used to signal a processor that has finished
   * configuration.
   *
   * For example, take unified itself.  It’s frozen.
   * Plug-ins should not be added to it.  Rather, it should
   * be extended, by invoking it, before modifying it.
   *
   * In essence, always invoke this when exporting a
   * processor. */
  function freeze() {
    var length = attachers.length;
    var index = -1;
    var values;
    var plugin;
    var options;
    var transformer;

    if (frozen) {
      return processor;
    }

    while (++index < length) {
      values = attachers[index];
      plugin = values[0];
      options = values[1];
      transformer = null;

      if (options === false) {
        return;
      }

      if (options === true) {
        values[1] = undefined;
      }

      transformer = plugin.apply(processor, values.slice(1));

      if (func(transformer)) {
        transformers.use(transformer);
      }
    }

    frozen = true;

    return processor;
  }

  /* Data management.
   * Getter / setter for processor-specific informtion. */
  function data(key, value) {
    if (string(key)) {
      /* Set `key`. */
      if (arguments.length === 2) {
        assertUnfrozen('data', frozen);

        namespace[key] = value;

        return processor;
      }

      /* Get `key`. */
      return (has(namespace, key) && namespace[key]) || null;
    }

    /* Set space. */
    if (key) {
      assertUnfrozen('data', frozen);
      namespace = key;
      return processor;
    }

    /* Get space. */
    return namespace;
  }

  /* Plug-in management.
   *
   * Pass it:
   * *   an attacher and options,
   * *   a preset,
   * *   a list of presets, attachers, and arguments (list
   *     of attachers and options). */
  function use(value) {
    var settings;

    assertUnfrozen('use', frozen);

    if (value === null || value === undefined) {
      /* empty */
    } else if (func(value)) {
      addPlugin.apply(null, arguments);
    } else if (typeof value === 'object') {
      if ('length' in value) {
        addList(value);
      } else {
        addPreset(value);
      }
    } else {
      throw new Error('Expected usable value, not `' + value + '`');
    }

    if (settings) {
      namespace.settings = extend(namespace.settings || {}, settings);
    }

    return processor;

    function addPreset(result) {
      addList(result.plugins);

      if (result.settings) {
        settings = extend(settings || {}, result.settings);
      }
    }

    function add(value) {
      if (func(value)) {
        addPlugin(value);
      } else if (typeof value === 'object') {
        if ('length' in value) {
          addPlugin.apply(null, value);
        } else {
          addPreset(value);
        }
      } else {
        throw new Error('Expected usable value, not `' + value + '`');
      }
    }

    function addList(plugins) {
      var length;
      var index;

      if (plugins === null || plugins === undefined) {
        /* empty */
      } else if (array(plugins)) {
        length = plugins.length;
        index = -1;

        while (++index < length) {
          add(plugins[index]);
        }
      } else {
        throw new Error('Expected a list of plugins, not `' + plugins + '`');
      }
    }

    function addPlugin(plugin, value) {
      var entry = find(plugin);

      if (entry) {
        if (value !== false && entry[1] !== false && !array(value)) {
          value = extend(entry[1], value);
        }

        entry[1] = value;
      } else {
        attachers.push(slice.call(arguments));
      }
    }
  }

  function find(plugin) {
    var length = attachers.length;
    var index = -1;
    var entry;

    while (++index < length) {
      entry = attachers[index];

      if (entry[0] === plugin) {
        return entry;
      }
    }
  }

  /* Parse a file (in string or VFile representation)
   * into a Unist node using the `Parser` on the
   * processor. */
  function parse(doc) {
    var Parser = processor.Parser;
    var file = vfile(doc);

    freeze();
    assertParser('parse', Parser);

    if (newable(Parser)) {
      return new Parser(String(file), file).parse();
    }

    return Parser(String(file), file); // eslint-disable-line new-cap
  }

  /* Run transforms on a Unist node representation of a file
   * (in string or VFile representation), async. */
  function run(node, file, cb) {
    assertNode(node);
    freeze();

    if (!cb && func(file)) {
      cb = file;
      file = null;
    }

    if (!cb) {
      return new Promise(executor);
    }

    executor(null, cb);

    function executor(resolve, reject) {
      transformers.run(node, vfile(file), done);

      function done(err, tree, file) {
        tree = tree || node;
        if (err) {
          reject(err);
        } else if (resolve) {
          resolve(tree);
        } else {
          cb(null, tree, file);
        }
      }
    }
  }

  /* Run transforms on a Unist node representation of a file
   * (in string or VFile representation), sync. */
  function runSync(node, file) {
    var complete = false;
    var result;

    run(node, file, done);

    assertDone('runSync', 'run', complete);

    return result;

    function done(err, tree) {
      complete = true;
      bail(err);
      result = tree;
    }
  }

  /* Stringify a Unist node representation of a file
   * (in string or VFile representation) into a string
   * using the `Compiler` on the processor. */
  function stringify(node, doc) {
    var Compiler = processor.Compiler;
    var file = vfile(doc);

    freeze();
    assertCompiler('stringify', Compiler);
    assertNode(node);

    if (newable(Compiler)) {
      return new Compiler(node, file).compile();
    }

    return Compiler(node, file); // eslint-disable-line new-cap
  }

  /* Parse a file (in string or VFile representation)
   * into a Unist node using the `Parser` on the processor,
   * then run transforms on that node, and compile the
   * resulting node using the `Compiler` on the processor,
   * and store that result on the VFile. */
  function process(doc, cb) {
    freeze();
    assertParser('process', processor.Parser);
    assertCompiler('process', processor.Compiler);

    if (!cb) {
      return new Promise(executor);
    }

    executor(null, cb);

    function executor(resolve, reject) {
      var file = vfile(doc);

      pipeline.run(processor, {file: file}, done);

      function done(err) {
        if (err) {
          reject(err);
        } else if (resolve) {
          resolve(file);
        } else {
          cb(null, file);
        }
      }
    }
  }

  /* Process the given document (in string or VFile
   * representation), sync. */
  function processSync(doc) {
    var complete = false;
    var file;

    freeze();
    assertParser('processSync', processor.Parser);
    assertCompiler('processSync', processor.Compiler);
    file = vfile(doc);

    process(file, done);

    assertDone('processSync', 'process', complete);

    return file;

    function done(err) {
      complete = true;
      bail(err);
    }
  }
}

/* Check if `func` is a constructor. */
function newable(value) {
  return func(value) && keys(value.prototype);
}

/* Check if `value` is an object with keys. */
function keys(value) {
  var key;
  for (key in value) {
    return true;
  }
  return false;
}

/* Assert a parser is available. */
function assertParser(name, Parser) {
  if (!func(Parser)) {
    throw new Error('Cannot `' + name + '` without `Parser`');
  }
}

/* Assert a compiler is available. */
function assertCompiler(name, Compiler) {
  if (!func(Compiler)) {
    throw new Error('Cannot `' + name + '` without `Compiler`');
  }
}

/* Assert the processor is not frozen. */
function assertUnfrozen(name, frozen) {
  if (frozen) {
    throw new Error(
      'Cannot invoke `' + name + '` on a frozen processor.\n' +
      'Create a new processor first, by invoking it: ' +
      'use `processor()` instead of `processor`.'
    );
  }
}

/* Assert `node` is a Unist node. */
function assertNode(node) {
  if (!node || !string(node.type)) {
    throw new Error('Expected node, got `' + node + '`');
  }
}

/* Assert that `complete` is `true`. */
function assertDone(name, asyncName, complete) {
  if (!complete) {
    throw new Error('`' + name + '` finished async. Use `' + asyncName + '` instead');
  }
}
<commit_msg>Fix bug where parser/compiler were accessed before freezing<commit_after>'use strict';

/* Dependencies. */
var has = require('has');
var extend = require('extend');
var bail = require('bail');
var vfile = require('vfile');
var trough = require('trough');
var string = require('x-is-string');
var func = require('x-is-function');
var array = require('isarray');

/* Expose a frozen processor. */
module.exports = unified().freeze();

var slice = [].slice;

/* Process pipeline. */
var pipeline = trough().use(pipelineParse).use(pipelineRun).use(pipelineStringify);

function pipelineParse(p, ctx) {
  ctx.tree = p.parse(ctx.file);
}

function pipelineRun(p, ctx, next) {
  p.run(ctx.tree, ctx.file, done);

  function done(err, tree, file) {
    if (err) {
      next(err);
    } else {
      ctx.tree = tree;
      ctx.file = file;
      next();
    }
  }
}

function pipelineStringify(p, ctx) {
  ctx.file.contents = p.stringify(ctx.tree, ctx.file);
}

/* Function to create the first processor. */
function unified() {
  var attachers = [];
  var transformers = trough();
  var namespace = {};
  var frozen = false;

  /* Data management. */
  processor.data = data;

  /* Lock. */
  processor.freeze = freeze;

  /* Plug-ins. */
  processor.attachers = attachers;
  processor.use = use;

  /* API. */
  processor.parse = parse;
  processor.stringify = stringify;
  processor.run = run;
  processor.runSync = runSync;
  processor.process = process;
  processor.processSync = processSync;

  /* Expose. */
  return processor;

  /* Create a new processor based on the processor
   * in the current scope. */
  function processor() {
    var destination = unified();
    var length = attachers.length;
    var index = -1;

    while (++index < length) {
      destination.use.apply(null, attachers[index]);
    }

    destination.data(extend(true, {}, namespace));

    return destination;
  }

  /* Freeze: used to signal a processor that has finished
   * configuration.
   *
   * For example, take unified itself.  It’s frozen.
   * Plug-ins should not be added to it.  Rather, it should
   * be extended, by invoking it, before modifying it.
   *
   * In essence, always invoke this when exporting a
   * processor. */
  function freeze() {
    var length = attachers.length;
    var index = -1;
    var values;
    var plugin;
    var options;
    var transformer;

    if (frozen) {
      return processor;
    }

    while (++index < length) {
      values = attachers[index];
      plugin = values[0];
      options = values[1];
      transformer = null;

      if (options === false) {
        return;
      }

      if (options === true) {
        values[1] = undefined;
      }

      transformer = plugin.apply(processor, values.slice(1));

      if (func(transformer)) {
        transformers.use(transformer);
      }
    }

    frozen = true;

    return processor;
  }

  /* Data management.
   * Getter / setter for processor-specific informtion. */
  function data(key, value) {
    if (string(key)) {
      /* Set `key`. */
      if (arguments.length === 2) {
        assertUnfrozen('data', frozen);

        namespace[key] = value;

        return processor;
      }

      /* Get `key`. */
      return (has(namespace, key) && namespace[key]) || null;
    }

    /* Set space. */
    if (key) {
      assertUnfrozen('data', frozen);
      namespace = key;
      return processor;
    }

    /* Get space. */
    return namespace;
  }

  /* Plug-in management.
   *
   * Pass it:
   * *   an attacher and options,
   * *   a preset,
   * *   a list of presets, attachers, and arguments (list
   *     of attachers and options). */
  function use(value) {
    var settings;

    assertUnfrozen('use', frozen);

    if (value === null || value === undefined) {
      /* empty */
    } else if (func(value)) {
      addPlugin.apply(null, arguments);
    } else if (typeof value === 'object') {
      if ('length' in value) {
        addList(value);
      } else {
        addPreset(value);
      }
    } else {
      throw new Error('Expected usable value, not `' + value + '`');
    }

    if (settings) {
      namespace.settings = extend(namespace.settings || {}, settings);
    }

    return processor;

    function addPreset(result) {
      addList(result.plugins);

      if (result.settings) {
        settings = extend(settings || {}, result.settings);
      }
    }

    function add(value) {
      if (func(value)) {
        addPlugin(value);
      } else if (typeof value === 'object') {
        if ('length' in value) {
          addPlugin.apply(null, value);
        } else {
          addPreset(value);
        }
      } else {
        throw new Error('Expected usable value, not `' + value + '`');
      }
    }

    function addList(plugins) {
      var length;
      var index;

      if (plugins === null || plugins === undefined) {
        /* empty */
      } else if (array(plugins)) {
        length = plugins.length;
        index = -1;

        while (++index < length) {
          add(plugins[index]);
        }
      } else {
        throw new Error('Expected a list of plugins, not `' + plugins + '`');
      }
    }

    function addPlugin(plugin, value) {
      var entry = find(plugin);

      if (entry) {
        if (value !== false && entry[1] !== false && !array(value)) {
          value = extend(entry[1], value);
        }

        entry[1] = value;
      } else {
        attachers.push(slice.call(arguments));
      }
    }
  }

  function find(plugin) {
    var length = attachers.length;
    var index = -1;
    var entry;

    while (++index < length) {
      entry = attachers[index];

      if (entry[0] === plugin) {
        return entry;
      }
    }
  }

  /* Parse a file (in string or VFile representation)
   * into a Unist node using the `Parser` on the
   * processor. */
  function parse(doc) {
    var file = vfile(doc);
    var Parser;

    freeze();
    Parser = processor.Parser;
    assertParser('parse', Parser);

    if (newable(Parser)) {
      return new Parser(String(file), file).parse();
    }

    return Parser(String(file), file); // eslint-disable-line new-cap
  }

  /* Run transforms on a Unist node representation of a file
   * (in string or VFile representation), async. */
  function run(node, file, cb) {
    assertNode(node);
    freeze();

    if (!cb && func(file)) {
      cb = file;
      file = null;
    }

    if (!cb) {
      return new Promise(executor);
    }

    executor(null, cb);

    function executor(resolve, reject) {
      transformers.run(node, vfile(file), done);

      function done(err, tree, file) {
        tree = tree || node;
        if (err) {
          reject(err);
        } else if (resolve) {
          resolve(tree);
        } else {
          cb(null, tree, file);
        }
      }
    }
  }

  /* Run transforms on a Unist node representation of a file
   * (in string or VFile representation), sync. */
  function runSync(node, file) {
    var complete = false;
    var result;

    run(node, file, done);

    assertDone('runSync', 'run', complete);

    return result;

    function done(err, tree) {
      complete = true;
      bail(err);
      result = tree;
    }
  }

  /* Stringify a Unist node representation of a file
   * (in string or VFile representation) into a string
   * using the `Compiler` on the processor. */
  function stringify(node, doc) {
    var file = vfile(doc);
    var Compiler;

    freeze();
    Compiler = processor.Compiler;
    assertCompiler('stringify', Compiler);
    assertNode(node);

    if (newable(Compiler)) {
      return new Compiler(node, file).compile();
    }

    return Compiler(node, file); // eslint-disable-line new-cap
  }

  /* Parse a file (in string or VFile representation)
   * into a Unist node using the `Parser` on the processor,
   * then run transforms on that node, and compile the
   * resulting node using the `Compiler` on the processor,
   * and store that result on the VFile. */
  function process(doc, cb) {
    freeze();
    assertParser('process', processor.Parser);
    assertCompiler('process', processor.Compiler);

    if (!cb) {
      return new Promise(executor);
    }

    executor(null, cb);

    function executor(resolve, reject) {
      var file = vfile(doc);

      pipeline.run(processor, {file: file}, done);

      function done(err) {
        if (err) {
          reject(err);
        } else if (resolve) {
          resolve(file);
        } else {
          cb(null, file);
        }
      }
    }
  }

  /* Process the given document (in string or VFile
   * representation), sync. */
  function processSync(doc) {
    var complete = false;
    var file;

    freeze();
    assertParser('processSync', processor.Parser);
    assertCompiler('processSync', processor.Compiler);
    file = vfile(doc);

    process(file, done);

    assertDone('processSync', 'process', complete);

    return file;

    function done(err) {
      complete = true;
      bail(err);
    }
  }
}

/* Check if `func` is a constructor. */
function newable(value) {
  return func(value) && keys(value.prototype);
}

/* Check if `value` is an object with keys. */
function keys(value) {
  var key;
  for (key in value) {
    return true;
  }
  return false;
}

/* Assert a parser is available. */
function assertParser(name, Parser) {
  if (!func(Parser)) {
    throw new Error('Cannot `' + name + '` without `Parser`');
  }
}

/* Assert a compiler is available. */
function assertCompiler(name, Compiler) {
  if (!func(Compiler)) {
    throw new Error('Cannot `' + name + '` without `Compiler`');
  }
}

/* Assert the processor is not frozen. */
function assertUnfrozen(name, frozen) {
  if (frozen) {
    throw new Error(
      'Cannot invoke `' + name + '` on a frozen processor.\n' +
      'Create a new processor first, by invoking it: ' +
      'use `processor()` instead of `processor`.'
    );
  }
}

/* Assert `node` is a Unist node. */
function assertNode(node) {
  if (!node || !string(node.type)) {
    throw new Error('Expected node, got `' + node + '`');
  }
}

/* Assert that `complete` is `true`. */
function assertDone(name, asyncName, complete) {
  if (!complete) {
    throw new Error('`' + name + '` finished async. Use `' + asyncName + '` instead');
  }
}
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var through = require('through2');
var convert = require('convert-source-map');
var sm = require('source-map');
var crypto = require('crypto');
var fs = require('fs');
var _ = require('lodash');
var RSVP = require('rsvp');

function has(object, propName) {
  return Object.prototype.hasOwnProperty.call(object, propName);
}

function hashSource(str) {
  var hasher = crypto.createHash('sha256');
  hasher.update(str);
  return hasher.digest('base64').slice(0, 20);
}

var readManagerTemplate = _.once(function() {
  return new RSVP.Promise(function(resolve, reject) {
    fs.readFile(path.join(__dirname, 'hmr-manager-template.js'), 'utf8', function(err, data) {
      if (err)
        reject(err);
      else
        resolve(data);
    });
  });
});

var validUpdateModes = ['ajax', 'fs'];
var updateModesNeedingUrl = ['ajax'];

function makeIdentitySourceMap(content, resourcePath) {
  var map = new sm.SourceMapGenerator();
  map.setSourceContent(resourcePath, content);
  content.split('\n').map(function(line, index) {
    map.addMapping({
      source: resourcePath,
      original: {
        line: index+1,
        column: 0
      },
      generated: {
        line: index+1,
        column: 0
      }
    });
  });
  return map.toJSON();
}

module.exports = function(bundle, opts) {
  if (!opts) opts = {};
  var updateMode = opts.mode||opts.m||'ajax';
  var updateUrl = opts.url||opts.u||null;

  var updateCacheBust = (function(){
    var value = has(opts, 'cacheBust') ? opts.cacheBust : has(opts, 'b') ? opts.b : true;
    return Boolean(value && value !== 'false');
  })();
  var bundleKey = opts.key || updateMode+':'+(updateUrl||bundle.argv.outfile);

  if (updateMode === 'xhr') {
    console.warn('Use update mode "ajax" instead of "xhr".');
    updateMode = 'ajax';
  }

  if (!_.includes(validUpdateModes, updateMode)) {
    throw new Error("Invalid mode "+updateMode);
  }
  if (!updateUrl && _.includes(updateModesNeedingUrl, updateMode)) {
    throw new Error("url option must be specified for "+updateMode+" mode");
  }

  var basedir = opts.basedir !== undefined ? opts.basedir : process.cwd();

  function fileKey(filename) {
    return path.relative(basedir, filename);
  }

  var hmrManagerFilename;

  // keys are filenames, values are {hash, transformedSource}
  var transformCache = {};

  function setupPipelineMods() {
    var originalEntries = [];
    bundle.pipeline.get('record').push(through.obj(function(row, enc, next) {
      if (row.entry) {
        originalEntries.push(row.file);
        next(null);
      } else {
        next(null, row);
      }
    }, function(next) {
      var source = originalEntries.map(function(name) {
        return 'require('+JSON.stringify(name)+');\n';
      }).join('');

      // Put the hmr file name in the same directory as an entry file in order
      // to prevent this: https://github.com/babel/babelify/issues/85
      hmrManagerFilename = path.join(path.dirname(originalEntries[0]), '__hmr_manager.js');
      this.push({
        entry: true,
        expose: false,
        basedir: undefined,
        file: hmrManagerFilename,
        id: hmrManagerFilename,
        source: source,
        order: 0
      });
      next();
    }));

    var moduleMeta = {};

    function makeModuleMetaEntry(name) {
      if (!has(moduleMeta, name)) {
        moduleMeta[name] = {
          index: null,
          hash: null,
          parents: []
        };
      }
    }

    bundle.pipeline.get('deps').push(through.obj(function(row, enc, next) {
      if (row.file !== hmrManagerFilename) {
        makeModuleMetaEntry(fileKey(row.file));
        _.forOwn(row.deps, function(name, ref) {
          // dependencies that aren't included in the bundle have the name false
          if (name) {
            makeModuleMetaEntry(fileKey(name));
            moduleMeta[fileKey(name)].parents.push(fileKey(row.file));
          }
        });
      }
      next(null, row);
    }));

    bundle.pipeline.get('syntax').push(through.obj(function(row, enc, next) {
      if (row.file === hmrManagerFilename) {
        next(null, row);
      } else {
        var hash = moduleMeta[fileKey(row.file)].hash = hashSource(row.source);
        if (has(transformCache, row.file) && transformCache[row.file].hash === hash) {
          row.source = transformCache[row.file].transformedSource;
        } else {
          var header = '_hmr['+JSON.stringify(bundleKey)+
            '].initModule('+JSON.stringify(fileKey(row.file))+', module);\n(function(){\n';
          var footer = '\n}).call(this, arguments);\n';

          var inputMapCV = convert.fromSource(row.source);
          var inputMap;
          if (inputMapCV) {
            inputMap = inputMapCV.toObject();
            row.source = convert.removeComments(row.source);
          } else {
            inputMap = makeIdentitySourceMap(row.source, path.relative(basedir, row.file));
          }

          var node = new sm.SourceNode(null, null, null, [
            new sm.SourceNode(null, null, null, header),
            sm.SourceNode.fromStringWithSourceMap(row.source, new sm.SourceMapConsumer(inputMap)),
            new sm.SourceNode(null, null, null, footer)
          ]);

          var result = node.toStringWithSourceMap();
          row.source = result.code + convert.fromObject(result.map.toJSON()).toComment();

          transformCache[row.file] = {
            hash: hash,
            transformedSource: row.source
          };
        }
        next(null, row);
      }
    }));

    var managerRow = null;
    bundle.pipeline.get('label').push(through.obj(function(row, enc, next) {
      if (row.file !== hmrManagerFilename) {
        // row.id used when fullPaths flag is used
        moduleMeta[fileKey(row.file)].index = has(row, 'index') ? row.index : row.id;
        next(null, row);
      } else {
        managerRow = row;
        next(null);
      }
    }, function(done) {
      var self = this;
      readManagerTemplate().then(function(mgrTemplate) {
        managerRow.source = mgrTemplate
          .replace('null/*!^^moduleMeta*/', JSON.stringify(moduleMeta))
          .replace('null/*!^^originalEntries*/', JSON.stringify(originalEntries))
          .replace('null/*!^^updateUrl*/', JSON.stringify(updateUrl))
          .replace('null/*!^^updateMode*/', JSON.stringify(updateMode))
          .replace('null/*!^^updateCacheBust*/', JSON.stringify(updateCacheBust))
          .replace('null/*!^^bundleKey*/', JSON.stringify(bundleKey));
        self.push(managerRow);
      }).then(done, done);
    }));
  }
  setupPipelineMods();

  bundle.on('reset', setupPipelineMods);
};
<commit_msg>simplify options handling code<commit_after>'use strict';

var path = require('path');
var through = require('through2');
var convert = require('convert-source-map');
var sm = require('source-map');
var crypto = require('crypto');
var fs = require('fs');
var _ = require('lodash');
var RSVP = require('rsvp');

function has(object, propName) {
  return Object.prototype.hasOwnProperty.call(object, propName);
}

function hashStr(str) {
  var hasher = crypto.createHash('sha256');
  hasher.update(str);
  return hasher.digest('base64').slice(0, 20);
}

var readManagerTemplate = _.once(function() {
  return new RSVP.Promise(function(resolve, reject) {
    fs.readFile(path.join(__dirname, 'hmr-manager-template.js'), 'utf8', function(err, data) {
      if (err)
        reject(err);
      else
        resolve(data);
    });
  });
});

var validUpdateModes = ['ajax', 'fs'];
var updateModesNeedingUrl = ['ajax'];

function makeIdentitySourceMap(content, resourcePath) {
  var map = new sm.SourceMapGenerator();
  map.setSourceContent(resourcePath, content);
  content.split('\n').map(function(line, index) {
    map.addMapping({
      source: resourcePath,
      original: {
        line: index+1,
        column: 0
      },
      generated: {
        line: index+1,
        column: 0
      }
    });
  });
  return map.toJSON();
}

function readOpt(opts, long, short, defval) {
  return has(opts, long) ? opts[long] : has(opts, short) ? opts[short] : defval;
}

function boolOpt(value) {
  return Boolean(value && value !== 'false');
}

module.exports = function(bundle, opts) {
  if (!opts) opts = {};
  var updateMode = readOpt(opts, 'mode', 'm', 'ajax');
  if (updateMode === 'xhr') {
    console.warn('Use update mode "ajax" instead of "xhr".');
    updateMode = 'ajax';
  }
  var updateUrl = readOpt(opts, 'url', 'u', null);
  var updateCacheBust = boolOpt(readOpt(opts, 'cacheBust', 'b', true));
  var bundleKey = readOpt(opts, 'key', 'k', updateMode+':'+(updateUrl||bundle.argv.outfile));

  if (!_.includes(validUpdateModes, updateMode)) {
    throw new Error("Invalid mode "+updateMode);
  }
  if (!updateUrl && _.includes(updateModesNeedingUrl, updateMode)) {
    throw new Error("url option must be specified for "+updateMode+" mode");
  }

  var basedir = opts.basedir !== undefined ? opts.basedir : process.cwd();

  function fileKey(filename) {
    return path.relative(basedir, filename);
  }

  var hmrManagerFilename;

  // keys are filenames, values are {hash, transformedSource}
  var transformCache = {};

  function setupPipelineMods() {
    var originalEntries = [];
    bundle.pipeline.get('record').push(through.obj(function(row, enc, next) {
      if (row.entry) {
        originalEntries.push(row.file);
        next(null);
      } else {
        next(null, row);
      }
    }, function(next) {
      var source = originalEntries.map(function(name) {
        return 'require('+JSON.stringify(name)+');\n';
      }).join('');

      // Put the hmr file name in the same directory as an entry file in order
      // to prevent this: https://github.com/babel/babelify/issues/85
      hmrManagerFilename = path.join(path.dirname(originalEntries[0]), '__hmr_manager.js');
      this.push({
        entry: true,
        expose: false,
        basedir: undefined,
        file: hmrManagerFilename,
        id: hmrManagerFilename,
        source: source,
        order: 0
      });
      next();
    }));

    var moduleMeta = {};

    function makeModuleMetaEntry(name) {
      if (!has(moduleMeta, name)) {
        moduleMeta[name] = {
          index: null,
          hash: null,
          parents: []
        };
      }
    }

    bundle.pipeline.get('deps').push(through.obj(function(row, enc, next) {
      if (row.file !== hmrManagerFilename) {
        makeModuleMetaEntry(fileKey(row.file));
        _.forOwn(row.deps, function(name, ref) {
          // dependencies that aren't included in the bundle have the name false
          if (name) {
            makeModuleMetaEntry(fileKey(name));
            moduleMeta[fileKey(name)].parents.push(fileKey(row.file));
          }
        });
      }
      next(null, row);
    }));

    bundle.pipeline.get('syntax').push(through.obj(function(row, enc, next) {
      if (row.file === hmrManagerFilename) {
        next(null, row);
      } else {
        var hash = moduleMeta[fileKey(row.file)].hash = hashStr(row.source);
        if (has(transformCache, row.file) && transformCache[row.file].hash === hash) {
          row.source = transformCache[row.file].transformedSource;
        } else {
          var header = '_hmr['+JSON.stringify(bundleKey)+
            '].initModule('+JSON.stringify(fileKey(row.file))+', module);\n(function(){\n';
          var footer = '\n}).call(this, arguments);\n';

          var inputMapCV = convert.fromSource(row.source);
          var inputMap;
          if (inputMapCV) {
            inputMap = inputMapCV.toObject();
            row.source = convert.removeComments(row.source);
          } else {
            inputMap = makeIdentitySourceMap(row.source, path.relative(basedir, row.file));
          }

          var node = new sm.SourceNode(null, null, null, [
            new sm.SourceNode(null, null, null, header),
            sm.SourceNode.fromStringWithSourceMap(row.source, new sm.SourceMapConsumer(inputMap)),
            new sm.SourceNode(null, null, null, footer)
          ]);

          var result = node.toStringWithSourceMap();
          row.source = result.code + convert.fromObject(result.map.toJSON()).toComment();

          transformCache[row.file] = {
            hash: hash,
            transformedSource: row.source
          };
        }
        next(null, row);
      }
    }));

    var managerRow = null;
    bundle.pipeline.get('label').push(through.obj(function(row, enc, next) {
      if (row.file !== hmrManagerFilename) {
        // row.id used when fullPaths flag is used
        moduleMeta[fileKey(row.file)].index = has(row, 'index') ? row.index : row.id;
        next(null, row);
      } else {
        managerRow = row;
        next(null);
      }
    }, function(done) {
      var self = this;
      readManagerTemplate().then(function(mgrTemplate) {
        managerRow.source = mgrTemplate
          .replace('null/*!^^moduleMeta*/', JSON.stringify(moduleMeta))
          .replace('null/*!^^originalEntries*/', JSON.stringify(originalEntries))
          .replace('null/*!^^updateUrl*/', JSON.stringify(updateUrl))
          .replace('null/*!^^updateMode*/', JSON.stringify(updateMode))
          .replace('null/*!^^updateCacheBust*/', JSON.stringify(updateCacheBust))
          .replace('null/*!^^bundleKey*/', JSON.stringify(bundleKey));
        self.push(managerRow);
      }).then(done, done);
    }));
  }
  setupPipelineMods();

  bundle.on('reset', setupPipelineMods);
};
<|endoftext|>


<commit_before>const ethUtil = require('ethereumjs-util')
const fees = require('ethereum-common')
const ecdsa = require('secp256k1')
const BN = ethUtil.BN
const rlp = ethUtil.rlp

// secp256k1n/2
const N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16)

// give browser access to Buffers
global.Buffer = Buffer
global.ethUtil = ethUtil

/**
 * Creates a new transaction object
 * @constructor
 * @class {Buffer|Array} data a transaction can be initiailized with either a buffer containing the RLP serialized transaction or an array of buffers relating to each of the tx Properties, listed in order below in the exmple. Or lastly an Object containing the Properties of the transaction like in the Usage example
 *
 * For Object and Arrays each of the elements can either be a Buffer, a hex-prefixed (0x) String , Number, or an object with a toBuffer method such as Bignum
 * @example
 * var rawTx = {
 *   nonce: '00',
 *   gasPrice: '09184e72a000',
 *   gasLimit: '2710',
 *   to: '0000000000000000000000000000000000000000',
 *   value: '00',
 *   data: '7f7465737432000000000000000000000000000000000000000000000000000000600057',
 *   v: '1c',
 *   r: '5e1d3a76fbf824220eafc8c79ad578ad2b67d01b0c2425eb1f1347e8f50882ab',
 *   s '5bd428537f05f9830e93792f90ea6a3e2d1ee84952dd96edbae9f658f831ab13'
 * };
 * var tx = new Transaction(rawTx);
 * @prop {Buffer} raw The raw rlp decoded transaction
 * @prop {Buffer} nonce
 * @prop {Buffer} to the to address
 * @prop {Buffer} value the amount of ether sent
 * @prop {Buffer} data this will contain the data of the message or the init of a contract
 * @prop {Buffer} v EC signature parameter
 * @prop {Buffer} r EC signature parameter
 * @prop {Buffer} s EC recovery ID
 * @prop {Buffer} from If you are not planing on signing the tx you can set the from property. If you do sign it will be over written
 */
var Transaction = module.exports = function (data) {
  // Define Properties
  const fields = [{
    name: 'nonce',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 'gasPrice',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 'gasLimit',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 'to',
    allowZero: true,
    length: 20,
    default: new Buffer([])
  }, {
    name: 'value',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 'data',
    allowZero: true,
    default: new Buffer([])
  }, {
    name: 'v',
    length: 1,
    default: new Buffer([0x1c])
  }, {
    name: 'r',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 's',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }]

  Object.defineProperty(this, 'from', {
    enumerable: false,
    configurable: true,
    get: function () {
      if (this._from) {
        return this._from
      }
      this._from = this.getSenderAddress()
      return this._from
    },
    set: function (v) {
      this._from = v
    }
  })

  ethUtil.defineProperties(this, fields, data)
  this._homestead = true
}

/**
 * Returns the rlp encoding of the transaction
 * @method serialize
 * @return {Buffer}
 */
Transaction.prototype.serialize = function () {
  return rlp.encode(this.raw)
}

/**
 * If the tx's `to` is to the creation address
 * @method toCreationAddress
 * @return {Boolean}
 */
Transaction.prototype.toCreationAddress = function () {
  return this.to.toString('hex') === ''
}

/**
 * Computes a sha3-256 hash of the serialized tx
 * @method hash
 * @param {Boolean} [signature=true] whether or not to inculde the signature
 * @return {Buffer}
 */
Transaction.prototype.hash = function (signature) {
  var toHash

  if (typeof signature === 'undefined') {
    signature = true
  }

  toHash = signature ? this.raw : this.raw.slice(0, 6)

  // create hash
  return ethUtil.rlphash(toHash)
}

/**
 * returns the sender`s address
 * @method getSenderAddress
 * @return {Buffer}
 */
Transaction.prototype.getSenderAddress = function () {
  var pubKey = this.getSenderPublicKey()
  pubKey = ecdsa.publicKeyConvert(pubKey, false)
  return ethUtil.pubToAddress(pubKey)
}

/**
 * returns the public key of the sender
 * @method getSenderPublicKey
 * @return {Buffer}
 */
Transaction.prototype.getSenderPublicKey = function () {
  if (!this._senderPubKey || !this._senderPubKey.length) {
    this.verifySignature()
  }

  return this._senderPubKey
}

/**
 * Determines if the signature is valid
 * @method verifySignature
 * @return {Boolean}
 */
Transaction.prototype.verifySignature = function () {
  var msgHash = this.hash(false)
  var signature = Buffer.concat([ethUtil.pad(this.r, 32), ethUtil.pad(this.s, 32)], 64)
  var recovery = ethUtil.bufferToInt(this.v) - 27

  // All transaction signatures whose s-value is greater than secp256k1n/2 are considered invalid.
  if (this._homestead && new BN(this.s).cmp(N_DIV_2) === 1) {
    return false
  }

  try {
    this._senderPubKey = ecdsa.recoverSync(msgHash, signature, recovery)
  } catch (e) {
    return false
  }

  if (!this._senderPubKey) {
    return false
  }

  //
  // In node-secp256k1, `recover` will fail on invalid inputs, but in
  // elliptic this is not enforced.
  //
  // Here we enable a pubkey based verification only in the case
  // of browserified output, where elliptic will be used, to workaround the issue.
  //
  // TODO: fix elliptic?
  if (process.browser) {
    var result = ecdsa.verifySync(msgHash, signature, this._senderPubKey)
    if (!result) {
      this._senderPubKey = null
    }
  } else {
    result = !!this._senderPubKey
  }

  return result
}
/**
 * sign a transaction with a given a private key
 * @method sign
 * @param {Buffer} privateKey
 */
Transaction.prototype.sign = function (privateKey) {
  var msgHash = this.hash(false)
  var sig = ecdsa.signSync(msgHash, privateKey)

  this.r = sig.signature.slice(0, 32)
  this.s = sig.signature.slice(32, 64)
  this.v = sig.recovery + 27
}
/**
 * The amount of gas paid for the data in this tx
 * @method getDataFee
 * @return {BN}
 */
Transaction.prototype.getDataFee = function () {
  const data = this.raw[5]
  var cost = new BN(0)
  for (var i = 0; i < data.length; i++) {
    data[i] === 0 ? cost.iaddn(fees.txDataZeroGas.v) : cost.iaddn(fees.txDataNonZeroGas.v)
  }
  return cost
}

/**
 * the minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee)
 * @method getBaseFee
 * @return {BN}
 */
Transaction.prototype.getBaseFee = function () {
  var fee = this.getDataFee().iaddn(fees.txGas.v)
  if (this._homestead && this.toCreationAddress()) {
    fee.iaddn(fees.txCreation.v)
  }
  return fee
}

/**
 * the up front amount that an account must have for this transaction to be valid
 * @method getUpfrontCost
 * @return {BN}
 */
Transaction.prototype.getUpfrontCost = function () {
  return new BN(this.gasLimit)
    .imul(new BN(this.gasPrice))
    .iadd(new BN(this.value))
}

/**
 * validates the signature and checks to see if it has enough gas
 * @method validate
 * @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean
 * @return {Boolean|String}
 */
Transaction.prototype.validate = function (stringError) {
  var errors = []
  if (!this.verifySignature()) {
    errors.push('Invalid Signature')
  }

  if (this.getBaseFee().cmp(new BN(this.gasLimit)) > 0) {
    errors.push(['gas limit is to low. Need at least ' + this.getBaseFee()])
  }

  if (stringError === undefined || stringError === false) {
    return errors.length === 0
  } else {
    try {
      return errors.reduce(function (str, err) {
        if (str) {
          str += ' '
        }
        return str + err
      })
    } catch (e) {
      return ''
    }
  }
}
<commit_msg>Use publicToAddress instead of pubToAddress and comment why publicKeyConvert is needed<commit_after>const ethUtil = require('ethereumjs-util')
const fees = require('ethereum-common')
const ecdsa = require('secp256k1')
const BN = ethUtil.BN
const rlp = ethUtil.rlp

// secp256k1n/2
const N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16)

// give browser access to Buffers
global.Buffer = Buffer
global.ethUtil = ethUtil

/**
 * Creates a new transaction object
 * @constructor
 * @class {Buffer|Array} data a transaction can be initiailized with either a buffer containing the RLP serialized transaction or an array of buffers relating to each of the tx Properties, listed in order below in the exmple. Or lastly an Object containing the Properties of the transaction like in the Usage example
 *
 * For Object and Arrays each of the elements can either be a Buffer, a hex-prefixed (0x) String , Number, or an object with a toBuffer method such as Bignum
 * @example
 * var rawTx = {
 *   nonce: '00',
 *   gasPrice: '09184e72a000',
 *   gasLimit: '2710',
 *   to: '0000000000000000000000000000000000000000',
 *   value: '00',
 *   data: '7f7465737432000000000000000000000000000000000000000000000000000000600057',
 *   v: '1c',
 *   r: '5e1d3a76fbf824220eafc8c79ad578ad2b67d01b0c2425eb1f1347e8f50882ab',
 *   s '5bd428537f05f9830e93792f90ea6a3e2d1ee84952dd96edbae9f658f831ab13'
 * };
 * var tx = new Transaction(rawTx);
 * @prop {Buffer} raw The raw rlp decoded transaction
 * @prop {Buffer} nonce
 * @prop {Buffer} to the to address
 * @prop {Buffer} value the amount of ether sent
 * @prop {Buffer} data this will contain the data of the message or the init of a contract
 * @prop {Buffer} v EC signature parameter
 * @prop {Buffer} r EC signature parameter
 * @prop {Buffer} s EC recovery ID
 * @prop {Buffer} from If you are not planing on signing the tx you can set the from property. If you do sign it will be over written
 */
var Transaction = module.exports = function (data) {
  // Define Properties
  const fields = [{
    name: 'nonce',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 'gasPrice',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 'gasLimit',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 'to',
    allowZero: true,
    length: 20,
    default: new Buffer([])
  }, {
    name: 'value',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 'data',
    allowZero: true,
    default: new Buffer([])
  }, {
    name: 'v',
    length: 1,
    default: new Buffer([0x1c])
  }, {
    name: 'r',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }, {
    name: 's',
    length: 32,
    allowLess: true,
    default: new Buffer([])
  }]

  Object.defineProperty(this, 'from', {
    enumerable: false,
    configurable: true,
    get: function () {
      if (this._from) {
        return this._from
      }
      this._from = this.getSenderAddress()
      return this._from
    },
    set: function (v) {
      this._from = v
    }
  })

  ethUtil.defineProperties(this, fields, data)
  this._homestead = true
}

/**
 * Returns the rlp encoding of the transaction
 * @method serialize
 * @return {Buffer}
 */
Transaction.prototype.serialize = function () {
  return rlp.encode(this.raw)
}

/**
 * If the tx's `to` is to the creation address
 * @method toCreationAddress
 * @return {Boolean}
 */
Transaction.prototype.toCreationAddress = function () {
  return this.to.toString('hex') === ''
}

/**
 * Computes a sha3-256 hash of the serialized tx
 * @method hash
 * @param {Boolean} [signature=true] whether or not to inculde the signature
 * @return {Buffer}
 */
Transaction.prototype.hash = function (signature) {
  var toHash

  if (typeof signature === 'undefined') {
    signature = true
  }

  toHash = signature ? this.raw : this.raw.slice(0, 6)

  // create hash
  return ethUtil.rlphash(toHash)
}

/**
 * returns the sender`s address
 * @method getSenderAddress
 * @return {Buffer}
 */
Transaction.prototype.getSenderAddress = function () {
  var pubKey = this.getSenderPublicKey()
  // ensure we have an uncompressed key
  pubKey = ecdsa.publicKeyConvert(pubKey, false)
  return ethUtil.publicToAddress(pubKey)
}

/**
 * returns the public key of the sender
 * @method getSenderPublicKey
 * @return {Buffer}
 */
Transaction.prototype.getSenderPublicKey = function () {
  if (!this._senderPubKey || !this._senderPubKey.length) {
    this.verifySignature()
  }

  return this._senderPubKey
}

/**
 * Determines if the signature is valid
 * @method verifySignature
 * @return {Boolean}
 */
Transaction.prototype.verifySignature = function () {
  var msgHash = this.hash(false)
  var signature = Buffer.concat([ethUtil.pad(this.r, 32), ethUtil.pad(this.s, 32)], 64)
  var recovery = ethUtil.bufferToInt(this.v) - 27

  // All transaction signatures whose s-value is greater than secp256k1n/2 are considered invalid.
  if (this._homestead && new BN(this.s).cmp(N_DIV_2) === 1) {
    return false
  }

  try {
    this._senderPubKey = ecdsa.recoverSync(msgHash, signature, recovery)
  } catch (e) {
    return false
  }

  if (!this._senderPubKey) {
    return false
  }

  //
  // In node-secp256k1, `recover` will fail on invalid inputs, but in
  // elliptic this is not enforced.
  //
  // Here we enable a pubkey based verification only in the case
  // of browserified output, where elliptic will be used, to workaround the issue.
  //
  // TODO: fix elliptic?
  if (process.browser) {
    var result = ecdsa.verifySync(msgHash, signature, this._senderPubKey)
    if (!result) {
      this._senderPubKey = null
    }
  } else {
    result = !!this._senderPubKey
  }

  return result
}
/**
 * sign a transaction with a given a private key
 * @method sign
 * @param {Buffer} privateKey
 */
Transaction.prototype.sign = function (privateKey) {
  var msgHash = this.hash(false)
  var sig = ecdsa.signSync(msgHash, privateKey)

  this.r = sig.signature.slice(0, 32)
  this.s = sig.signature.slice(32, 64)
  this.v = sig.recovery + 27
}
/**
 * The amount of gas paid for the data in this tx
 * @method getDataFee
 * @return {BN}
 */
Transaction.prototype.getDataFee = function () {
  const data = this.raw[5]
  var cost = new BN(0)
  for (var i = 0; i < data.length; i++) {
    data[i] === 0 ? cost.iaddn(fees.txDataZeroGas.v) : cost.iaddn(fees.txDataNonZeroGas.v)
  }
  return cost
}

/**
 * the minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee)
 * @method getBaseFee
 * @return {BN}
 */
Transaction.prototype.getBaseFee = function () {
  var fee = this.getDataFee().iaddn(fees.txGas.v)
  if (this._homestead && this.toCreationAddress()) {
    fee.iaddn(fees.txCreation.v)
  }
  return fee
}

/**
 * the up front amount that an account must have for this transaction to be valid
 * @method getUpfrontCost
 * @return {BN}
 */
Transaction.prototype.getUpfrontCost = function () {
  return new BN(this.gasLimit)
    .imul(new BN(this.gasPrice))
    .iadd(new BN(this.value))
}

/**
 * validates the signature and checks to see if it has enough gas
 * @method validate
 * @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean
 * @return {Boolean|String}
 */
Transaction.prototype.validate = function (stringError) {
  var errors = []
  if (!this.verifySignature()) {
    errors.push('Invalid Signature')
  }

  if (this.getBaseFee().cmp(new BN(this.gasLimit)) > 0) {
    errors.push(['gas limit is to low. Need at least ' + this.getBaseFee()])
  }

  if (stringError === undefined || stringError === false) {
    return errors.length === 0
  } else {
    try {
      return errors.reduce(function (str, err) {
        if (str) {
          str += ' '
        }
        return str + err
      })
    } catch (e) {
      return ''
    }
  }
}
<|endoftext|>


<commit_before>// Cort tested exhaustively!
//
// Copyright (c) 2017 12 Quarters Consulting & ...Max...
// MIT License - https://raw.githubusercontent.com/MaxMotovilov/cort/master/LICENSE

exports.run = function run( test_case, complete, options ) {
    const meta = {};

    cort(
        (later, done) => test_case( later, done, meta ),
        null,
        err => err ? complete( err, meta ) : complete(),
        options,
        meta
    )()
}

exports.iterate = function iterate( test_case, options ) {

    return iterator( null, [], 0 )

    function iterator( root, path, run_no ) {
        const result = loop(),

              iteration = cort(
                    test_case,
                    (new_root, new_run_no) => {
                        root = new_root;
                        run_no = new_run_no;
                        next();
                    },
                    err => done( err ),
                    options,
                    result,
                    root,
                    path,
                    run_no
              );

        var	next, done;

        result.copy = () => iterator( deepCopy( root ), path.slice(), run_no );

        return result;

        function* loop() {
            var promise, finished;

            while( !finished ) {
                promise = (options && options.promise || builtinPromise)(
                    function( resolve, reject ) {
                        next = () => {
                            promise = null;
                            resolve( true );
                        }
                        done = err => {
                            promise = null;
                            finished = true;
                            if( err != null )
                                reject( err );
                            else
                                resolve( false );
                        }
                    }
                );

                (options && options.enqueue || setImmediate)( iteration );

                yield promise;

                if( promise )
                    throw Error( "Assertion failed in cort: next() called before run has completed" );
            }
        }
    }
}

function cort( iteration, next_iteration, complete, options, meta, root, path, run_no ) {

    var pos;

    path = path || [];
    run_no = run_no || 0;

    Object.defineProperties( meta, {
        name:  { get: function() {
            var result = [], n = run_no - 1;

            do {
                result.push( String.fromCharCode( n % 26 + "a".charCodeAt(0) ) );
                n = Math.floor( n / 26 );
            } while( n > 0 );

            return result.reverse().join( "" )
        } },

        trace: { get: function() { return path.slice( 0, pos ).map( cleanTag ) } },

        todo:  { get: function() { return path.slice( pos ).map( cleanTag ) } }
    } );

    return runTestCase

    function runTestCase() {
        var curr, pending, finished;
        const pool = [];

        pos = 0;
        ++run_no;

        if( options && options.maxRuns && run_no > options.maxRuns ) {
            complete( Error( "maxRuns exceeded" ), meta );
            return
        }

        iteration( later, done );

        function later( tag, fn ) {

            const seq = this && this.later && this || { tags: [] };
            if( !seq.later )
                seq.later = later.bind( seq );

            if( fn == null ) {
                fn = tag;
                tag = fn.toString();
            }

            pool.push( { seq: seq, pos: seq.tags.length, fn: fn } );
            seq.tags.push( tag );

            pendingNextStep();

            return seq
        }

        function ready( item, callback ) {
            item.running = false;
            item.fn = callback;
            pendingNextStep();
        }

        function done( err ) {
            if( err != null )
                 complete( err );
            finished = true;
            pendingNextStep();
        }

        function pendingNextStep() {
            if( !pending ) {
                pending = true;
                (options && options.enqueue || setImmediate)( nextStep );
            }
        }

        function nextStep() {
            var next;

            pending = false;

            if( pool.length > 0 ) {
                if( path.length == pos ) {
                    // Growing the tree

                    pool.sort( initialStepOrder );

                    if( pool[0].running )
                        // top candidate still running, wait for it to complete
                        return

                    let node = { next: {}, pool: pool.map( item => ({ seq: { tags: item.seq.tags }, pos: item.pos, running: item.running }) ) }

                    if( pos == 0 )
                        root = curr = node;
                    else
                        curr = curr.next[ path[pos-1] ] = node;

                    path.push( tagList( pool[0] ) );

                    next = pool.shift();
                } else {
                    // Navigating the path

                    let next_index = pool.findIndex( item => tagList( item ) == path[pos] );

                    if( next_index < 0 ) {
                        complete(
                            Error( "Non-deterministic test case: expected step not scheduled\n" + path[pos] )
                        );
                        return
                    } else if( pool[next_index].running ) {
                        // action we are waiting for is still running, wait for it to complete
                        return
                    } else {
                        curr = pos == 0 ? root : curr.next[ path[pos-1] ];
                        if( !curr )
                            nodeNotFound();

                        [next] = pool.splice( next_index, 1 );
                    }
                }

                let has_duration = next.running == null && next.fn.length;

                if( has_duration )
                    // Start action and wait for completion
                    pool.unshift( { seq: next.seq, pos: next.pos, running: true } );

                ++ pos;

                if( pool.some( item => !item.running ) )
                    // There is at least one pending step in the pool, so try again after executing current one
                    pendingNextStep();

                try {
                    if( has_duration )
                        next.fn( makeReadyCallback( ready, pool[0] ) );
                    else
                        next.fn();
                } catch( err ) {
                    complete( err )
                }
            }

            if( pool.length == 0 && !pending && finished ) {
                if( pos < path.length )
                    complete( Error( "Non-deterministic test case: done() called before expected steps completed" ) );
                nextTestCase();
            }
        }
    }

    function nextTestCase() {
        var tried, curr, pos;

        while( path.length > 0 ) {
            tried = path.pop();
            curr = root;

            try {
                path.forEach( tag => (curr = curr.next[tag]) );
                pos = curr.pool.findIndex( item => tagList( item ) == tried );
            } catch( e ) {
                nodeNotFound()
            }

            if( pos < 0 )
                nodeNotFound();
            else while( ++pos < curr.pool.length ) {
                if( curr.pool[pos].pos == 0 || path.indexOf( tagList( curr.pool[pos], -1 ) ) >= 0 ) {
                    path.push( tagList( curr.pool[ pos ] ) );

                    if( next_iteration )
                        next_iteration( root, run_no );
                    else
                        runTestCase();

                    return
                }
            }
        }

        complete();
    }

    function makeReadyCallback( ready, item ) {
        const result =
                callback => function() {
                    ready( item, () => callback.apply( this, arguments ) )
                }

        result.when =
                v_or_p => v_or_p && typeof v_or_p.then === 'function'
                    ? v_or_p.then( x => whenReady( x ), err => whenReady( null, err ) )
                    : whenReady( v_or_p )

        return result

        function whenReady( value, err ) {
            return (options && options.promise || builtinPromise)(
                (resolve, reject) =>
                    ready( item, err == null ? () => resolve( value ) : () => reject( err ) )
            )
        }
    }
}

function builtinPromise( init ) {
    return new Promise( init )
}

function deepCopy( x ) {
    return JSON.parse( JSON.stringify( x ) )
}

function initialStepOrder( a, b ) {
    return (b.running === false) - (a.running === false) ||
           tagList(a).localeCompare( tagList(b) )
}

function nodeNotFound() {
    // Bug in cort
    throw Error( "Assertion failed in cort: node not found at path" )
}

function tagList( item, rel ) {
    return item.seq.tags.slice( 0, item.pos + 1 + ( rel || 0 ) ).join( "\xffff" ) + (item.running != null ? '\xfffe' : '')
}

function cleanTag( t ) {
    return t.replace( /^[\s\S]*\xffff/, "" ).replace( /\xfffe$/, " (completed)" )
}
<commit_msg>Added later().promise() API<commit_after>// Cort tested exhaustively!
//
// Copyright (c) 2017 12 Quarters Consulting & ...Max...
// MIT License - https://raw.githubusercontent.com/MaxMotovilov/cort/master/LICENSE

exports.run = function run( test_case, complete, options ) {
    const meta = {};

    cort(
        (later, done) => test_case( later, done, meta ),
        null,
        err => err ? complete( err, meta ) : complete(),
        options,
        meta
    )()
}

exports.iterate = function iterate( test_case, options ) {

    return iterator( null, [], 0 )

    function iterator( root, path, run_no ) {
        const result = loop(),

              iteration = cort(
                    test_case,
                    (new_root, new_run_no) => {
                        root = new_root;
                        run_no = new_run_no;
                        next();
                    },
                    err => done( err ),
                    options,
                    result,
                    root,
                    path,
                    run_no
              );

        var	next, done;

        result.copy = () => iterator( deepCopy( root ), path.slice(), run_no );

        return result;

        function* loop() {
            var promise, finished;

            while( !finished ) {
                promise = (options && options.promise || builtinPromise)(
                    function( resolve, reject ) {
                        next = () => {
                            promise = null;
                            resolve( true );
                        }
                        done = err => {
                            promise = null;
                            finished = true;
                            if( err != null )
                                reject( err );
                            else
                                resolve( false );
                        }
                    }
                );

                (options && options.enqueue || setImmediate)( iteration );

                yield promise;

                if( promise )
                    throw Error( "Assertion failed in cort: next() called before run has completed" );
            }
        }
    }
}

function cort( iteration, next_iteration, complete, options, meta, root, path, run_no ) {

    var pos;

    path = path || [];
    run_no = run_no || 0;

    Object.defineProperties( meta, {
        name:  { get: function() {
            var result = [], n = run_no - 1;

            do {
                result.push( String.fromCharCode( n % 26 + "a".charCodeAt(0) ) );
                n = Math.floor( n / 26 );
            } while( n > 0 );

            return result.reverse().join( "" )
        } },

        trace: { get: function() { return path.slice( 0, pos ).map( cleanTag ) } },

        todo:  { get: function() { return path.slice( pos ).map( cleanTag ) } }
    } );

    return runTestCase

    function runTestCase() {
        var curr, pending, finished;
        const pool = [];

        pos = 0;
        ++run_no;

        if( options && options.maxRuns && run_no > options.maxRuns ) {
            complete( Error( "maxRuns exceeded" ), meta );
            return
        }

        iteration( later, done );

        function later( tag, fn ) {

            const seq = this && this.later && this || { tags: [], promise: promisifyLater };
            if( !seq.later )
                seq.later = later.bind( seq );

            if( fn == null ) {
                fn = tag;
                tag = fn.toString();
            }

            pool.push( { seq: seq, pos: seq.tags.length, fn: fn } );
            seq.tags.push( tag );

            pendingNextStep();

            return seq
        }

        function ready( item, callback ) {
            item.running = false;
            item.fn = callback;
            pendingNextStep();
        }

        function done( err ) {
            if( err != null )
                 complete( err );
            finished = true;
            pendingNextStep();
        }

        function pendingNextStep() {
            if( !pending ) {
                pending = true;
                (options && options.enqueue || setImmediate)( nextStep );
            }
        }

        function nextStep() {
            var next;

            pending = false;

            if( pool.length > 0 ) {
                if( path.length == pos ) {
                    // Growing the tree

                    pool.sort( initialStepOrder );

                    if( pool[0].running )
                        // top candidate still running, wait for it to complete
                        return

                    let node = {
                        next: {},
                        pool: pool.map(
                            item => ({ seq: { tags: item.seq.tags }, pos: item.pos, running: item.running })
                        )
                    }

                    if( pos == 0 )
                        root = curr = node;
                    else
                        curr = curr.next[ path[pos-1] ] = node;

                    path.push( tagList( pool[0] ) );

                    next = pool.shift();
                } else {
                    // Navigating the path

                    let next_index = pool.findIndex( item => tagList( item ) == path[pos] );

                    if( next_index < 0 ) {
                        complete(
                            Error( "Non-deterministic test case: expected step not scheduled\n" + path[pos] )
                        );
                        return
                    } else if( pool[next_index].running ) {
                        // action we are waiting for is still running, wait for it to complete
                        return
                    } else {
                        curr = pos == 0 ? root : curr.next[ path[pos-1] ];
                        if( !curr )
                            nodeNotFound();

                        [next] = pool.splice( next_index, 1 );
                    }
                }

                let has_duration = next.running == null && next.fn.length;

                if( has_duration )
                    // Start action and wait for completion
                    pool.unshift( { seq: next.seq, pos: next.pos, running: true } );

                ++ pos;

                if( pool.some( item => !item.running ) )
                    // There is at least one pending step in the pool, so try again after executing current one
                    pendingNextStep();

                try {
                    if( has_duration )
                        next.fn( makeReadyCallback( ready, pool[0] ) );
                    else
                        next.fn();
                } catch( err ) {
                    complete( err )
                }
            }

            if( pool.length == 0 && !pending && finished ) {
                if( pos < path.length )
                    complete( Error( "Non-deterministic test case: done() called before expected steps completed" ) );
                nextTestCase();
            }
        }

        function promisifyLater() {
            // this = sequence object
            const key = tagList( { seq: this, pos: this.tags.length-1 } ),
                  item = pool.find( item => tagList( item ) == key ),
                  fn = item && item.fn;

            if( !item )
                throw Error( "later().promise() used out of sequence" );

            return (options && options.promise || builtinPromise)( fn.length ? wrap1 : wrap0 );

            function wrap0( resolve, reject ) {
                item.fn = () => {
                    try {
                        resolve( fn() )
                    } catch( err ) {
                        reject( err )
                    }
                }
            }

            function wrap1( resolve, reject ) {
                item.fn = ready => {
                    try {
                        resolve( fn( ready ) )
                    } catch( err ) {
                        reject( err )
                    }
                }
            }
        }
    }

    function nextTestCase() {
        var tried, curr, pos;

        while( path.length > 0 ) {
            tried = path.pop();
            curr = root;

            try {
                path.forEach( tag => (curr = curr.next[tag]) );
                pos = curr.pool.findIndex( item => tagList( item ) == tried );
            } catch( e ) {
                nodeNotFound()
            }

            if( pos < 0 )
                nodeNotFound();
            else while( ++pos < curr.pool.length ) {
                if( curr.pool[pos].pos == 0 || path.indexOf( tagList( curr.pool[pos], -1 ) ) >= 0 ) {
                    path.push( tagList( curr.pool[ pos ] ) );

                    if( next_iteration )
                        next_iteration( root, run_no );
                    else
                        runTestCase();

                    return
                }
            }
        }

        complete();
    }

    function makeReadyCallback( ready, item ) {
        const result =
                callback => function() {
                    ready( item, () => callback.apply( this, arguments ) )
                }

        result.when =
                v_or_p => v_or_p && typeof v_or_p.then === 'function'
                    ? v_or_p.then( x => whenReady( x ), err => whenReady( null, err ) )
                    : whenReady( v_or_p )

        return result

        function whenReady( value, err ) {
            return (options && options.promise || builtinPromise)(
                (resolve, reject) =>
                    ready( item, err == null ? () => resolve( value ) : () => reject( err ) )
            )
        }
    }
}

function builtinPromise( init ) {
    return new Promise( init )
}

function deepCopy( x ) {
    return JSON.parse( JSON.stringify( x ) )
}

function initialStepOrder( a, b ) {
    return (b.running === false) - (a.running === false) ||
           tagList(a).localeCompare( tagList(b) )
}

function nodeNotFound() {
    // Bug in cort
    throw Error( "Assertion failed in cort: node not found at path" )
}

function tagList( item, rel ) {
    return item.seq.tags.slice( 0, item.pos + 1 + ( rel || 0 ) ).join( "\xffff" ) + (item.running != null ? '\xfffe' : '')
}

function cleanTag( t ) {
    return t.replace( /^[\s\S]*\xffff/, "" ).replace( /\xfffe$/, " (completed)" )
}
<|endoftext|>


<commit_before>/**
 * Yes you can use it with your self-hosted server or any other cloud services
 * like Parse.com or Appcelerator cloud.
 *
 * @auther Hazem Khaled <hazem.khaled@gmail.com>
 */
var ANDROID = Ti.Platform.name === 'android',
  IOS = !ANDROID && (Ti.Platform.name === 'iPhone OS');

if (ANDROID) {
  var GCM = require("nl.vanvianen.android.gcm");
}

function TiPush(e) {
  this.backendUrl = e.backendUrl;
  this.token = '';
  this.os = (ANDROID) ? 'Android' : 'iOS';
}

TiPush.prototype.registerDevice = function(_prams) {
  var that = this,
    token = '',
    onReceive = _prams.onReceive,
    onStart = _prams.onStart || _prams.onReceive,
    onResume = _prams.onResume || _prams.onReceive,
    pnOptions = _prams.pnOptions,
    extraOptions = _prams.extraOptions || {};

  for (var key in extraOptions) {
    that[key] = extraOptions[key];
  }

  function deviceTokenSuccess(e) {
    if (ANDROID) {
      Ti.API.debug('[TiPush] Device Token:', e.registrationId);
      token = e.registrationId;
    } else if (IOS) {
      Ti.API.debug('[TiPush] Device Token:', e.deviceToken);
      token = e.deviceToken;
    }
    that.token = token;

    var uploadParams = {};

    for (var key in that) {
			if (['backendUrl', 'getToken', 'registerDevice'].indexOf(key) === -1) {
        uploadParams[key] = that[key];
      }
    }

    var xhr = Ti.Network.createHTTPClient({
      onload: function() {
        Ti.API.debug("[TiPush] Token sent to our backend");
      },
      onerror: function() {
        Ti.API.error("[TiPush] Can't send tokend to our backend");
      }
    });
    xhr.open("POST", that.backendUrl);
    xhr.send(uploadParams);
  }

  function deviceTokenError(e) {
    Ti.API.error('[TiPush] Token Error:', e.error);
  }

  function receivePush(e) {
    Ti.API.debug("[TiPush] onReceive Push callback =", JSON.stringify(e));

    if (IOS) {
      // Reset badge
      Titanium.UI.iPhone.appBadge = null;
    }

    onReceive(e.data);
    Ti.API.debug("[TiPush] Push notification received: Module", JSON.stringify(e.data));
  }

  if (ANDROID) {

    GCM.registerPush({
      senderId: pnOptions.senderId,
      notificationSettings: pnOptions.notificationSettings,
      success: deviceTokenSuccess,
      error: deviceTokenError,
      callback: receivePush
    });

    /* When the app is started */
    var lastData = GCM.getLastData();
    if (lastData) {
      onStart({
        data: lastData
      });
      GCM.clearLastData();
    }

    /* And when the app is resumed */
    Ti.Android.currentActivity.addEventListener("resume", function() {
      var lastData = GCM.getLastData();
      if (lastData) {
        onResume({
          data: lastData
        });
        GCM.clearLastData();
      }
    });

  } else if (IOS) {
    // Check if the device is running iOS 8 or later
    if (parseInt(Ti.Platform.version.split(".")[0], 10) >= 8) {
      function registerForPush() {
        Ti.Network.registerForPushNotifications({
          success: deviceTokenSuccess,
          error: deviceTokenError,
          callback: receivePush
        });
        // Remove event listener once registered for push notifications
        Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
      }

      // Wait for user settings to be registered before registering for push notifications
      Ti.App.iOS.addEventListener('usernotificationsettings', registerForPush);

      // Register notification types to use
      Ti.App.iOS.registerUserNotificationSettings({
        types: pnOptions.types,
        categories: pnOptions.categories
      });

    } else {
      // For iOS 7 and earlier
      Ti.Network.registerForPushNotifications({
        // Specifies which notifications to receive
        types: pnOptions.types,
        success: deviceTokenSuccess,
        error: deviceTokenError,
        callback: receivePush
      });
    }

  } else {
    Ti.API.warn("[TiPush] Push notification not implemented yet into TiPushNotification for", Ti.Platform.osname);
  }
};

TiPush.prototype.getToken = function() {
  return this.token;
};

exports.init = function(param) {
  return new TiPush(param);
};
<commit_msg>repair iOS check<commit_after>/**
 * Yes you can use it with your self-hosted server or any other cloud services
 * like Parse.com or Appcelerator cloud.
 *
 * @auther Hazem Khaled <hazem.khaled@gmail.com>
 */
var ANDROID = Ti.Platform.name === 'android',
  IOS = Ti.Platform.name === 'iPhone OS' || Ti.Platform.name === 'iOS';

if (ANDROID) {
  var GCM = require("nl.vanvianen.android.gcm");
}

function TiPush(e) {
  this.backendUrl = e.backendUrl;
  this.token = '';
  this.os = (ANDROID) ? 'Android' : 'iOS';
}

TiPush.prototype.registerDevice = function(_prams) {
  var that = this,
    token = '',
    onReceive = _prams.onReceive,
    onStart = _prams.onStart || _prams.onReceive,
    onResume = _prams.onResume || _prams.onReceive,
    pnOptions = _prams.pnOptions,
    extraOptions = _prams.extraOptions || {};

  for (var key in extraOptions) {
    that[key] = extraOptions[key];
  }

  function deviceTokenSuccess(e) {
    if (ANDROID) {
      Ti.API.debug('[TiPush] Device Token:', e.registrationId);
      token = e.registrationId;
    } else if (IOS) {
      Ti.API.debug('[TiPush] Device Token:', e.deviceToken);
      token = e.deviceToken;
    }
    that.token = token;

    var uploadParams = {};

    for (var key in that) {
			if (['backendUrl', 'getToken', 'registerDevice'].indexOf(key) === -1) {
        uploadParams[key] = that[key];
      }
    }

    var xhr = Ti.Network.createHTTPClient({
      onload: function() {
        Ti.API.debug("[TiPush] Token sent to our backend");
      },
      onerror: function() {
        Ti.API.error("[TiPush] Can't send tokend to our backend");
      }
    });
    xhr.open("POST", that.backendUrl);
    xhr.send(uploadParams);
  }

  function deviceTokenError(e) {
    Ti.API.error('[TiPush] Token Error:', e.error);
  }

  function receivePush(e) {
    Ti.API.debug("[TiPush] onReceive Push callback =", JSON.stringify(e));

    if (IOS) {
      // Reset badge
      Titanium.UI.iPhone.appBadge = null;
    }

    onReceive(e.data);
    Ti.API.debug("[TiPush] Push notification received: Module", JSON.stringify(e.data));
  }

  if (ANDROID) {

    GCM.registerPush({
      senderId: pnOptions.senderId,
      notificationSettings: pnOptions.notificationSettings,
      success: deviceTokenSuccess,
      error: deviceTokenError,
      callback: receivePush
    });

    /* When the app is started */
    var lastData = GCM.getLastData();
    if (lastData) {
      onStart({
        data: lastData
      });
      GCM.clearLastData();
    }

    /* And when the app is resumed */
    Ti.Android.currentActivity.addEventListener("resume", function() {
      var lastData = GCM.getLastData();
      if (lastData) {
        onResume({
          data: lastData
        });
        GCM.clearLastData();
      }
    });

  } else if (IOS) {
    // Check if the device is running iOS 8 or later
    if (parseInt(Ti.Platform.version.split(".")[0], 10) >= 8) {
      function registerForPush() {
        Ti.Network.registerForPushNotifications({
          success: deviceTokenSuccess,
          error: deviceTokenError,
          callback: receivePush
        });
        // Remove event listener once registered for push notifications
        Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
      }

      // Wait for user settings to be registered before registering for push notifications
      Ti.App.iOS.addEventListener('usernotificationsettings', registerForPush);

      // Register notification types to use
      Ti.App.iOS.registerUserNotificationSettings({
        types: pnOptions.types,
        categories: pnOptions.categories
      });

    } else {
      // For iOS 7 and earlier
      Ti.Network.registerForPushNotifications({
        // Specifies which notifications to receive
        types: pnOptions.types,
        success: deviceTokenSuccess,
        error: deviceTokenError,
        callback: receivePush
      });
    }

  } else {
    Ti.API.warn("[TiPush] Push notification not implemented yet into TiPushNotification for", Ti.Platform.osname);
  }
};

TiPush.prototype.getToken = function() {
  return this.token;
};

exports.init = function(param) {
  return new TiPush(param);
};
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import R from 'ramda';

import {
  NAVIGATE,
  GOT_USER,
  EDIT_USER,
  CHANGE_LANGUAGE,
  RESPONSE_LINKTYPES,
  RESPONSE_COUNTRIES,
  REQUEST_ADD_USERPROFILEIMAGE,
  REQUEST_ADD_USERTEASERIMAGE,
  OPEN_STAGENAME_MODAL,
  CLOSE_STAGENAME_MODAL,
  OPEN_PASSWORD_MODAL,
  CLOSE_PASSWORD_MODAL,
  REQUEST_USER_MAKEABOUTPRIMARY,

  EDIT_EVENT,
  REQUEST_DELETE_EVENT,
  REQUEST_EDIT_EVENT,
  REQUEST_ADD_EVENT,
  REQUEST_ADD_EVENTIMAGE,
  REQUEST_SUGGEST_EVENT_PERFORMANCE,
  RESPONSE_SUGGEST_EVENT_PERFORMANCE,
  REQUEST_SUGGEST_EVENT_ORGANIZER,
  RESPONSE_SUGGEST_EVENT_ORGANIZER,
  REQUEST_SUGGEST_EVENT_ORGANIZINGCREW,
  RESPONSE_SUGGEST_EVENT_ORGANIZINGCREW,

  REQUEST_SUGGEST_CREWMEMBER,
  RESPONSE_SUGGEST_CREWMEMBER,
  REQUEST_ADD_CREWIMAGE,
  ADD_CREWMEMBER,
  REQUEST_DELETE_CREWMEMBER,
  REQUEST_CREW_MAKEABOUTPRIMARY,

  REQUEST_ADD_PERFORMANCEIMAGE,
  REQUEST_SUGGEST_PERFORMANCE_CREW,
  RESPONSE_SUGGEST_PERFORMANCE_CREW,
  REQUEST_SUGGEST_PERFORMANCE_PERFORMER,
  RESPONSE_SUGGEST_PERFORMANCE_PERFORMER
} from './actions';

const initialValues = {
  active: window.location.pathname,
  events: [],
  performances: [],
  crews: []
};
const event = (state = {}, action) => {
  switch (action.type) {
    case EDIT_EVENT:
      if (state._id !== action.json._id) {
        return state;
      }
      return Object.assign({}, state, action.json);
    case REQUEST_ADD_EVENT:
      return Object.assign({}, state, {
        ajaxInProgress: true
      });
    case REQUEST_DELETE_EVENT:
      if (state._id !== action.id) {
        return state;
      }
      return Object.assign({}, state, {
        ajaxInProgress: true
      });
    case REQUEST_ADD_EVENTIMAGE:
      if (state._id !== action.payload.eventId) {
        return state;
      }
      return Object.assign({}, state, {
        imageUploadInProgress: true
      });
    default:
      return state;
  }
};

const crew = (state = {}, action) => {
  switch (action.type) {
    case ADD_CREWMEMBER:
      if (state._id !== action.payload.crewId) {
        return state;
      }
      return Object.assign({}, state, {
        members: R.append(action.payload.member, state.members)
      });
    case REQUEST_ADD_CREWIMAGE:
      if (state._id !== action.payload.crewId) {
        return state;
      }
      return Object.assign({}, state, {
        imageUploadInProgress: true
      });
    case REQUEST_DELETE_CREWMEMBER:
      if (state._id !== action.payload.crewId) {
        return state;
      }
      return Object.assign({}, state, {
        members: state.members.map((m) => {
          if (m._id === action.payload.memberId) {
            return Object.assign({}, m, {
              deletionInProgress: true
            });
          } else {
            return m;
          }
        })
      });
    case REQUEST_CREW_MAKEABOUTPRIMARY:
      return state;
    default:
      console.log("crew default, returns state");
      return state;
  }
};

const performance = (state = {}, action) => {
  switch (action.type) {
    case REQUEST_ADD_PERFORMANCEIMAGE:
      if (state._id !== action.payload.performanceId) {
        return state;
      }
      return Object.assign({}, state, {
        imageUploadInProgress: true
      });
    default:
      return state;
  }
};

// EVENT.REQUEST_ADD
// CREW.REQUEST_SUGGEST_MEMBER
const user = (state = initialValues, action) => {
  switch (action.type) {
    case NAVIGATE:
      return Object.assign({}, state, {
        active: action.active
      });
    case GOT_USER:
      return Object.assign({}, state, action.json);
    case EDIT_USER:
      return state;
    case REQUEST_ADD_USERPROFILEIMAGE:
      return Object.assign({}, state, {
        profileImageUploadInProgress: true
      });
    case REQUEST_ADD_USERTEASERIMAGE:
      return Object.assign({}, state, {
        teaserImageUploadInProgress: true
      });
    case EDIT_EVENT:
      return state; // FIXME?!
    case REQUEST_ADD_EVENT:
      return Object.assign({}, state, event(state, action));
    case REQUEST_EDIT_EVENT:
    case REQUEST_DELETE_EVENT:
      return Object.assign({}, state, {
        events: state.events.map((e) => {
          return event(e, action);
        })
      });
    case RESPONSE_SUGGEST_CREWMEMBER:
      return Object.assign({}, state, {
        _memberSuggestions: action.suggestions,
        _memberSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_CREWMEMBER:
      return Object.assign({}, state, {
        _memberSuggestionInProgress: true
      });
    case REQUEST_SUGGEST_PERFORMANCE_CREW:
      return Object.assign({}, state, {
        _crewSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_PERFORMANCE_CREW:
      return Object.assign({}, state, {
        _crewSuggestions: action.suggestions,
        _crewSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_PERFORMANCE_PERFORMER:
      return Object.assign({}, state, {
        _performerSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_PERFORMANCE_PERFORMER:
      return Object.assign({}, state, {
        _performerSuggestions: action.suggestions,
        _performerSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_EVENT_PERFORMANCE:
      return Object.assign({}, state, {
        _performanceSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_EVENT_PERFORMANCE:
      return Object.assign({}, state, {
        _performanceSuggestions: action.suggestions,
        _performanceSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_EVENT_ORGANIZER:
      return Object.assign({}, state, {
        _organizerSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_EVENT_ORGANIZER:
      return Object.assign({}, state, {
        _organizerSuggestions: action.suggestions,
        _organizerSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_EVENT_ORGANIZINGCREW:
      return Object.assign({}, state, {
        _organizingCrewSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_EVENT_ORGANIZINGCREW:
      return Object.assign({}, state, {
        _organizingCrewSuggestions: action.suggestions,
        _organizingCrewSuggestionInProgress: false
      });
    case REQUEST_ADD_CREWIMAGE:
    case REQUEST_DELETE_CREWMEMBER:
    case ADD_CREWMEMBER:
    case REQUEST_CREW_MAKEABOUTPRIMARY:
      return Object.assign({}, state, {
        crews: state.crews.map((c) => {
          return crew(c, action);
        })
      });

    case REQUEST_ADD_CREWIMAGE:
      return Object.assign({}, state, {
        performances: state.performances.map((c) => {
          return performance(c, action);
        })
      });

    case OPEN_STAGENAME_MODAL:
      return Object.assign({}, state, {
        _stagenameModalActive: true
      });
    case CLOSE_STAGENAME_MODAL:
      return Object.assign({}, state, {
        _stagenameModalActive: false
      });
    case OPEN_PASSWORD_MODAL:
      return Object.assign({}, state, {
        _passwordModalActive: true
      });
    case CLOSE_PASSWORD_MODAL:
      return Object.assign({}, state, {
        _passwordModalActive: false
      });
    case CHANGE_LANGUAGE:
      return Object.assign({}, state, {
        settings: Object.assign({}, state.settings, {
          language: action.payload.language
        })
      });
    case RESPONSE_LINKTYPES:
      return Object.assign({}, state, {
        _linktypes: action.payload.linktypes
      });
    case RESPONSE_COUNTRIES:
      return Object.assign({}, state, {
        _countries: action.payload.countries
      });
    case REQUEST_USER_MAKEABOUTPRIMARY:
      console.log("REQUEST_USER_MAKEABOUTPRIMARY state._id " + state._id);
      return state;
    default:
      console.log("user default, returns state");
      return state;
  }
};

const reducer = combineReducers({
  user,
  form: formReducer
});

export default reducer;
<commit_msg>redux<commit_after>import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import R from 'ramda';

import {
  NAVIGATE,
  GOT_USER,
  EDIT_USER,
  CHANGE_LANGUAGE,
  RESPONSE_LINKTYPES,
  RESPONSE_COUNTRIES,
  REQUEST_ADD_USERPROFILEIMAGE,
  REQUEST_ADD_USERTEASERIMAGE,
  OPEN_STAGENAME_MODAL,
  CLOSE_STAGENAME_MODAL,
  OPEN_PASSWORD_MODAL,
  CLOSE_PASSWORD_MODAL,
  REQUEST_USER_MAKEABOUTPRIMARY,

  EDIT_EVENT,
  REQUEST_DELETE_EVENT,
  REQUEST_EDIT_EVENT,
  REQUEST_ADD_EVENT,
  REQUEST_ADD_EVENTIMAGE,
  REQUEST_SUGGEST_EVENT_PERFORMANCE,
  RESPONSE_SUGGEST_EVENT_PERFORMANCE,
  REQUEST_SUGGEST_EVENT_ORGANIZER,
  RESPONSE_SUGGEST_EVENT_ORGANIZER,
  REQUEST_SUGGEST_EVENT_ORGANIZINGCREW,
  RESPONSE_SUGGEST_EVENT_ORGANIZINGCREW,

  REQUEST_SUGGEST_CREWMEMBER,
  RESPONSE_SUGGEST_CREWMEMBER,
  REQUEST_ADD_CREWIMAGE,
  ADD_CREWMEMBER,
  REQUEST_DELETE_CREWMEMBER,
  REQUEST_CREW_MAKEABOUTPRIMARY,

  REQUEST_ADD_PERFORMANCEIMAGE,
  REQUEST_SUGGEST_PERFORMANCE_CREW,
  RESPONSE_SUGGEST_PERFORMANCE_CREW,
  REQUEST_SUGGEST_PERFORMANCE_PERFORMER,
  RESPONSE_SUGGEST_PERFORMANCE_PERFORMER
} from './actions';

const initialValues = {
  active: window.location.pathname,
  events: [],
  performances: [],
  crews: []
};
const event = (state = {}, action) => {
  switch (action.type) {
    case EDIT_EVENT:
      if (state._id !== action.json._id) {
        return state;
      }
      return Object.assign({}, state, action.json);
    case REQUEST_ADD_EVENT:
      return Object.assign({}, state, {
        ajaxInProgress: true
      });
    case REQUEST_DELETE_EVENT:
      if (state._id !== action.id) {
        return state;
      }
      return Object.assign({}, state, {
        ajaxInProgress: true
      });
    case REQUEST_ADD_EVENTIMAGE:
      if (state._id !== action.payload.eventId) {
        return state;
      }
      return Object.assign({}, state, {
        imageUploadInProgress: true
      });
    default:
      return state;
  }
};

const crew = (state = {}, action) => {
  switch (action.type) {
    case ADD_CREWMEMBER:
      if (state._id !== action.payload.crewId) {
        return state;
      }
      return Object.assign({}, state, {
        members: R.append(action.payload.member, state.members)
      });
    case REQUEST_ADD_CREWIMAGE:
      if (state._id !== action.payload.crewId) {
        return state;
      }
      return Object.assign({}, state, {
        imageUploadInProgress: true
      });
    case REQUEST_DELETE_CREWMEMBER:
      if (state._id !== action.payload.crewId) {
        return state;
      }
      return Object.assign({}, state, {
        members: state.members.map((m) => {
          if (m._id === action.payload.memberId) {
            return Object.assign({}, m, {
              deletionInProgress: true
            });
          } else {
            return m;
          }
        })
      });
    case REQUEST_CREW_MAKEABOUTPRIMARY:
      return state;
    default:
      console.log("crew action not defined: " + action.type);
      return state;
  }
};

const performance = (state = {}, action) => {
  switch (action.type) {
    case REQUEST_ADD_PERFORMANCEIMAGE:
      if (state._id !== action.payload.performanceId) {
        return state;
      }
      return Object.assign({}, state, {
        imageUploadInProgress: true
      });
    default:
      return state;
  }
};

// EVENT.REQUEST_ADD
// CREW.REQUEST_SUGGEST_MEMBER
const user = (state = initialValues, action) => {
  switch (action.type) {
    case NAVIGATE:
      return Object.assign({}, state, {
        active: action.active
      });
    case GOT_USER:
      return Object.assign({}, state, action.json);
    case EDIT_USER:
      return state;
    case REQUEST_ADD_USERPROFILEIMAGE:
      return Object.assign({}, state, {
        profileImageUploadInProgress: true
      });
    case REQUEST_ADD_USERTEASERIMAGE:
      return Object.assign({}, state, {
        teaserImageUploadInProgress: true
      });
    case EDIT_EVENT:
      return state; // FIXME?!
    case REQUEST_ADD_EVENT:
      return Object.assign({}, state, event(state, action));
    case REQUEST_EDIT_EVENT:
    case REQUEST_DELETE_EVENT:
      return Object.assign({}, state, {
        events: state.events.map((e) => {
          return event(e, action);
        })
      });
    case RESPONSE_SUGGEST_CREWMEMBER:
      return Object.assign({}, state, {
        _memberSuggestions: action.suggestions,
        _memberSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_CREWMEMBER:
      return Object.assign({}, state, {
        _memberSuggestionInProgress: true
      });
    case REQUEST_SUGGEST_PERFORMANCE_CREW:
      return Object.assign({}, state, {
        _crewSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_PERFORMANCE_CREW:
      return Object.assign({}, state, {
        _crewSuggestions: action.suggestions,
        _crewSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_PERFORMANCE_PERFORMER:
      return Object.assign({}, state, {
        _performerSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_PERFORMANCE_PERFORMER:
      return Object.assign({}, state, {
        _performerSuggestions: action.suggestions,
        _performerSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_EVENT_PERFORMANCE:
      return Object.assign({}, state, {
        _performanceSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_EVENT_PERFORMANCE:
      return Object.assign({}, state, {
        _performanceSuggestions: action.suggestions,
        _performanceSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_EVENT_ORGANIZER:
      return Object.assign({}, state, {
        _organizerSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_EVENT_ORGANIZER:
      return Object.assign({}, state, {
        _organizerSuggestions: action.suggestions,
        _organizerSuggestionInProgress: false
      });
    case REQUEST_SUGGEST_EVENT_ORGANIZINGCREW:
      return Object.assign({}, state, {
        _organizingCrewSuggestionInProgress: true
      });
    case RESPONSE_SUGGEST_EVENT_ORGANIZINGCREW:
      return Object.assign({}, state, {
        _organizingCrewSuggestions: action.suggestions,
        _organizingCrewSuggestionInProgress: false
      });
    case REQUEST_ADD_CREWIMAGE:
    case REQUEST_DELETE_CREWMEMBER:
    case ADD_CREWMEMBER:
    case REQUEST_CREW_MAKEABOUTPRIMARY:
      return Object.assign({}, state, {
        crews: state.crews.map((c) => {
          return crew(c, action);
        })
      });

    case REQUEST_ADD_CREWIMAGE:
      return Object.assign({}, state, {
        performances: state.performances.map((c) => {
          return performance(c, action);
        })
      });

    case OPEN_STAGENAME_MODAL:
      return Object.assign({}, state, {
        _stagenameModalActive: true
      });
    case CLOSE_STAGENAME_MODAL:
      return Object.assign({}, state, {
        _stagenameModalActive: false
      });
    case OPEN_PASSWORD_MODAL:
      return Object.assign({}, state, {
        _passwordModalActive: true
      });
    case CLOSE_PASSWORD_MODAL:
      return Object.assign({}, state, {
        _passwordModalActive: false
      });
    case CHANGE_LANGUAGE:
      return Object.assign({}, state, {
        settings: Object.assign({}, state.settings, {
          language: action.payload.language
        })
      });
    case RESPONSE_LINKTYPES:
      return Object.assign({}, state, {
        _linktypes: action.payload.linktypes
      });
    case RESPONSE_COUNTRIES:
      return Object.assign({}, state, {
        _countries: action.payload.countries
      });
    case REQUEST_USER_MAKEABOUTPRIMARY:
      console.log("REQUEST_USER_MAKEABOUTPRIMARY state._id " + state._id);
      return state;
    default:
      console.log("user action not defined: " + action.type);
      return state;
  }
};

const reducer = combineReducers({
  user,
  form: formReducer
});

export default reducer;
<|endoftext|>


<commit_before>'use strict';

// Dependencies
const Aldous = require('aldous')
const fs = require('./fs')
const config = require('./config')
const path = require('path')
const readdir = require('recursive-readdir')

// Setup
let build = Aldous(config)
let dest = config.paths.destination
let src = config.paths.source

// Do ya thing!
fs.readSourceDir(src)
  .then(function(input) { return build.run(input) })
  .then(function cb(response) { return fs.writeOutput(dest, response[0]) })
  .then(function cb() { console.log('Done.') })
  .catch(console.error)
<commit_msg>Remove unnused dependencies<commit_after>'use strict';

// Dependencies
const Aldous = require('aldous')
const fs = require('./fs')
const config = require('./config')

// Setup
let build = Aldous(config)
let dest = config.paths.destination
let src = config.paths.source

// Do ya thing!
fs.readSourceDir(src)
  .then(function(input) { return build.run(input) })
  .then(function cb(response) { return fs.writeOutput(dest, response[0]) })
  .then(function cb() { console.log('Done.') })
  .catch(console.error)
<|endoftext|>