(function (native_require, this_module) {

// based on TJ Holowaychuk's commonjs require binding

function require(p, root) {
  // third-party module?  use native require
  if ('.' != p[0] && '/' != p[0])
    return native_require(p);

  root = root || 'root';

  var path = require.resolve(p);

  // if it's a non-registered json file, it
  // must be at the root of the project
  if (!path && /\.json$/i.test(p))
    return native_require('./' + require.basename(p));

  var module = require.cache[path];

  if (!module) {
    try {
      return native_require(p);
    } catch (err) {
      throw new Error('failed to require "' + p + '" from ' + root +'\n' + err.message + '\n' + err.stack);
    }
  }

  if (!module.exports) {
    module.exports = {};
    module.call(module.exports, module, module.exports,
      require.relative(path));
  }

  return module.exports;
}

// same as node's `require`
require.cache = {};

// node's native `path.basename`
require.basename = native_require('path').basename;

require.resolve = function (path) {
  // GH-12
  if ('.' != path[0]) return native_require.resolve(path);

  var pathWithSlash = path.slice(-1) === '/' ? path : path + '/';
  var paths = [
    path,
    path + '.js',
    pathWithSlash + 'index.js',
    path + '.json',
    pathWithSlash + 'index.json'
  ];

  for (var i = 0, p; p = paths[i]; i++) {
    if (require.cache[p]) return p;
  }
};

require.register = function (path, fn) {
  require.cache[path] = fn;
};

require.relative = function (parent) {
  function relative(p) {
    if ('.' != p[0]) return require(p);

    var path = parent.split('/');
    var segs = p.split('/');
    path.pop();

    for (var i = 0, len = segs.length; i < len; i += 1) {
      var seg = segs[i];
      if ('..' == seg) {
        path.pop();
      } else if ('.' != seg) {
        path.push(seg);
      }
    }

    return require(path.join('/'), parent);
  }

  relative.resolve = require.resolve;
  relative.cache = require.cache;
  return relative;
};

require.register("./index.js",function (module, exports, require) {process.env.UV_THREADPOOL_SIZE = 128
require("coffee-script/register")
require && require.extensions && delete require.extensions[".litcoffee"]
require && require.extensions && delete require.extensions[".coffee.md"]
require("./lib/cypress").start(process.argv)
});
require.register("./lib/api.js",function (module, exports, require) {(function() {
  var Promise, Routes, _, errors, formatResponseBody, getos, os, osVersion, pkg, provider, request, rp;

  _ = require("lodash");

  os = require("os");

  getos = require("getos");

  request = require("request-promise");

  errors = require("request-promise/errors");

  Promise = require("bluebird");

  Routes = require("./util/routes");

  pkg = require("../package.json");

  provider = require("./util/provider");

  getos = Promise.promisify(getos);

  rp = request.defaults(function(params, callback) {
    var headers, method;
    if (params == null) {
      params = {};
    }
    headers = params.headers != null ? params.headers : params.headers = {};
    _.defaults(headers, {
      "x-platform": os.platform(),
      "x-cypress-version": pkg.version
    });
    method = params.method.toLowerCase();
    return request[method](params, callback);
  });

  formatResponseBody = function(err) {
    var body;
    if (_.isObject(err.error)) {
      body = JSON.stringify(err.error, null, 2);
      err.message = [err.statusCode, body].join("\n\n");
    }
    throw err;
  };

  osVersion = function(platform) {
    return Promise["try"](function() {
      if (platform === "linux") {
        return getos().then(function(obj) {
          return [obj.dist, obj.release].join(" - ");
        })["catch"](function(err) {
          return os.release();
        });
      } else {
        return os.release();
      }
    });
  };

  module.exports = {
    ping: function() {
      return rp.get(Routes.ping());
    },
    createBuild: function(options) {
      var ref;
      if (options == null) {
        options = {};
      }
      return rp.post({
        url: Routes.builds(),
        json: true,
        timeout: (ref = options.timeout) != null ? ref : 10000,
        headers: {
          "x-route-version": "2"
        },
        body: {
          projectId: options.projectId,
          projectToken: options.projectToken,
          commitSha: options.commitSha,
          commitBranch: options.commitBranch,
          commitAuthorName: options.commitAuthorName,
          commitAuthorEmail: options.commitAuthorEmail,
          commitMessage: options.commitMessage,
          ciProvider: provider.get()
        }
      }).promise().get("buildId")["catch"](errors.StatusCodeError, formatResponseBody);
    },
    createInstance: function(options) {
      var platform;
      if (options == null) {
        options = {};
      }
      platform = os.platform();
      return osVersion(platform).then(function(v) {
        var ref;
        return rp.post({
          url: Routes.instances(options.buildId),
          json: true,
          timeout: (ref = options.timeout) != null ? ref : 10000,
          headers: {
            "x-route-version": "3"
          },
          body: {
            spec: options.spec,
            browserName: "Electron",
            browserVersion: process.versions.chrome,
            osName: platform,
            osVersion: v
          }
        }).promise().get("instanceId")["catch"](errors.StatusCodeError, formatResponseBody);
      });
    },
    updateInstance: function(options) {
      var body, ref;
      if (options == null) {
        options = {};
      }
      body = _.pick(options, ["tests", "duration", "passes", "failures", "pending", "error", "video", "screenshots", "failingTests", "cypressConfig"]);
      return rp.put({
        url: Routes.instance(options.instanceId),
        json: true,
        timeout: (ref = options.timeout) != null ? ref : 10000,
        body: _.extend(body, {
          ciProvider: provider.get()
        })
      })["catch"](errors.StatusCodeError, formatResponseBody);
    },
    createRaygunException: function(body, session, timeout) {
      if (timeout == null) {
        timeout = 3000;
      }
      return rp.post({
        url: Routes.exceptions(),
        json: true,
        body: body,
        headers: {
          "x-session": session
        }
      }).promise().timeout(timeout);
    },
    createSignin: function(code) {
      return rp.post({
        url: Routes.signin({
          code: code
        }),
        json: true,
        headers: {
          "x-route-version": "2"
        }
      })["catch"](errors.StatusCodeError, function(err) {
        err.message = err.message.split(" - ").slice(1).join("");
        throw err;
      });
    },
    createSignout: function(session) {
      return rp.post({
        url: Routes.signout(),
        json: true,
        headers: {
          "x-session": session
        }
      })["catch"](function(err) {
        if (err.statusCode === 401) {
          return;
        }
        throw err;
      });
    },
    createProject: function(projectName, session) {
      return rp.post({
        url: Routes.projects(),
        json: true,
        headers: {
          "x-session": session
        },
        body: {
          "x-project-name": projectName
        }
      }).promise().get("uuid");
    },
    updateProject: function(projectId, type, projectName, session) {
      return rp.get({
        url: Routes.project(projectId),
        json: true,
        headers: {
          "x-session": session
        },
        body: {
          "x-type": type,
          "x-platform": os.platform(),
          "x-version": pkg.version,
          "x-project-name": projectName
        }
      });
    },
    sendUsage: function(numRuns, exampleSpec, allSpecs, projectName, session) {
      return rp.post({
        url: Routes.usage(),
        json: true,
        headers: {
          "x-session": session
        },
        body: {
          "x-runs": numRuns,
          "x-example": exampleSpec,
          "x-all": allSpecs,
          "x-project-name": projectName
        }
      });
    },
    getLoginUrl: function() {
      return rp.get({
        url: Routes.auth(),
        json: true
      }).promise().get("url");
    },
    _projectToken: function(method, projectId, session) {
      return rp({
        method: method,
        url: Routes.projectToken(projectId),
        json: true,
        headers: {
          "x-session": session,
          "x-route-version": "2"
        }
      }).promise().get("apiToken");
    },
    getProjectToken: function(projectId, session) {
      return this._projectToken("get", projectId, session);
    },
    updateProjectToken: function(projectId, session) {
      return this._projectToken("put", projectId, session);
    }
  };

}).call(this);

});
require.register("./lib/automation.js",function (module, exports, require) {(function() {
  var COOKIE_PROPERTIES, Promise, _, automation, charAfterColonRe, middlewareMesssages, needsMiddleware, normalizeCookieProps, normalizeCookies, screenshots,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  _ = require("lodash");

  Promise = require("bluebird");

  screenshots = require("./screenshots");

  middlewareMesssages = "take:screenshot get:cookies get:cookie set:cookie clear:cookie clear:cookies".split(" ");

  charAfterColonRe = /:(.)/;

  COOKIE_PROPERTIES = "url name value path domain secure httpOnly expiry".split(" ");

  needsMiddleware = function(message) {
    return indexOf.call(middlewareMesssages, message) >= 0;
  };

  normalizeCookies = function(cookies) {
    return _.map(cookies, normalizeCookieProps);
  };

  normalizeCookieProps = function(data) {
    var cookie;
    if (!data) {
      return data;
    }
    cookie = _.chain(data, COOKIE_PROPERTIES).pick(COOKIE_PROPERTIES).omitBy(_.isUndefined).value();
    switch (false) {
      case data.expiry == null:
        delete cookie.expiry;
        cookie.expirationDate = data.expiry;
        break;
      case data.expirationDate == null:
        delete cookie.expirationDate;
        delete cookie.url;
        cookie.expiry = data.expirationDate;
    }
    return cookie;
  };

  automation = function(namespace, socketIoCookie, screenshotsFolder) {
    var isCypressNamespaced;
    isCypressNamespaced = function(cookie) {
      var name;
      if (!(name = cookie != null ? cookie.name : void 0)) {
        return cookie;
      }
      return name.startsWith(namespace) || name === socketIoCookie;
    };
    return {
      getCookies: function(message, data, automate) {
        return automate(message, data).then(normalizeCookies).then(function(cookies) {
          return _.reject(cookies, isCypressNamespaced);
        });
      },
      getCookie: function(message, data, automate) {
        return automate(message, data).then(function(cookie) {
          if (isCypressNamespaced(cookie)) {
            throw new Error("Sorry, you cannot get a Cypress namespaced cookie.");
          } else {
            return cookie;
          }
        }).then(normalizeCookieProps);
      },
      setCookie: function(message, data, automate) {
        var cookie;
        if (isCypressNamespaced(data)) {
          throw new Error("Sorry, you cannot set a Cypress namespaced cookie.");
        } else {
          cookie = normalizeCookieProps(data);
          return automate(message, cookie).then(normalizeCookieProps);
        }
      },
      clearCookie: function(message, data, automate) {
        if (isCypressNamespaced(data)) {
          throw new Error("Sorry, you cannot clear a Cypress namespaced cookie.");
        } else {
          return automate(message, data).then(normalizeCookieProps);
        }
      },
      clearCookies: function(message, data, automate) {
        var clear, cookies;
        cookies = _.reject(normalizeCookies(data), isCypressNamespaced);
        clear = function(cookie) {
          return automate("clear:cookie", {
            name: cookie.name
          }).then(normalizeCookieProps);
        };
        return Promise.map(cookies, clear);
      },
      takeScreenshot: function(message, data, automate) {
        return automate(message, data).then(function(dataUrl) {
          return screenshots.take(data, dataUrl, screenshotsFolder);
        });
      },
      applyMiddleware: function(message, data, automate) {
        return Promise["try"]((function(_this) {
          return function() {
            var fn;
            fn = message.replace(charAfterColonRe, function(match, p1) {
              return p1.toUpperCase();
            });
            return _this[fn](message, data, automate);
          };
        })(this));
      },
      changeCookie: function(data, cb) {
        var c, msg;
        c = normalizeCookieProps(data.cookie);
        if (isCypressNamespaced(c)) {
          return;
        }
        msg = data.removed ? "Cookie Removed: '" + c.name + "=" + c.value + "'" : "Cookie Set: '" + c.name + "=" + c.value + "'";
        return cb({
          cookie: c,
          message: msg,
          removed: data.removed
        });
      },
      request: function(message, data, automate) {
        if (needsMiddleware(message)) {
          return this.applyMiddleware(message, data, automate);
        } else {
          return automate(message, data);
        }
      },
      pushMessage: function(message, data, cb) {
        switch (message) {
          case "change:cookie":
            return this.changeCookie(data, cb);
          default:
            throw new Error("Automation push message: '" + message + "' not recognized.");
        }
      }
    };
  };

  automation.normalizeCookieProps = normalizeCookieProps;

  automation.normalizeCookies = normalizeCookies;

  module.exports = automation;

}).call(this);

});
require.register("./lib/cache.js",function (module, exports, require) {(function() {
  var CACHE, Promise, _, api, appData, convertProjectsToArray, current, fs, logger, path, queue, renameSessionToken,
    slice = [].slice,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  _ = require("lodash");

  fs = require("fs-extra");

  path = require("path");

  Promise = require("bluebird");

  appData = require("./util/app_data");

  api = require("./api");

  logger = require("./logger");

  CACHE = appData.path("cache");

  fs = Promise.promisifyAll(fs);

  current = null;

  convertProjectsToArray = function(obj) {
    if (!_.isArray(obj.PROJECTS)) {
      obj.PROJECTS = _.chain(obj.PROJECTS).values().map("PATH").compact().value();
      return obj;
    }
  };

  renameSessionToken = function(obj) {
    var st;
    if (obj.USER && (st = obj.USER.session_token)) {
      delete obj.USER.session_token;
      obj.USER.sessionToken = st;
      return obj;
    }
  };

  queue = function(fn) {
    if (current) {
      return Promise.delay(20).then(function() {
        return queue(fn);
      });
    } else {
      current = true;
      return Promise["try"](fn)["finally"](function() {
        return current = null;
      });
    }
  };

  module.exports = {
    path: CACHE,
    ensureExists: function() {
      return fs.readJsonAsync(this.path).then((function(_this) {
        return function(json) {
          if (!json.USER) {
            json.USER = {};
          }
          if (!json.PROJECTS) {
            json.PROJECTS = [];
          }
          return _this.write(json);
        };
      })(this)).then((function(_this) {
        return function(json) {
          var changed;
          changed = _this._applyRewriteRules(json);
          if (_.isEqual(json, changed)) {
            return json;
          } else {
            return _this.write(changed);
          }
        };
      })(this))["return"](true)["catch"]((function(_this) {
        return function() {
          return _this.write(_this.defaults());
        };
      })(this));
    },
    exists: function() {
      return this.ensureExists()["return"](true)["catch"](false);
    },
    defaults: function() {
      return {
        USER: {},
        PROJECTS: []
      };
    },
    _applyRewriteRules: function(obj) {
      if (obj == null) {
        obj = {};
      }
      return _.reduce([convertProjectsToArray, renameSessionToken], function(memo, fn) {
        var ret;
        if (ret = fn(memo)) {
          return ret;
        } else {
          return memo;
        }
      }, _.cloneDeep(obj));
    },
    _read: function() {
      return this.ensureExists().then((function(_this) {
        return function() {
          return fs.readJsonAsync(_this.path);
        };
      })(this));
    },
    write: function(obj) {
      if (obj == null) {
        obj = {};
      }
      logger.info("writing to .cy cache", {
        cache: obj
      });
      return fs.outputJsonAsync(this.path, obj, {
        spaces: 2
      })["return"](obj);
    },
    _mergeOrWrite: function(contents, key, val) {
      switch (false) {
        case !_.isString(key):
          if (contents[key] == null) {
            contents[key] = {};
          }
          _.extend(contents[key], val);
          break;
        case !_.isObject(key):
          _.extend(contents, key);
      }
      return this.write(contents);
    },
    _set: function(key, val) {
      return this._read().then((function(_this) {
        return function(contents) {
          return _this._mergeOrWrite(contents, key, val);
        };
      })(this));
    },
    _get: function(key) {
      return this._read().then(function(contents) {
        return contents[key];
      });
    },
    _getProjects: function() {
      return this._get("PROJECTS");
    },
    _removeProjects: function(projects, paths) {
      projects = _.without.apply(_, [projects].concat(slice.call([].concat(paths))));
      return this._set({
        PROJECTS: projects
      });
    },
    read: function() {
      return queue((function(_this) {
        return function() {
          return _this._read();
        };
      })(this));
    },
    getProjectPaths: function() {
      return queue((function(_this) {
        return function() {
          return _this._getProjects().then(function(projects) {
            var pathsToRemove;
            pathsToRemove = Promise.reduce(projects, function(memo, path) {
              return fs.statAsync(path)["catch"](function() {
                return memo.push(path);
              })["return"](memo);
            }, []);
            return pathsToRemove.then(function(removedPaths) {
              return _this._removeProjects(projects, removedPaths);
            }).then(function() {
              return _this._getProjects();
            });
          });
        };
      })(this));
    },
    removeProject: function(path) {
      return queue((function(_this) {
        return function() {
          return _this._getProjects().then(function(projects) {
            return _this._removeProjects(projects, path);
          });
        };
      })(this));
    },
    insertProject: function(path) {
      return queue((function(_this) {
        return function() {
          return _this._getProjects().then(function(projects) {
            if (indexOf.call(projects, path) >= 0) {
              return projects;
            }
            projects.push(path);
            return _this._set("PROJECTS", projects);
          });
        };
      })(this));
    },
    getUser: function() {
      logger.info("getting user");
      return queue((function(_this) {
        return function() {
          return _this._get("USER");
        };
      })(this));
    },
    setUser: function(user) {
      logger.info("setting user", {
        user: user
      });
      return queue((function(_this) {
        return function() {
          return _this._set({
            USER: user
          });
        };
      })(this));
    },
    removeUser: function() {
      return queue((function(_this) {
        return function() {
          return _this._set({
            USER: {}
          });
        };
      })(this));
    },
    remove: function() {
      return fs.removeAsync(this.path);
    },
    removeSync: function() {
      return fs.removeSync(this.path);
    }
  };

}).call(this);

});
require.register("./lib/config.js",function (module, exports, require) {(function() {
  var Promise, _, coerce, configKeys, convertRelativeToAbsolutePaths, cypressEnvRe, dashesOrUnderscoresRe, defaults, errors, folders, isCypressEnvLike, path, scaffold, settings, str;

  _ = require("lodash");

  str = require("underscore.string");

  path = require("path");

  Promise = require("bluebird");

  coerce = require("./util/coerce");

  settings = require("./util/settings");

  errors = require("./errors");

  scaffold = require("./scaffold");

  cypressEnvRe = /^(cypress_)/i;

  dashesOrUnderscoresRe = /^(_-)+/;

  folders = "fileServerFolder videosFolder supportFolder fixturesFolder integrationFolder screenshotsFolder unitFolder supportFile".split(" ");

  configKeys = "port reporter reporterOptions baseUrl execTimeout defaultCommandTimeout pageLoadTimeout requestTimeout responseTimeout numTestsKeptInMemory screenshotOnHeadlessFailure waitForAnimations animationDistanceThreshold watchForFileChanges trashAssetsBeforeHeadlessRuns chromeWebSecurity videoRecording videoCompression viewportWidth viewportHeight supportFile fileServerFolder supportFolder fixturesFolder integrationFolder videosFolder screenshotsFolder environmentVariables hosts".split(" ");

  isCypressEnvLike = function(key) {
    return cypressEnvRe.test(key) && key !== "CYPRESS_ENV";
  };

  defaults = {
    port: null,
    hosts: null,
    morgan: true,
    baseUrl: null,
    socketId: null,
    isHeadless: false,
    reporter: "spec",
    reporterOptions: null,
    clientRoute: "/__/",
    xhrRoute: "/xhrs/",
    socketIoRoute: "/__socket.io",
    socketIoCookie: "__socket.io",
    reporterRoute: "/__cypress/reporter",
    ignoreTestFiles: "*.hot-update.js",
    defaultCommandTimeout: 4000,
    requestTimeout: 5000,
    responseTimeout: 30000,
    pageLoadTimeout: 60000,
    execTimeout: 60000,
    videoRecording: true,
    videoCompression: 32,
    chromeWebSecurity: true,
    waitForAnimations: true,
    animationDistanceThreshold: 5,
    numTestsKeptInMemory: 50,
    watchForFileChanges: true,
    screenshotOnHeadlessFailure: true,
    trashAssetsBeforeHeadlessRuns: true,
    autoOpen: false,
    viewportWidth: 1000,
    viewportHeight: 660,
    fileServerFolder: "",
    videosFolder: "cypress/videos",
    supportFile: "cypress/support",
    fixturesFolder: "cypress/fixtures",
    integrationFolder: "cypress/integration",
    screenshotsFolder: "cypress/screenshots",
    namespace: "__cypress",
    javascripts: []
  };

  convertRelativeToAbsolutePaths = function(projectRoot, obj, defaults) {
    if (defaults == null) {
      defaults = {};
    }
    return _.reduce(folders, function(memo, folder) {
      var val;
      val = obj[folder];
      if ((val != null) && val !== false) {
        memo[folder] = path.resolve(projectRoot, val);
      }
      return memo;
    }, {});
  };

  module.exports = {
    getConfigKeys: function() {
      return configKeys;
    },
    whitelist: function(obj) {
      if (obj == null) {
        obj = {};
      }
      return _.pick(obj, configKeys);
    },
    get: function(projectRoot, options) {
      if (options == null) {
        options = {};
      }
      return Promise.all([settings.read(projectRoot), settings.readEnv(projectRoot)]).spread((function(_this) {
        return function(settings, envFile) {
          return _this.set({
            projectName: _this.getNameFromRoot(projectRoot),
            projectRoot: projectRoot,
            config: settings,
            envFile: envFile,
            options: options
          });
        };
      })(this));
    },
    set: function(obj) {
      var config, envFile, options, projectName, projectRoot;
      if (obj == null) {
        obj = {};
      }
      projectRoot = obj.projectRoot, projectName = obj.projectName, config = obj.config, envFile = obj.envFile, options = obj.options;
      if (config == null) {
        config = {};
      }
      config.envFile = envFile;
      config.projectRoot = projectRoot;
      config.projectName = projectName;
      return this.mergeDefaults(config, options);
    },
    mergeDefaults: function(config, options) {
      var resolved, url;
      if (config == null) {
        config = {};
      }
      if (options == null) {
        options = {};
      }
      resolved = {};
      _.extend(config, _.pick(options, "morgan", "isHeadless", "socketId", "report", "browsers"));
      _.each(this.whitelist(options), function(val, key) {
        resolved[key] = "cli";
        config[key] = val;
      });
      if (url = config.baseUrl) {
        config.baseUrl = str.rtrim(url, "/");
      }
      _.defaults(config, defaults);
      config.environmentVariables = this.parseEnv(config, resolved);
      config.env = process.env["CYPRESS_ENV"];
      delete config.envFile;
      if (config.isHeadless) {
        config.watchForFileChanges = false;
        config.numTestsKeptInMemory = 0;
      }
      config = this.setResolvedConfigValues(config, defaults, resolved);
      if (config.port) {
        config = this.setUrls(config);
      }
      config = this.setAbsolutePaths(config, defaults);
      config = this.setParentTestsPaths(config);
      config = this.setScaffoldPaths(config);
      config = this.setSupportFileAndFolder(config);
      return config;
    },
    setResolvedConfigValues: function(config, defaults, resolved) {
      var obj;
      obj = _.clone(config);
      obj.resolved = this.resolveConfigValues(config, defaults, resolved);
      return obj;
    },
    resolveConfigValues: function(config, defaults, resolved) {
      if (resolved == null) {
        resolved = {};
      }
      return _.chain(config).pick(configKeys).mapValues(function(val, key) {
        var r, source;
        source = function(s) {
          return {
            value: val,
            from: s
          };
        };
        switch (false) {
          case !(r = resolved[key]):
            if (_.isObject(r)) {
              return r;
            } else {
              return source(r);
            }
            break;
          case !!_.isEqual(config[key], defaults[key]):
            return source("config");
          default:
            return source("default");
        }
      }).value();
    },
    setScaffoldPaths: function(obj) {
      var fileName;
      obj = _.clone(obj);
      fileName = scaffold.integrationExampleName();
      obj.integrationExampleFile = path.join(obj.integrationFolder, fileName);
      obj.integrationExampleName = fileName;
      return obj;
    },
    setSupportFileAndFolder: function(obj) {
      var err, sf;
      obj = _.clone(obj);
      if (sf = obj.supportFile) {
        try {
          obj.supportFile = require.resolve(sf);
        } catch (error) {
          err = error;
          if (sf !== path.resolve(obj.projectRoot, defaults.supportFile)) {
            errors["throw"]("SUPPORT_FILE_NOT_FOUND", path.resolve(obj.projectRoot, sf));
          } else {
            obj.supportFile = path.join(sf, "index.js");
          }
        }
        obj.supportFolder = path.dirname(obj.supportFile);
      }
      return obj;
    },
    setParentTestsPaths: function(obj) {
      var prd, ptfd, ref;
      obj = _.clone(obj);
      ptfd = obj.parentTestsFolder = path.dirname(obj.integrationFolder);
      prd = path.dirname((ref = obj.projectRoot) != null ? ref : "");
      obj.parentTestsFolderDisplay = path.relative(prd, ptfd);
      return obj;
    },
    setAbsolutePaths: function(obj, defaults) {
      var pr;
      obj = _.clone(obj);
      if (pr = obj.projectRoot) {
        _.extend(obj, convertRelativeToAbsolutePaths(pr, obj, defaults));
      }
      return obj;
    },
    setUrls: function(obj) {
      var rootUrl;
      obj = _.clone(obj);
      rootUrl = "http://localhost:" + obj.port;
      _.extend(obj, {
        clientUrlDisplay: rootUrl,
        clientUrl: rootUrl + obj.clientRoute,
        reporterUrl: rootUrl + obj.reporterRoute,
        xhrUrl: obj.namespace + obj.xhrRoute
      });
      return obj;
    },
    parseEnv: function(cfg, resolved) {
      var configFromEnv, envCLI, envCfg, envFile, envProc, envVars, matchesConfigKey, ref, ref1, ref2, ref3, resolveFrom;
      if (resolved == null) {
        resolved = {};
      }
      envVars = resolved.environmentVariables = {};
      resolveFrom = function(from, obj) {
        if (obj == null) {
          obj = {};
        }
        return _.each(obj, function(val, key) {
          return envVars[key] = {
            value: val,
            from: from
          };
        });
      };
      envCfg = (ref = cfg.env) != null ? ref : {};
      envFile = (ref1 = cfg.envFile) != null ? ref1 : {};
      envProc = (ref2 = this.getProcessEnvVars(process.env)) != null ? ref2 : {};
      envCLI = (ref3 = cfg.environmentVariables) != null ? ref3 : {};
      matchesConfigKey = function(key) {
        if (_.has(cfg, key)) {
          return key;
        }
        key = key.toLowerCase().replace(dashesOrUnderscoresRe, "");
        key = str.camelize(key);
        if (_.has(cfg, key)) {
          return key;
        }
      };
      configFromEnv = _.reduce(envProc, function(memo, val, key) {
        var cfgKey;
        if (cfgKey = matchesConfigKey(key)) {
          if (resolved[cfgKey] !== "cli") {
            cfg[cfgKey] = val;
            resolved[cfgKey] = {
              value: val,
              from: "env"
            };
          }
          memo.push(key);
        }
        return memo;
      }, []);
      envProc = _.omit(envProc, configFromEnv);
      resolveFrom("config", envCfg);
      resolveFrom("envFile", envFile);
      resolveFrom("env", envProc);
      resolveFrom("cli", envCLI);
      return _.extend(envCfg, envFile, envProc, envCLI);
    },
    getProcessEnvVars: function(obj) {
      var normalize;
      if (obj == null) {
        obj = {};
      }
      normalize = function(key) {
        return key.replace(cypressEnvRe, "");
      };
      return _.reduce(obj, function(memo, value, key) {
        if (isCypressEnvLike(key)) {
          memo[normalize(key)] = coerce(value);
        }
        return memo;
      }, {});
    },
    getNameFromRoot: function(root) {
      if (root == null) {
        root = "";
      }
      return path.basename(root);
    }
  };

}).call(this);

});
require.register("./lib/controllers/builds.js",function (module, exports, require) {(function() {
  var api, user;

  api = require("../api");

  user = require("../user");

  module.exports = {
    handle: function(req, res, config, next) {
      return user.get().then((function(_this) {
        return function(user) {
          return api.getBuilds(config.projectId, user != null ? user.sessionToken : void 0).on("error", next).pipe(res);
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/controllers/client.js",function (module, exports, require) {(function() {
  var clientSource, clientVersion, socketIo;

  socketIo = require("@cypress/core-socket");

  clientSource = socketIo.getClientSource();

  clientVersion = socketIo.getClientVersion();

  module.exports = {
    handle: function(req, res) {
      var etag;
      etag = req.get("if-none-match");
      if (etag && (etag === clientVersion)) {
        return res.sendStatus(304);
      } else {
        return res.type("application/javascript").set("ETag", clientVersion).status(200).send(clientSource);
      }
    }
  };

}).call(this);

});
require.register("./lib/controllers/errors.js",function (module, exports, require) {(function() {
  var Promise, cwd, fs, path;

  fs = require("fs");

  path = require("path");

  Promise = require("bluebird");

  fs = Promise.promisifyAll(fs);

  cwd = require("../cwd");

  module.exports = {
    handle: function(req, res, config) {
      res.set({
        "Cache-Control": "no-cache, no-store, must-revalidate",
        "Pragma": "no-cache",
        "Expires": "0"
      });
      res.type("js");
      switch (req.params.error) {
        case "support_folder":
          return res.sendFile(cwd("lib", "util", "support_folder.js"));
      }
    }
  };

}).call(this);

});
require.register("./lib/controllers/files.js",function (module, exports, require) {(function() {
  var CacheBuster, Promise, _, allSpecs, api, check, cwd, errors, exampleSpec, glob, interval, intervalId, minimatch, numRuns, path, pathHelpers, projectName, reset, str, user;

  _ = require("lodash");

  str = require("underscore.string");

  path = require("path");

  glob = require("glob");

  Promise = require("bluebird");

  minimatch = require("minimatch");

  cwd = require("../cwd");

  api = require("../api");

  user = require("../user");

  pathHelpers = require("../util/path_helpers");

  CacheBuster = require("../util/cache_buster");

  errors = require("../errors");

  glob = Promise.promisify(glob);

  intervalId = null;

  numRuns = null;

  exampleSpec = null;

  allSpecs = null;

  projectName = null;

  (reset = function() {
    numRuns = 0;
    projectName = null;
    exampleSpec = false;
    return allSpecs = false;
  })();

  check = function() {
    if (numRuns === 0) {
      return;
    }
    return user.ensureSession().then(function(session) {
      return api.sendUsage(numRuns, exampleSpec, allSpecs, projectName, session);
    }).then(reset)["catch"](function() {});
  };

  (interval = function() {
    return intervalId = setInterval(check, 1000 * 60 * 10);
  })();

  module.exports = {
    interval: function() {
      return interval();
    },
    getStats: function() {
      return {
        numRuns: numRuns,
        allSpecs: allSpecs,
        exampleSpec: exampleSpec,
        projectName: projectName
      };
    },
    check: function() {
      return check();
    },
    reset: function() {
      reset();
      if (intervalId) {
        return clearInterval(intervalId);
      }
    },
    increment: function(test, config) {
      var p;
      if (config == null) {
        config = {};
      }
      switch (test) {
        case "integration/example_spec.js":
          exampleSpec = true;
          break;
        case "__all":
          allSpecs = true;
      }
      numRuns += 1;
      if (p = config.projectName) {
        return projectName = p;
      }
    },
    handleFiles: function(req, res, config) {
      return this.getTestFiles(config).then(function(files) {
        return res.json(files);
      });
    },
    handleIframe: function(req, res, config, getRemoteState) {
      var iframePath, test;
      test = req.params[0];
      iframePath = cwd("lib", "html", "iframe.html");
      this.increment(test, config);
      return this.getSpecs(test, config).then((function(_this) {
        return function(specs) {
          return _this.getJavascripts(config).then(function(js) {
            return res.render(iframePath, {
              title: _this.getTitle(test),
              domain: getRemoteState().domainName,
              javascripts: js,
              specs: specs
            });
          });
        };
      })(this));
    },
    getSpecs: function(spec, config) {
      var convertSpecPath, getSpecs;
      convertSpecPath = (function(_this) {
        return function(spec) {
          spec = pathHelpers.getAbsolutePathToSpec(spec, config);
          return _this.prepareForBrowser(spec, config.projectRoot);
        };
      })(this);
      getSpecs = (function(_this) {
        return function() {
          if (spec === "__all") {
            return _this.getTestFiles(config).map(function(spec) {
              return spec.name;
            }).map(convertSpecPath);
          } else {
            return [convertSpecPath(spec)];
          }
        };
      })(this);
      return Promise["try"]((function(_this) {
        return function() {
          return getSpecs();
        };
      })(this));
    },
    prepareForBrowser: function(filePath, projectRoot) {
      filePath = path.relative(projectRoot, filePath);
      return this.getTestUrl(filePath);
    },
    getTestUrl: function(file) {
      file += CacheBuster.get();
      return "/__cypress/tests?p=" + file;
    },
    getTitle: function(test) {
      if (test === "__all") {
        return "All Tests";
      } else {
        return test;
      }
    },
    getJavascripts: function(config) {
      var files, javascripts, paths, projectRoot, supportFile;
      projectRoot = config.projectRoot, supportFile = config.supportFile, javascripts = config.javascripts;
      files = [].concat(javascripts);
      if (supportFile !== false) {
        files = [supportFile].concat(files);
      }
      paths = _.map(files, function(file) {
        return path.resolve(projectRoot, file);
      });
      return Promise.map(paths, function(p) {
        if (!glob.hasMagic(p)) {
          return p;
        }
        p = path.resolve(projectRoot, p);
        return glob(p, {
          nodir: true
        });
      }).then(_.flatten).map((function(_this) {
        return function(filePath) {
          return _this.prepareForBrowser(filePath, projectRoot);
        };
      })(this));
    },
    getTestFiles: function(config) {
      var doesNotMatchAllIgnoredPatterns, fixturesFolderPath, ignorePatterns, integrationFolderPath, javascriptsPath, options, prependIntegrationPath, supportFilePath;
      integrationFolderPath = config.integrationFolder;
      fixturesFolderPath = path.join(config.fixturesFolder, "**", "*");
      supportFilePath = config.supportFile || [];
      javascriptsPath = _.map(config.javascripts, function(js) {
        return path.join(config.projectRoot, js);
      });
      options = {
        sort: true,
        realpath: true,
        cwd: integrationFolderPath,
        ignore: [].concat(javascriptsPath, supportFilePath, fixturesFolderPath)
      };
      prependIntegrationPath = function(file) {
        return path.join("integration", path.relative(integrationFolderPath, file));
      };
      ignorePatterns = [].concat(config.ignoreTestFiles);
      doesNotMatchAllIgnoredPatterns = function(file) {
        return _.every(ignorePatterns, function(pattern) {
          return !minimatch(file, pattern, {
            dot: true,
            matchBase: true
          });
        });
      };
      return glob("**/*.+(js|jsx|coffee|cjsx)", options).filter(doesNotMatchAllIgnoredPatterns).map(function(file) {
        return {
          name: prependIntegrationPath(file)
        };
      });
    }
  };

}).call(this);

});
require.register("./lib/controllers/proxy.js",function (module, exports, require) {(function() {
  var Promise, _, accept, bodyRe, buffers, concat, cors, cwd, headRe, htmlRe, inject, logger, networkFailures, redirectRe, setCookie, through, zlib,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  _ = require("lodash");

  zlib = require("zlib");

  concat = require("concat-stream");

  through = require("through");

  Promise = require("bluebird");

  accept = require("http-accept");

  cwd = require("../cwd");

  logger = require("../logger");

  cors = require("../util/cors");

  inject = require("../util/inject");

  buffers = require("../util/buffers");

  networkFailures = require("../util/network_failures");

  headRe = /(<head.*?>)/i;

  bodyRe = /(<body.*?>)/i;

  htmlRe = /(<html.*?>)/i;

  redirectRe = /^30(1|2|3|7|8)$/;

  zlib = Promise.promisifyAll(zlib);

  setCookie = function(res, key, val, domainName) {
    var options;
    options = {
      domain: domainName
    };
    if (!val) {
      val = "";
      options.expires = new Date(0);
    }
    return res.cookie(key, val, options);
  };

  module.exports = {
    handle: function(req, res, config, getRemoteState, request) {
      var remoteState, thr;
      logger.info("cookies are", req.cookies);
      if (req.cookies["__cypress.unload"]) {
        return res.redirect(config.clientRoute);
      }
      remoteState = getRemoteState();
      logger.info({
        "handling request": "handling request",
        url: req.url,
        proxiedUrl: req.proxiedUrl,
        remoteState: remoteState
      });
      if (req.url === req.proxiedUrl && !remoteState.visiting) {
        return res.redirect(config.clientRoute);
      }
      thr = through(function(d) {
        return this.queue(d);
      });
      return this.getHttpContent(thr, req, res, remoteState, config, request).pipe(res);
    },
    getHttpContent: function(thr, req, res, remoteState, config, request) {
      var endWithResponseErr, err, getErrorHtml, isInitial, obj, onResponse, opts, remoteUrl, reqAcceptsHtml, resContentTypeIsHtml, resMatchesOriginPolicy, rq, setBody, setCookies, wantsInjection;
      process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
      remoteUrl = req.proxiedUrl;
      isInitial = req.cookies["__cypress.initial"] === "true";
      wantsInjection = null;
      resContentTypeIsHtml = function(respHeaders) {
        var contentType;
        contentType = respHeaders["content-type"];
        return contentType && contentType.includes("text/html");
      };
      reqAcceptsHtml = function() {
        var find, ref, types;
        if (req.headers["x-requested-with"]) {
          return;
        }
        types = (ref = accept.parser(req.headers.accept)) != null ? ref : [];
        find = function(type) {
          return indexOf.call(types, type) >= 0;
        };
        return find("text/html") && find("application/xhtml+xml");
      };
      resMatchesOriginPolicy = function(respHeaders) {
        switch (remoteState.strategy) {
          case "http":
            return cors.urlMatchesOriginPolicyProps(remoteUrl, remoteState.props);
          case "file":
            return remoteUrl.startsWith(remoteState.origin);
        }
      };
      setCookies = (function(_this) {
        return function(value) {
          if ((!value) && (!wantsInjection)) {
            return;
          }
          if (!isInitial) {
            return;
          }
          return setCookie(res, "__cypress.initial", value, remoteState.domainName);
        };
      })(this);
      getErrorHtml = (function(_this) {
        return function(err, filePath) {
          var ref, status, urlStr;
          status = (ref = err.status) != null ? ref : 500;
          logger.info("request failed", {
            url: remoteUrl,
            status: status,
            err: err.message
          });
          urlStr = filePath != null ? filePath : remoteUrl;
          return networkFailures.get(err, urlStr, status, remoteState.strategy);
        };
      })(this);
      setBody = (function(_this) {
        return function(str, statusCode, headers) {
          var injection, rewrite;
          res.status(statusCode);
          setCookies(false, wantsInjection);
          logger.info("received request response");
          if (!wantsInjection) {
            return str.pipe(thr);
          } else {
            rewrite = function(body) {
              return _this.rewrite(body.toString(), remoteState, wantsInjection);
            };
            injection = concat(function(body) {
              var encoding;
              encoding = headers["content-encoding"];
              if (encoding && encoding.includes("gzip")) {
                return zlib.gunzipAsync(body).then(rewrite).then(zlib.gzipAsync).then(thr.end)["catch"](endWithResponseErr);
              } else {
                return thr.end(rewrite(body));
              }
            });
            return str.pipe(injection);
          }
        };
      })(this);
      endWithResponseErr = function(err) {
        var checkResStatus, ref, ref1, status, str;
        checkResStatus = function() {
          if (res.headersSent) {
            return res.statusCode;
          }
        };
        status = (ref = (ref1 = err.status) != null ? ref1 : checkResStatus()) != null ? ref : 500;
        if (!res.headersSent) {
          res.removeHeader("Content-Encoding");
        }
        str = through(function(d) {
          return this.queue(d);
        });
        onResponse(str, {
          statusCode: status,
          headers: {
            "content-type": "text/html"
          }
        });
        return str.end(getErrorHtml(err));
      };
      onResponse = (function(_this) {
        return function(str, incomingRes) {
          var cookies, filePath, headers, newUrl, statusCode;
          headers = incomingRes.headers, statusCode = incomingRes.statusCode;
          if (wantsInjection == null) {
            wantsInjection = (function() {
              if (!resContentTypeIsHtml(headers)) {
                return false;
              }
              if (!resMatchesOriginPolicy(headers)) {
                return false;
              }
              if (isInitial) {
                return "full";
              }
              if (!reqAcceptsHtml()) {
                return false;
              }
              return "partial";
            })();
          }
          _this.setResHeaders(req, res, incomingRes, wantsInjection);
          if (cookies = headers["set-cookie"]) {
            res.append("Set-Cookie", cookies);
          }
          if (redirectRe.test(statusCode)) {
            newUrl = headers.location;
            setCookies(true);
            logger.info("redirecting to new url", {
              status: statusCode,
              url: newUrl
            });
            return res.redirect(statusCode, newUrl);
          } else {
            if (headers["x-cypress-file-server-error"]) {
              filePath = headers["x-cypress-file-path"];
              wantsInjection || (wantsInjection = "partial");
              str = through(function(d) {
                return this.queue(d);
              });
              setBody(str, statusCode, headers);
              return str.end(getErrorHtml({
                status: statusCode
              }, filePath));
            } else {
              return setBody(str, statusCode, headers);
            }
          }
        };
      })(this);
      if (obj = buffers.take(remoteUrl)) {
        wantsInjection = "full";
        if (err = obj.stream.error) {
          endWithResponseErr(err);
        } else {
          obj.stream.on("error", endWithResponseErr);
        }
        onResponse(obj.stream, obj.response);
      } else {
        opts = {
          followRedirect: false,
          strictSSL: false
        };
        if (remoteState.strategy === "file" && req.proxiedUrl.startsWith(remoteState.origin)) {
          opts.url = req.proxiedUrl.replace(remoteState.origin, remoteState.fileServer);
        } else {
          opts.url = remoteUrl;
        }
        rq = request.create(opts);
        rq.on("error", endWithResponseErr);
        rq.on("response", function(incomingRes) {
          return onResponse(rq, incomingRes);
        });
        req.pipe(rq);
      }
      return thr;
    },
    setResHeaders: function(req, res, incomingRes, wantsInjection) {
      var headers;
      if (res.headersSent) {
        return;
      }
      headers = _.omit(incomingRes.headers, "set-cookie", "x-frame-options", "content-length", "content-security-policy");
      if (wantsInjection) {
        headers["cache-control"] = "no-cache, no-store, must-revalidate";
      }
      return res.set(headers);
    },
    rewrite: function(html, remoteState, wantsInjection) {
      var htmlToInject, rewrite;
      rewrite = function(re, str) {
        return html.replace(re, str);
      };
      htmlToInject = (function(_this) {
        return function() {
          switch (wantsInjection) {
            case "full":
              return inject.full(remoteState.domainName);
            case "partial":
              return inject.partial(remoteState.domainName);
          }
        };
      })(this)();
      switch (false) {
        case !headRe.test(html):
          return rewrite(headRe, "$1 " + htmlToInject);
        case !bodyRe.test(html):
          return rewrite(bodyRe, "<head> " + htmlToInject + " </head> $1");
        case !htmlRe.test(html):
          return rewrite(htmlRe, "$1 <head> " + htmlToInject + " </head>");
        default:
          return ("<head> " + htmlToInject + " </head>") + html;
      }
    }
  };

}).call(this);

});
require.register("./lib/controllers/runner.js",function (module, exports, require) {(function() {
  var _, runner, send;

  _ = require("lodash");

  send = require("send");

  runner = require("@cypress/core-runner");

  module.exports = {
    serve: function(req, res, config, getRemoteState) {
      config = _.clone(config);
      config.remote = getRemoteState();
      return res.render(runner.getPathToIndex(), {
        config: JSON.stringify(config),
        projectName: config.projectName
      });
    },
    handle: function(req, res) {
      var pathToFile;
      pathToFile = runner.getPathToDist(req.params[0]);
      return send(req, pathToFile).pipe(res);
    }
  };

}).call(this);

});
require.register("./lib/controllers/spec.js",function (module, exports, require) {(function() {
  var appData, bundle, errors, fs;

  fs = require("fs");

  errors = require("../errors");

  bundle = require("../util/bundle");

  appData = require("../util/app_data");

  module.exports = {
    handle: function(spec, req, res, config, next, watchers, project) {
      var streamBundle;
      res.set({
        "Cache-Control": "no-cache, no-store, must-revalidate",
        "Pragma": "no-cache",
        "Expires": "0"
      });
      res.type("js");
      streamBundle = function() {
        return fs.createReadStream(appData.path("bundles", spec)).pipe(res);
      };
      if (config.isHeadless) {
        return bundle.build(spec, config).getLatestBundle().then(streamBundle)["catch"](function(err) {
          var filePath, ref;
          filePath = (ref = err.filePath) != null ? ref : spec;
          err = errors.get("BUNDLE_ERROR", filePath, bundle.errorMessage(err));
          errors.log(err);
          return project.emit("exitEarlyWithErr", err.message);
        });
      } else {
        return watchers.watchBundle(spec, config).then(streamBundle)["catch"](function(err) {
          return res.send(bundle.clientSideError(err));
        });
      }
    }
  };

}).call(this);

});
require.register("./lib/controllers/xhrs.js",function (module, exports, require) {(function() {
  var Promise, _, fixture, fixturesRe, htmlLikeRe, isValidJSON, mime, str;

  _ = require("lodash");

  mime = require("mime");

  str = require("string-to-stream");

  Promise = require("bluebird");

  fixture = require("../fixture");

  fixturesRe = /^(fx:|fixture:)/;

  htmlLikeRe = /<.+>[\s\S]+<\/.+>/;

  isValidJSON = function(text) {
    var o;
    if (_.isObject(text)) {
      return true;
    }
    try {
      o = JSON.parse(text);
      return _.isObject(o);
    } catch (error) {
      false;
    }
    return false;
  };

  module.exports = {
    handle: function(req, res, config, next) {
      var delay, get, headers, respond, response, status;
      get = function(val, def) {
        var ref;
        return decodeURI((ref = req.get(val)) != null ? ref : def);
      };
      delay = ~~get("x-cypress-delay");
      status = get("x-cypress-status", 200);
      headers = get("x-cypress-headers", null);
      response = get("x-cypress-response", "");
      respond = (function(_this) {
        return function() {
          return _this.getResponse(response, config).then(function(resp) {
            headers = _this.parseHeaders(headers, resp);
            return res.set(headers).status(status).send(resp);
          })["catch"](function(err) {
            return res.status(400).send({
              __error: err.message
            });
          });
        };
      })(this);
      if (delay > 0) {
        return Promise.delay(delay).then(respond);
      } else {
        return respond();
      }
    },
    _get: function(resp, config) {
      var file;
      file = resp.replace(fixturesRe, "");
      return fixture.get(config.fixturesFolder, file);
    },
    getStream: function(resp) {
      if (fixturesRe.test(resp)) {
        return this._get(resp).then(function(contents) {
          return str(contents);
        });
      } else {
        return str(resp);
      }
    },
    getResponse: function(resp, config) {
      if (fixturesRe.test(resp)) {
        return this._get(resp, config);
      } else {
        return Promise.resolve(resp);
      }
    },
    parseContentType: function(response) {
      var ret;
      ret = function(type) {
        return mime.lookup(type);
      };
      switch (false) {
        case !isValidJSON(response):
          return ret("json");
        case !htmlLikeRe.test(response):
          return ret("html");
        default:
          return ret("text");
      }
    },
    parseHeaders: function(headers, response) {
      try {
        headers = JSON.parse(headers);
      } catch (error) {}
      if (headers == null) {
        headers = {};
      }
      if (headers["content-type"] == null) {
        headers["content-type"] = this.parseContentType(response);
      }
      return headers;
    }
  };

}).call(this);

});
require.register("./lib/cwd.js",function (module, exports, require) {(function() {
  var appPath, path,
    slice = [].slice;

  path = require("path");

  appPath = (function() {
    if (path.basename(__dirname) === "lib") {
      return path.join(__dirname, "..");
    } else {
      return __dirname;
    }
  })();

  if (process.cwd() !== appPath) {
    process.chdir(appPath);
  }

  module.exports = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return path.join.apply(path, [appPath].concat(slice.call(args)));
  };

}).call(this);

});
require.register("./lib/cypress.js",function (module, exports, require) {(function() {
  var Promise, _, cp, exit, exit0, exitErr, path;

  require("./environment");

  _ = require("lodash");

  cp = require("child_process");

  path = require("path");

  Promise = require("bluebird");

  exit = function(code) {
    if (code == null) {
      code = 0;
    }
    return process.exit(code);
  };

  exit0 = function() {
    return exit(0);
  };

  exitErr = function(err) {
    return require("./errors").log(err).then(function() {
      return exit(1);
    });
  };

  module.exports = {
    isCurrentlyRunningElectron: function() {
      return !!(process.versions && process.versions.electron);
    },
    runElectron: function(mode, options) {
      return Promise["try"]((function(_this) {
        return function() {
          if (_this.isCurrentlyRunningElectron()) {
            return require("./electron")(mode, options);
          } else {
            require("./api").ping()["catch"](function(err) {
              console.log(err.message);
              return require("./errors").warning("DEV_NO_SERVER");
            });
            return new Promise(function(resolve) {
              var cypressElectron, fn;
              cypressElectron = require("@cypress/core-electron");
              fn = function(code) {
                return resolve({
                  failures: code
                });
              };
              return cypressElectron.open(".", require("./util/args").toArray(options), fn);
            });
          }
        };
      })(this));
    },
    openProject: function(options) {
      return require("./electron/handlers/project").open(options.project, options);
    },
    runServer: function(options) {
      var args;
      args = {};
      _.defaults(options, {
        autoOpen: true
      });
      if (!options.project) {
        throw new Error("Missing path to project:\n\nPlease pass 'npm run server -- --project path/to/project'\n\n");
      }
      if (options.debug) {
        args.debug = "--debug";
      }
      _.extend(args, {
        script: "index.js",
        watch: ["--watch", "lib"],
        ignore: ["--ignore", "lib/public"],
        verbose: "--verbose",
        exts: ["-e", "coffee,js"],
        args: ["--", "--config", "port=2020", "--mode", "openProject", "--project", options.project]
      });
      args = _.chain(args).values().flatten().value();
      cp.spawn("nodemon", args, {
        stdio: "inherit"
      });
      if (options.autoOpen) {
        _.delay(function() {
          return require("./launcher").launch("chrome", "http://localhost:2020/__", {
            proxyServer: "http://localhost:2020"
          });
        }, 2000);
      }
      if (options.debug) {
        cp.spawn("node-inspector", [], {
          stdio: "inherit"
        });
        return require("opn")("http://127.0.0.1:8080/debug?ws=127.0.0.1:8080&port=5858");
      }
    },
    start: function(argv) {
      if (argv == null) {
        argv = [];
      }
      require("./logger").info("starting desktop app", {
        args: argv
      });
      return require("./util/app_data").ensure().then((function(_this) {
        return function() {
          var mode, options;
          options = require("./util/args").toObject(argv);
          switch (false) {
            case !options.removeIds:
              options.mode = "removeIds";
              break;
            case !options.version:
              options.mode = "version";
              break;
            case !options.smokeTest:
              options.mode = "smokeTest";
              break;
            case !options.returnPkg:
              options.mode = "returnPkg";
              break;
            case !options.logs:
              options.mode = "logs";
              break;
            case !options.clearLogs:
              options.mode = "clearLogs";
              break;
            case !options.getKey:
              options.mode = "getKey";
              break;
            case !options.generateKey:
              options.mode = "generateKey";
              break;
            case options.exitWithCode == null:
              options.mode = "exitWithCode";
              break;
            case !options.ci:
              options.mode = "ci";
              break;
            case !options.runProject:
              options.mode = "headless";
              break;
            default:
              if (options.mode == null) {
                options.mode = "headed";
              }
          }
          mode = options.mode;
          options = _.omit(options, "mode");
          return _this.startInMode(mode, options);
        };
      })(this));
    },
    startInMode: function(mode, options) {
      switch (mode) {
        case "removeIds":
          return require("./project").removeIds(options.projectPath).then(function(stats) {
            if (stats == null) {
              stats = {};
            }
            return console.log("Removed '" + stats.ids + "' ids from '" + stats.files + "' files.");
          }).then(exit0)["catch"](exitErr);
        case "version":
          return require("./modes/pkg")(options).get("version").then(function(version) {
            return console.log(version);
          }).then(exit0)["catch"](exitErr);
        case "smokeTest":
          return require("./modes/smoke_test")(options).then(function(pong) {
            return console.log(pong);
          }).then(exit0)["catch"](exitErr);
        case "returnPkg":
          return require("./modes/pkg")(options).then(function(pkg) {
            return console.log(JSON.stringify(pkg));
          }).then(exit0)["catch"](exitErr);
        case "logs":
          return require("./electron/handlers/logs").print().then(exit0)["catch"](exitErr);
        case "clearLogs":
          return require("./electron/handlers/logs").clear().then(exit0)["catch"](exitErr);
        case "getKey":
          return require("./project").getSecretKeyByPath(options.projectPath).then(function(key) {
            return console.log(key);
          }).then(exit0)["catch"](exitErr);
        case "generateKey":
          return require("./project").generateSecretKeyByPath(options.projectPath).then(function(key) {
            return console.log(key);
          }).then(exit0)["catch"](exitErr);
        case "exitWithCode":
          return require("./modes/exit")(options).then(exit)["catch"](exitErr);
        case "headless":
          return this.runElectron(mode, options).get("failures").then(exit)["catch"](exitErr);
        case "headed":
          return this.runElectron(mode, options);
        case "ci":
          return this.runElectron(mode, options).get("failures").then(exit)["catch"](exitErr);
        case "server":
          return this.runServer(options);
        case "openProject":
          return this.openProject(options);
        default:
          throw new Error("Cannot start. Invalid mode: '" + mode + "'");
      }
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/automation.js",function (module, exports, require) {(function() {
  var Promise, Renderer, _, automation, cookies, firstOrNull, invoke, os;

  _ = require("lodash");

  os = require("os");

  Promise = require("bluebird");

  cookies = require("./cookies");

  Renderer = require("./renderer");

  firstOrNull = function(cookies) {
    var ref;
    return (ref = cookies[0]) != null ? ref : null;
  };

  invoke = function(method, data) {
    return Promise["try"](function() {
      return automation[method](data);
    });
  };

  automation = {
    getSessionCookies: function() {
      var win;
      win = Renderer.get("PROJECT");
      return win.webContents.session.cookies;
    },
    clear: function(filter) {
      var c, clear;
      if (filter == null) {
        filter = {};
      }
      c = this.getSessionCookies();
      clear = (function(_this) {
        return function(cookie) {
          return cookies.remove(c, cookie)["return"](cookie);
        };
      })(this);
      return this.getAll(filter).map(clear);
    },
    getAll: function(filter) {
      return cookies.get(this.getSessionCookies(), filter);
    },
    getCookies: function(filter) {
      return this.getAll(filter);
    },
    getCookie: function(filter) {
      return this.getAll(filter).then(firstOrNull);
    },
    setCookie: function(props) {
      if (props == null) {
        props = {};
      }
      return cookies.set(this.getSessionCookies(), props)["return"](props);
    },
    clearCookie: function(filter) {
      return this.clear(filter).then(firstOrNull);
    },
    clearCookies: function(filter) {
      return this.clear(filter);
    },
    verify: function(data) {
      return Promise.resolve(true);
    },
    takeScreenshot: function() {
      return new Promise(function(resolve) {
        var win;
        win = Renderer.get("PROJECT");
        return win.capturePage(function(img) {
          return resolve(img.toDataURL());
        });
      });
    }
  };

  module.exports = {
    automation: automation,
    perform: function(msg, data) {
      switch (msg) {
        case "get:cookies":
          return invoke("getCookies", data);
        case "get:cookie":
          return invoke("getCookie", data);
        case "set:cookie":
          return invoke("setCookie", data);
        case "clear:cookies":
          return invoke("clearCookies", data);
        case "clear:cookie":
          return invoke("clearCookie", data);
        case "is:automation:connected":
          return invoke("verify", data);
        case "take:screenshot":
          return invoke("takeScreenshot");
        default:
          return Promise.reject(new Error("No handler registered for: '" + msg + "'"));
      }
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/cookies.js",function (module, exports, require) {(function() {
  var Promise, _, extension;

  _ = require("lodash");

  Promise = require("bluebird");

  extension = require("@cypress/core-extension");

  module.exports = {
    get: function(cookies, filter) {
      if (filter == null) {
        filter = {};
      }
      cookies = this.promisify(cookies);
      return cookies.getAsync(filter);
    },
    set: function(cookies, props) {
      if (props == null) {
        props = {};
      }
      cookies = this.promisify(cookies);
      if (props.url == null) {
        props.url = extension.getCookieUrl(props);
      }
      return cookies.setAsync(props);
    },
    remove: function(cookies, cookie) {
      var url;
      cookies = this.promisify(cookies);
      url = extension.getCookieUrl(cookie);
      return cookies.removeAsync(url, cookie.name);
    },
    promisify: function(cookies) {
      if (cookies.__isPromisified) {
        return cookies;
      }
      cookies.__isPromisified = true;
      return Promise.promisifyAll(cookies);
    },
    clearGithub: function(cookies) {
      var removeCookie;
      removeCookie = (function(_this) {
        return function(cookie) {
          return _this.remove(cookies, cookie);
        };
      })(this);
      return this.get(cookies, {
        domain: "github.com"
      }).map(removeCookie)["return"](null);
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/dialog.js",function (module, exports, require) {(function() {
  var Renderer, dialog;

  dialog = require("electron").dialog;

  Renderer = require("./renderer");

  module.exports = {
    show: function() {
      var props;
      props = {
        properties: ["openDirectory"]
      };
      return new Promise(function(resolve, reject) {
        return dialog.showOpenDialog(props, function(paths) {
          if (paths == null) {
            paths = [];
          }
          return process.nextTick(function() {
            return resolve(paths[0]);
          });
        });
      });
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/events.js",function (module, exports, require) {(function() {
  var Project, Renderer, Updater, _, cookies, cyIcons, dialog, errors, handleEvent, ipc, logger, logs, open, pgk, project, shell, user;

  _ = require("lodash");

  ipc = require("electron").ipcMain;

  shell = require("electron").shell;

  cyIcons = require("@cypress/core-icons");

  dialog = require("./dialog");

  project = require("./project");

  pgk = require("./package");

  cookies = require("./cookies");

  logs = require("./logs");

  Renderer = require("./renderer");

  open = require("../../util/open");

  user = require("../../user");

  logger = require("../../logger");

  errors = require("../../errors");

  Updater = require("../../updater");

  Project = require("../../project");

  handleEvent = function(options, bus, event, id, type, arg) {
    var echo, getConfig, onBus, onFocusTests, onSettingsChanged, onSpecChanged, send, sendErr, sendResponse, upd, win;
    sendResponse = function(data) {
      if (data == null) {
        data = {};
      }
      try {
        logger.info("sending ipc data", {
          type: type,
          data: data
        });
        return event.sender.send("response", data);
      } catch (error) {}
    };
    sendErr = function(err) {
      return sendResponse({
        id: id,
        __error: errors.clone(err, {
          html: true
        })
      });
    };
    send = function(data) {
      return sendResponse({
        id: id,
        data: data
      });
    };
    onBus = function(event) {
      bus.removeAllListeners(event);
      return bus.on(event, send);
    };
    switch (type) {
      case "on:menu:clicked":
        return onBus("menu:item:clicked");
      case "on:app:event":
        return onBus("app:events");
      case "on:focus:tests":
        return onBus("focus:tests");
      case "gui:error":
        return logs.error(arg).then(function() {
          return send(null);
        })["catch"](sendErr);
      case "show:directory:dialog":
        return dialog.show().then(send)["catch"](sendErr);
      case "log:in":
        return user.logIn(arg).then(send)["catch"](sendErr);
      case "log:out":
        return user.logOut().then(send)["catch"](sendErr);
      case "get:current:user":
        return user.get().then(send)["catch"](sendErr);
      case "clear:github:cookies":
        return cookies.clearGithub(event.sender.session.cookies).then(send)["catch"](sendErr);
      case "external:open":
        return shell.openExternal(arg);
      case "on:launch:browser":
        return project.onRelaunch(send);
      case "close:browser":
        return project.closeBrowser().then(send)["catch"](sendErr);
      case "launch:browser":
        return project.launch(arg.browser, arg.url, arg.spec, {
          onBrowserOpen: function() {
            return send({
              browserOpened: true
            });
          },
          onBrowserClose: function() {
            project.closeBrowser();
            return send({
              browserClosed: true
            });
          }
        })["catch"](sendErr);
      case "change:browser:spec":
        return project.changeToSpec(arg.spec).then(send)["catch"](sendErr);
      case "get:open:browsers":
        return project.getBrowsers().then(send)["catch"](sendErr);
      case "window:open":
        return Renderer.create(arg).then(send)["catch"](sendErr);
      case "window:close":
        return Renderer.getByWebContents(event.sender).destroy();
      case "open:finder":
        return open.opn(arg).then(send)["catch"](sendErr);
      case "get:options":
        return pgk(options).then(send)["catch"](sendErr);
      case "updater:check":
        return Updater.check({
          onNewVersion: function() {
            return send(true);
          },
          onNoNewVersion: function() {
            return send(false);
          }
        });
      case "updater:run":
        echo = function(event, version) {
          return send({
            event: event,
            version: version
          });
        };
        upd = Updater.run({
          onStart: function() {
            return echo("start");
          },
          onApply: function() {
            return echo("apply");
          },
          onError: function() {
            return echo("error");
          },
          onDone: function() {
            return echo("done");
          },
          onNone: function() {
            return echo("none");
          },
          onDownload: function(version) {
            return echo("download", version);
          }
        });
        win = Renderer.getByWebContents(event.sender);
        return win.once("closed", function() {
          return upd.cancel();
        });
      case "get:logs":
        return logs.get().then(send)["catch"](sendErr);
      case "clear:logs":
        return logs.clear().then(function() {
          return send(null);
        })["catch"](sendErr);
      case "on:log":
        return logs.onLog(send);
      case "off:log":
        logs.off();
        return send(null);
      case "get:project:paths":
        return Project.paths().then(send)["catch"](sendErr);
      case "add:project":
        return Project.add(arg).then(function() {
          return send(arg);
        })["catch"](sendErr);
      case "remove:project":
        return Project.remove(arg).then(function() {
          return send(arg);
        })["catch"](sendErr);
      case "open:project":
        getConfig = function() {
          return project.opened().getConfig().then(send)["catch"](sendErr);
        };
        onSettingsChanged = function() {
          return project.reboot().then(open);
        };
        onSpecChanged = function(spec) {
          return send({
            specChanged: spec
          });
        };
        onFocusTests = function() {
          if (_.isFunction(options.onFocusTests)) {
            options.onFocusTests();
          }
          return bus.emit("focus:tests");
        };
        open = function() {
          return project.open(arg, options, {
            onFocusTests: onFocusTests,
            onSpecChanged: onSpecChanged,
            onSettingsChanged: onSettingsChanged
          }).then(getConfig)["catch"](sendErr);
        };
        return open();
      case "close:project":
        return project.close().then(send)["catch"](sendErr);
      case "get:specs":
        return project.getSpecChanges({
          onChange: send,
          onError: sendErr
        });
      default:
        throw new Error("No ipc event registered for: '" + type + "'");
    }
  };

  module.exports = {
    handleEvent: handleEvent,
    stop: function() {
      return ipc.removeAllListeners();
    },
    start: function(options, bus) {
      return ipc.on("request", _.partial(this.handleEvent, options, bus));
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/logs.js",function (module, exports, require) {(function() {
  var chalk, logger;

  chalk = require("chalk");

  logger = require("../../logger");

  module.exports = {
    get: function() {
      return logger.getLogs();
    },
    clear: function() {
      return logger.clearLogs();
    },
    off: function() {
      return logger.off();
    },
    onLog: function(fn) {
      return logger.onLog(fn);
    },
    error: function(err) {
      return logger.createException(err)["catch"](function() {});
    },
    print: function() {
      return this.get().then(function(logs) {
        return logs.forEach(function(log, i) {
          var color, str;
          str = JSON.stringify(log);
          color = i % 2 === 0 ? "cyan" : "yellow";
          return console.log(chalk[color](str));
        });
      });
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/menu.js",function (module, exports, require) {(function() {
  var Menu, _, os, shell;

  _ = require("lodash");

  os = require("os");

  Menu = require("electron").Menu;

  shell = require("electron").shell;

  module.exports = {
    set: function(options) {
      var menu, name, template;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        onUpdatesClicked: function() {},
        onLogOutClicked: function() {}
      });
      template = [
        {
          label: "File",
          submenu: [
            {
              label: "Changelog",
              click: function() {
                return shell.openExternal("https://on.cypress.io/changelog");
              }
            }, {
              label: "Check for Updates",
              click: options.onUpdatesClicked
            }, {
              type: "separator"
            }, {
              label: "Log Out",
              click: options.onLogOutClicked
            }, {
              type: "separator"
            }, {
              label: "Close Window",
              accelerator: "CmdOrCtrl+W",
              role: "close"
            }
          ]
        }, {
          label: "Edit",
          submenu: [
            {
              label: "Undo",
              accelerator: "CmdOrCtrl+Z",
              role: "undo"
            }, {
              label: "Redo",
              accelerator: "Shift+CmdOrCtrl+Z",
              role: "redo"
            }, {
              type: "separator"
            }, {
              label: "Cut",
              accelerator: "CmdOrCtrl+X",
              role: "cut"
            }, {
              label: "Copy",
              accelerator: "CmdOrCtrl+C",
              role: "copy"
            }, {
              label: "Paste",
              accelerator: "CmdOrCtrl+V",
              role: "paste"
            }, {
              label: "Select All",
              accelerator: "CmdOrCtrl+A",
              role: "selectall"
            }
          ]
        }, {
          label: "Window",
          role: "window",
          submenu: [
            {
              label: "Minimize",
              accelerator: "CmdOrCtrl+M",
              role: "minimize"
            }
          ]
        }, {
          label: "Help",
          role: "help",
          submenu: [
            {
              label: "Report an Issue..",
              click: function() {
                return shell.openExternal("https://on.cypress.io/new-issue");
              }
            }, {
              label: "Cypress Documentation",
              click: function() {
                return shell.openExternal("https://on.cypress.io");
              }
            }, {
              label: "Cypress Chat",
              click: function() {
                return shell.openExternal("https://on.cypress.io/chat");
              }
            }
          ]
        }
      ];
      if (os.platform() === "darwin") {
        name = "Cypress";
        template.unshift({
          label: name,
          submenu: [
            {
              label: "About " + name,
              role: "about"
            }, {
              type: "separator"
            }, {
              label: "Services",
              role: "services",
              submenu: []
            }, {
              type: "separator"
            }, {
              label: "Hide " + name,
              accelerator: "Command+H",
              role: "hide"
            }, {
              label: "Hide Others",
              accelerator: "Command+Shift+H",
              role: "hideothers"
            }, {
              label: "Show All",
              role: "unhide"
            }, {
              type: "separator"
            }, {
              label: "Quit",
              accelerator: "Command+Q",
              click: (function(_this) {
                return function(item, focusedWindow) {
                  return process.exit(0);
                };
              })(this)
            }
          ]
        });
      }
      if (process.env["CYPRESS_ENV"] === "development") {
        template.push({
          label: "Developer Tools",
          submenu: [
            {
              label: 'Reload',
              accelerator: 'CmdOrCtrl+R',
              click: (function(_this) {
                return function(item, focusedWindow) {
                  if (focusedWindow) {
                    return focusedWindow.reload();
                  }
                };
              })(this)
            }, {
              label: 'Toggle Developer Tools',
              accelerator: (function() {
                if (os.platform() === 'darwin') {
                  return 'Alt+Command+I';
                } else {
                  return 'Ctrl+Shift+I';
                }
              })(),
              click: (function(_this) {
                return function(item, focusedWindow) {
                  if (focusedWindow) {
                    return focusedWindow.toggleDevTools();
                  }
                };
              })(this)
            }
          ]
        });
      }
      menu = Menu.buildFromTemplate(template);
      return Menu.setApplicationMenu(menu);
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/package.js",function (module, exports, require) {(function() {
  var Promise, _, cwd, fs, path, pathToPkg;

  _ = require("lodash");

  fs = require("fs-extra");

  path = require("path");

  Promise = require("bluebird");

  cwd = require("../../cwd");

  fs = Promise.promisifyAll(fs);

  pathToPkg = cwd("package.json");

  module.exports = function(options) {
    return fs.readJsonAsync(pathToPkg).then(function(json) {
      return _.extend({}, options, _.pick(json, "version"));
    });
  };

}).call(this);

});
require.register("./lib/electron/handlers/project.js",function (module, exports, require) {(function() {
  var Project, Promise, _, cache, config, errors, extension, files, launcher, onRelaunch, openBrowser, openBrowserOpts, openProject, specIntervalId;

  _ = require("lodash");

  Promise = require("bluebird");

  extension = require("@cypress/core-extension");

  files = require("../../controllers/files");

  config = require("../../config");

  errors = require("../../errors");

  cache = require("../../cache");

  Project = require("../../project");

  launcher = require("../../launcher");

  onRelaunch = null;

  openProject = null;

  openBrowser = null;

  specIntervalId = null;

  openBrowserOpts = null;

  module.exports = {
    open: function(path, args, options) {
      if (args == null) {
        args = {};
      }
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        sync: true,
        onReloadBrowser: (function(_this) {
          return function(url, browser) {
            return _this.relaunch(url, browser);
          };
        })(this)
      });
      options = _.extend({}, config.whitelist(args), options);
      openProject = Project(path);
      return launcher.getBrowsers().then(function(browsers) {
        if (browsers == null) {
          browsers = [];
        }
        options.browsers = browsers;
        return openProject.open(options);
      }).then(function() {
        return openProject.getConfig().then(function(cfg) {
          return extension.setHostAndPath(cfg.clientUrlDisplay, cfg.socketIoRoute);
        });
      })["return"](openProject);
    },
    opened: function() {
      return openProject;
    },
    launch: function(browser, url, spec, options) {
      if (options == null) {
        options = {};
      }
      return openProject.getConfig().then(function(cfg) {
        if (spec) {
          url = openProject.getUrlBySpec(cfg.clientUrl, spec);
        }
        if (url == null) {
          url = cfg.clientUrl;
        }
        openBrowser = browser;
        openBrowserOpts = options;
        if (options.proxyServer == null) {
          options.proxyServer = cfg.clientUrlDisplay;
        }
        options.chromeWebSecurity = cfg.chromeWebSecurity;
        return launcher.launch(browser, url, options);
      });
    },
    onRelaunch: function(fn) {
      return onRelaunch = fn;
    },
    relaunch: function(url, browser) {
      var b;
      if ((b = browser) && onRelaunch) {
        return onRelaunch({
          browser: b,
          url: url
        });
      } else {
        if (!(b = openBrowser)) {
          return;
        }
        return launcher.launch(b, url, openBrowserOpts);
      }
    },
    reboot: function() {
      return this.close({
        sync: false,
        clearInterval: false
      });
    },
    getSpecChanges: function(options) {
      var checkForSpecUpdates, currentSpecs, get, sendIfChanged;
      if (options == null) {
        options = {};
      }
      currentSpecs = null;
      _.defaults(options, {
        onChange: function() {},
        onError: function() {}
      });
      sendIfChanged = function(specs) {
        if (specs == null) {
          specs = [];
        }
        if (_.isEqual(specs, currentSpecs)) {
          return;
        }
        currentSpecs = specs;
        return options.onChange(specs);
      };
      checkForSpecUpdates = function() {
        return get().then(sendIfChanged)["catch"](options.onError);
      };
      get = function() {
        return openProject.getConfig().then(function(cfg) {
          return files.getTestFiles(cfg);
        });
      };
      specIntervalId = setInterval(checkForSpecUpdates, 2500);
      return checkForSpecUpdates();
    },
    changeToSpec: function(spec) {
      return openProject.getConfig().then(function(cfg) {
        var url;
        openProject.resetState();
        url = openProject.getUrlBySpec(cfg.clientUrl, spec);
        return openProject.changeToUrl(url);
      });
    },
    getBrowsers: function() {
      return Promise.resolve(_.compact([openBrowser]));
    },
    closeBrowser: function() {
      launcher.close();
      if (openProject) {
        openProject.resetState();
      }
      openBrowser = null;
      openBrowserOpts = null;
      return Promise.resolve(null);
    },
    close: function(options) {
      var nullify;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        sync: true,
        clearInterval: true
      });
      nullify = function() {
        onRelaunch = null;
        openProject = null;
        if (options.clearInterval) {
          clearInterval(specIntervalId);
          specIntervalId = null;
        }
        return Promise.resolve(null);
      };
      if (!openProject) {
        return nullify();
      } else {
        return Promise.all([this.closeBrowser(), openProject.close(options)]).then(nullify);
      }
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/renderer.js",function (module, exports, require) {(function() {
  var BrowserWindow, _, cwd, cyDesktop, getByType, getUrl, path, recentlyCreatedWindow, uri, user, windows;

  _ = require("lodash");

  path = require("path");

  uri = require("url");

  cyDesktop = require("@cypress/core-desktop-gui");

  BrowserWindow = require("electron").BrowserWindow;

  cwd = require("../../cwd");

  user = require("../../user");

  windows = {};

  recentlyCreatedWindow = false;

  getUrl = function(type) {
    switch (type) {
      case "GITHUB_LOGIN":
        return user.getLoginUrl();
      case "ABOUT":
        return cyDesktop.getPathToAbout();
      case "DEBUG":
        return cyDesktop.getPathToDebug();
      case "UPDATES":
        return cyDesktop.getPathToUpdates();
      case "INDEX":
        return cyDesktop.getPathToIndex();
      default:
        throw new Error("No acceptable window type found for: '" + type + "'");
    }
  };

  getByType = function(type) {
    return windows[type];
  };

  module.exports = {
    reset: function() {
      return windows = {};
    },
    destroy: function(type) {
      var win;
      if (type && (win = getByType(type))) {
        return win.destroy();
      }
    },
    get: function(type) {
      var ref;
      return (function() {
        if ((ref = getByType(type)) != null) {
          return ref;
        } else {
          throw new Error("No window exists for: '" + type + "'");
        }
      })();
    },
    showAll: function() {
      return _.invoke(windows, "showInactive");
    },
    hideAllUnlessAnotherWindowIsFocused: function() {
      if (BrowserWindow.getFocusedWindow() || recentlyCreatedWindow) {
        return;
      }
      return _.invoke(windows, "hide");
    },
    getByWebContents: function(webContents) {
      return _.find(windows, function(win) {
        return win.webContents === webContents;
      });
    },
    create: function(options) {
      var args, err, height, urlChanged, width, win;
      if (options == null) {
        options = {};
      }
      if (win = getByType(options.type)) {
        win.show();
        if (options.type === "GITHUB_LOGIN") {
          err = new Error;
          err.alreadyOpen = true;
          return Promise.reject(err);
        } else {
          return Promise.resolve(win);
        }
      }
      recentlyCreatedWindow = true;
      _.defaults(options, {
        onFocus: function() {},
        onBlur: function() {}
      });
      args = _.defaults({}, options, {
        width: 600,
        height: 500,
        show: true,
        webPreferences: {
          preload: cwd("lib", "ipc", "ipc.js"),
          nodeIntegration: false,
          backgroundThrottling: false
        }
      });
      if (args.show === false) {
        args.webPreferences.offscreen = true;
      }
      if (options.chromeWebSecurity === false) {
        args.webPreferences.webSecurity = false;
      }
      if (args.url == null) {
        args.url = getUrl(options.type);
      }
      urlChanged = function(url, resolve) {
        var code, parsed;
        parsed = uri.parse(url, true);
        if (code = parsed.query.code) {
          _.defer(function() {
            return win.destroy();
          });
          return resolve(code);
        }
      };
      if (args.transparent && args.show) {
        width = args.width, height = args.height;
        args.show = false;
        args.width = 0;
        args.height = 0;
      }
      win = new BrowserWindow(args);
      win.on("blur", function() {
        return options.onBlur.apply(win, arguments);
      });
      win.on("focus", function() {
        return options.onFocus.apply(win, arguments);
      });
      windows[options.type] = win;
      win.webContents.id = _.uniqueId("webContents");
      win.once("closed", function() {
        win.removeAllListeners();
        return delete windows[options.type];
      });
      if (args.devTools) {
        win.webContents.openDevTools({
          detach: true
        });
      }
      return Promise.resolve(args.url).then(function(url) {
        if (width && height) {
          win.webContents.once("dom-ready", function() {
            win.setSize(width, height);
            return win.show();
          });
        }
        win.loadURL(url);
        recentlyCreatedWindow = false;
        if (args.type === "GITHUB_LOGIN") {
          return new Promise(function(resolve, reject) {
            win.webContents.on("will-navigate", function(e, url) {
              return urlChanged(url, resolve);
            });
            return win.webContents.on("did-get-redirect-request", function(e, oldUrl, newUrl) {
              return urlChanged(newUrl, resolve);
            });
          });
        } else {
          return Promise.resolve(win);
        }
      });
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/updater.js",function (module, exports, require) {(function() {


}).call(this);

});
require.register("./lib/electron/index.js",function (module, exports, require) {(function() {
  module.exports = function(mode, options) {
    switch (mode) {
      case "ci":
        return require("../modes/ci").run(options);
      case "headless":
        return require("../modes/headless").run(options);
      case "headed":
        return require("../modes/headed").run(options);
    }
  };

}).call(this);

});
require.register("./lib/environment.js",function (module, exports, require) {(function() {
  var Promise, app, cwd, fs, getEnv, os, pkg;

  require("./util/http_overrides");

  os = require("os");

  fs = require("fs-extra");

  cwd = require("./cwd");

  Promise = require("bluebird");

  Promise.config({
    cancellation: true
  });

  Error.stackTraceLimit = 2e308;

  pkg = cwd("package.json");

  try {
    app = require("electron").app;
    app.commandLine.appendSwitch("disable-renderer-backgrounding", true);
    app.commandLine.appendSwitch("ignore-certificate-errors", true);
    if (os.platform() === "linux") {
      app.disableHardwareAcceleration();
    }
  } catch (error) {}

  getEnv = function() {
    var base, ref;
    return (base = process.env)["CYPRESS_ENV"] || (base["CYPRESS_ENV"] = (ref = fs.readJsonSync(pkg).env) != null ? ref : "development");
  };

  module.exports = getEnv();

}).call(this);

});
require.register("./lib/errors.js",function (module, exports, require) {(function() {
  var API, Promise, _, ansi_up, chalk, strip,
    hasProp = {}.hasOwnProperty;

  _ = require("lodash");

  strip = require("strip-ansi");

  chalk = require("chalk");

  ansi_up = require("ansi_up");

  Promise = require("bluebird");

  API = {
    getMsgByType: function(type, arg1, arg2) {
      switch (type) {
        case "CANNOT_TRASH_ASSETS":
          return "Warning: We failed to trash the existing build assets.\n\nThis error will not alter the exit code.\n\n" + arg1;
        case "VIDEO_RECORDING_FAILED":
          return "Warning: We failed to record the video.\n\nThis error will not alter the exit code.\n\n" + arg1;
        case "VIDEO_POST_PROCESSING_FAILED":
          return "Warning: We failed processing this video.\n\nThis error will not alter the exit code.\n\n" + arg1;
        case "NOT_LOGGED_IN":
          return "You're not logged in.\n\nRun `cypress open` to open the Desktop App and login.";
        case "TESTS_DID_NOT_START_RETRYING":
          return "Timed out waiting for the browser to connect. " + arg1;
        case "TESTS_DID_NOT_START_FAILED":
          return "The browser never connected. Something is wrong. The tests cannot run. Aborting...";
        case "PROJECT_DOES_NOT_EXIST":
          return "You need to add a project to run tests.";
        case "CI_CANNOT_UPLOAD_ASSETS":
          return "Warning: We encountered an error while uploading your build assets.\n\nThese build assets will not be recorded\n\nThis error will not alter or the exit code.\n\n" + arg1;
        case "CI_CANNOT_CREATE_BUILD_OR_INSTANCE":
          return "Warning: We encountered an error talking to our servers.\n\nNo build assets will be recorded.\n\nThis error will not alter the exit code.\n\n" + arg1;
        case "CI_KEY_MISSING":
          return "Can't run in CI without a CI key. You did not provide one.";
        case "CI_KEY_NOT_VALID":
          return "Can't run project in CI. Your project's CI key: " + (chalk.blue(arg1)) + " is invalid.";
        case "CI_PROJECT_NOT_FOUND":
          return "Can't find project. Aborting the CI run.\n\nCheck that your 'projectId' and 'secret CI key' are valid.";
        case "DEV_NO_SERVER":
          return " > The local API server isn't running in development. This may cause problems running the GUI.";
        case "NO_PROJECT_ID":
          return "Can't find 'projectId' in the 'cypress.json' file for this project: " + chalk.blue(arg1);
        case "NO_PROJECT_FOUND_AT_PROJECT_ROOT":
          return "Can't find project at the path: " + chalk.blue(arg1);
        case "CANNOT_FETCH_PROJECT_TOKEN":
          return "Can't find project's secret key.";
        case "CANNOT_CREATE_PROJECT_TOKEN":
          return "Can't create project's secret key.";
        case "PORT_IN_USE_SHORT":
          return "Port '" + arg1 + "' is already in use.";
        case "PORT_IN_USE_LONG":
          return "Can't run project because port is currently in use: " + chalk.blue(arg1) + "\n\n" + chalk.yellow("Assign a different port with the '--port <port>' argument or shut down the other running process.");
        case "ERROR_READING_FILE":
          return "Error reading from: " + chalk.blue(arg1) + "\n\n" + chalk.yellow(arg2);
        case "ERROR_WRITING_FILE":
          return "Error writing to: " + chalk.blue(arg1) + "\n\n" + chalk.yellow(arg2);
        case "SPEC_FILE_NOT_FOUND":
          return "Can't find test spec: " + chalk.blue(arg1);
        case "RENDERER_CRASHED":
          return "We detected that the Chromium Renderer process just crashed.\n\nThis is the equivalent to seeing the 'sad face' when Chrome dies.\n\nThis can happen for a number of different reasons:\n\n- You wrote an endless loop and you must fix your own code\n- There is a memory leak in Cypress (unlikely but possible)\n- You are running Docker (there is an easy fix for this: see link below)\n- You are running lots of tests on a memory intense application\n- You are running in a memory starved VM environment\n- There are problems with your GPU / GPU drivers\n- There are browser bugs in Chromium\n\nYou can learn more including how to fix Docker here:\n\nhttps://on.cypress.io/renderer-process-crashed";
        case "NO_CURRENTLY_OPEN_PROJECT":
          return "Can't find open project.";
        case "AUTOMATION_SERVER_DISCONNECTED":
          return "The automation server disconnected. Cannot continue running tests.";
        case "SUPPORT_FILE_NOT_FOUND":
          return "Support file missing or invalid\n\nYour supportFile is set to '" + arg1 + "', but either the file is missing or it's invalid. The supportFile must be a .js or .coffee file.\n\nCorrect your cypress.json or create the appropriate file.\n\nLearn more at https://on.cypress.io/support-file-missing-or-invalid";
        case "BUNDLE_ERROR":
          return "Oops...we found an error preparing this test file:\n\n  " + (chalk.blue(arg1)) + "\n\nThe error was:\n\n" + (chalk.yellow(arg2)) + "\n\nThis occurred while Cypress was compiling and bundling your test code. This is usually caused by:\n\n* A missing file or dependency\n* A syntax error in the file or one of its dependencies\n\nFix the error in your code and re-run your tests.";
      }
    },
    get: function(type, arg1, arg2) {
      var err, msg;
      msg = this.getMsgByType(type, arg1, arg2);
      err = new Error(msg);
      err.type = type;
      return err;
    },
    isCypressErr: function(err) {
      return err.type && this.getMsgByType(err.type);
    },
    warning: function(type, arg) {
      var err;
      err = this.get(type, arg);
      return this.log(err, "magenta");
    },
    log: function(err, color) {
      if (color == null) {
        color = "red";
      }
      return Promise["try"]((function(_this) {
        return function() {
          console.log(chalk[color](err.message));
          if (_this.isCypressErr(err)) {
            return;
          }
          console.log(chalk[color](err.stack));
          if (process.env["CYPRESS_ENV"] === "production") {
            return require("./logger").createException(err)["catch"](function() {});
          }
        };
      })(this));
    },
    "throw": function(type, arg) {
      throw this.get(type, arg);
    },
    stripAnsi: strip,
    clone: function(err, options) {
      var obj, prop, val;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        html: false
      });
      obj = _.pick(err, "type", "name", "stack", "fileName", "lineNumber", "columnNumber");
      if (options.html) {
        obj.message = ansi_up.ansi_to_html(err.message, {
          use_classes: true
        });
      } else {
        obj.message = err.message;
      }
      for (prop in err) {
        if (!hasProp.call(err, prop)) continue;
        val = err[prop];
        obj[prop] = val;
      }
      return obj;
    }
  };

  module.exports = _.bindAll(API, _.functions(API));

}).call(this);

});
require.register("./lib/exception.js",function (module, exports, require) {(function() {
  var Promise, Settings, api, cache, fs, logger, user, winston;

  Promise = require("bluebird");

  winston = require("winston");

  fs = require("fs-extra");

  api = require("./api");

  user = require("./user");

  cache = require("./cache");

  logger = require("./logger");

  Settings = require("./util/settings");

  module.exports = {
    getCache: function() {
      return cache.read();
    },
    getLogs: function() {
      return logger.getLogs();
    },
    getErr: function(err) {
      return {
        name: err.name,
        message: err.message,
        stack: err.stack,
        info: winston.exception.getAllInfo(err)
      };
    },
    getVersion: function() {
      return fs.readJsonAsync("./package.json").get("version");
    },
    getBody: function(err, settings) {
      var body;
      body = {
        err: this.getErr(err)
      };
      return Promise.all([this.getCache(), this.getLogs(), this.getVersion()]).spread(function(cache, logs, version) {
        body.cache = cache;
        body.logs = logs;
        body.settings = settings;
        return body.version = version;
      })["return"](body);
    },
    getSession: function() {
      return user.get().then(function(user) {
        return user && user.sessionToken;
      });
    },
    create: function(err, settings) {
      if (process.env["CYPRESS_ENV"] !== "production") {
        return Promise.resolve();
      }
      return Promise.props({
        body: this.getBody(err, settings),
        session: this.getSession()
      }).then(function(props) {
        return api.createRaygunException(props.body, props.session);
      });
    }
  };

}).call(this);

});
require.register("./lib/exec.js",function (module, exports, require) {(function() {
  var Promise, _, cp, exec, getProfilePath, getShell, profiles, shell, sourced, str;

  _ = require("underscore");

  str = require("underscore.string");

  cp = require("child_process");

  Promise = require("bluebird");

  exec = Promise.promisify(cp.exec);

  profiles = {
    "~/.profile": /\/sh$/,
    "~/.bash_profile": /\/bash$/,
    "~/.cshrc": /\/csh$/,
    "~/.profile": /\/ksh$/,
    "~/.zshrc": /\/zsh$/,
    "~/.config/fish/config.fish": /\/fish$/
  };

  sourced = false;

  getProfilePath = function(shellPath) {
    var profilePath, regex;
    for (profilePath in profiles) {
      regex = profiles[profilePath];
      if (regex.test(shellPath)) {
        return profilePath;
      }
    }
  };

  shell = null;

  getShell = function() {
    if (shell) {
      return Promise.resolve(shell);
    }
    return exec("echo $SHELL").then(function(shell) {
      var path;
      path = str.trim(shell);
      shell = {
        shellPath: path,
        profilePath: getProfilePath(path)
      };
      return shell;
    });
  };

  module.exports = {
    run: function(projectRoot, options) {
      var child, run;
      child = null;
      run = function() {
        return getShell().then(function(shell) {
          return new Promise(function(resolve, reject) {
            var cmd, output, ref;
            cmd = shell.profilePath && !sourced ? (sourced = true, "source " + shell.profilePath + " > /dev/null 2>&1; " + options.cmd) : options.cmd;
            child = cp.spawn(cmd, {
              cwd: projectRoot,
              env: _.extend({}, process.env, options.env),
              shell: (ref = shell.shellPath) != null ? ref : true
            });
            output = {
              shell: shell,
              stdout: "",
              stderr: ""
            };
            child.stdout.on("data", function(data) {
              return output.stdout += data.toString();
            });
            child.stderr.on("data", function(data) {
              return output.stderr += data.toString();
            });
            child.on("error", function(err) {
              return reject(err);
            });
            return child.on("close", function(code) {
              output.code = code;
              return resolve(output);
            });
          });
        });
      };
      return Promise["try"](run).timeout(options.timeout)["catch"](Promise.TimeoutError, function() {
        var err;
        if (child) {
          child.kill();
        }
        err = new Error("Process timed out");
        err.timedout = true;
        throw err;
      });
    }
  };

}).call(this);

});
require.register("./lib/file_server.js",function (module, exports, require) {(function() {
  var _, allowDestroy, errors, http, onRequest, path, send, url;

  _ = require("lodash");

  url = require("url");

  http = require("http");

  path = require("path");

  send = require("send");

  allowDestroy = require("server-destroy-vvo");

  errors = require("./errors");

  onRequest = function(req, res, fileServerFolder) {
    var args, file;
    args = _.compact([fileServerFolder, req.url]);
    file = decodeURI(url.parse(path.join.apply(path, args)).pathname);
    res.setHeader("x-cypress-file-path", file);
    return send(req, url.parse(req.url).pathname, {
      root: path.resolve(fileServerFolder)
    }).on("error", function(err) {
      res.setHeader("x-cypress-file-server-error", true);
      res.statusCode = err.status;
      return res.end();
    }).pipe(res);
  };

  module.exports = {
    create: function(fileServerFolder) {
      return new Promise(function(resolve) {
        var srv;
        srv = http.createServer(function(req, res) {
          return onRequest(req, res, fileServerFolder);
        });
        allowDestroy(srv);
        return srv.listen(function() {
          return resolve({
            port: function() {
              return srv.address().port;
            },
            address: function() {
              return "http://localhost:" + this.port();
            },
            close: function() {
              return new Promise(function(resolve) {
                return srv.destroy(resolve);
              });
            }
          });
        });
      });
    }
  };

}).call(this);

});
require.register("./lib/files.js",function (module, exports, require) {(function() {
  var Promise, fs, path;

  fs = require("fs-extra");

  path = require("path");

  Promise = require("bluebird");

  fs = Promise.promisifyAll(fs);

  module.exports = {
    readFile: function(projectRoot, file, options) {
      var filePath, readFn;
      if (options == null) {
        options = {};
      }
      filePath = path.join(projectRoot, file);
      readFn = path.extname(filePath) === ".json" ? fs.readJsonAsync : fs.readFileAsync;
      return readFn(filePath, options.encoding || "utf8").then(function(contents) {
        return {
          contents: contents,
          filePath: filePath
        };
      })["catch"](function(err) {
        err.filePath = filePath;
        throw err;
      });
    },
    writeFile: function(projectRoot, file, contents, options) {
      var filePath;
      if (options == null) {
        options = {};
      }
      filePath = path.join(projectRoot, file);
      return fs.outputFileAsync(filePath, contents, options.encoding || "utf8").then(function() {
        return {
          contents: contents,
          filePath: filePath
        };
      })["catch"](function(err) {
        err.filePath = filePath;
        throw err;
      });
    }
  };

}).call(this);

});
require.register("./lib/fixture.js",function (module, exports, require) {(function() {
  var Promise, _, beautify, check, coffee, cwd, extensions, formatter, fs, jsonlint, lastCharacterIsNewLine, path, pretty, queue;

  _ = require("lodash");

  fs = require("fs-extra");

  path = require("path");

  check = require("syntax-error");

  coffee = require("coffee-script");

  Promise = require("bluebird");

  jsonlint = require("jsonlint");

  beautify = require("js-beautify").html;

  pretty = require("js-object-pretty-print").pretty;

  formatter = require("jsonlint/lib/formatter").formatter;

  cwd = require("./cwd");

  fs = Promise.promisifyAll(fs);

  extensions = ".json .js .coffee .html .txt .csv .png .jpg .jpeg .gif .tif .tiff .zip".split(" ");

  queue = {};

  lastCharacterIsNewLine = function(str) {
    return str[str.length - 1] === "\n";
  };

  module.exports = {
    get: function(fixturesFolder, filePath, options) {
      var ext, fixture, p, tryParsingFile;
      if (options == null) {
        options = {};
      }
      p = path.join(fixturesFolder, filePath);
      fixture = path.basename(p);
      if (ext = path.extname(p)) {
        return this.parseFile(p, fixture, ext, options);
      } else {
        tryParsingFile = (function(_this) {
          return function(index) {
            ext = extensions[index];
            if (!ext) {
              throw new Error("No fixture file found with an acceptable extension. Searched in: " + p);
            }
            return _this.fileExists(p + ext)["catch"](function() {
              return tryParsingFile(index + 1);
            }).then(function() {
              return this.parseFile(p + ext, fixture, ext, options);
            });
          };
        })(this);
        return Promise.resolve(tryParsingFile(0));
      }
    },
    fileExists: function(p) {
      return fs.statAsync(p).bind(this);
    },
    parseFile: function(p, fixture, ext, options) {
      var cleanup;
      if (queue[p]) {
        return Promise.delay(1).then((function(_this) {
          return function() {
            return _this.parseFile(p, fixture, ext);
          };
        })(this));
      } else {
        queue[p] = true;
        cleanup = function() {
          return delete queue[p];
        };
        return this.fileExists(p)["catch"](function(err) {
          throw new Error("No fixture exists at: " + p);
        }).then(function() {
          return this.parseFileByExtension(p, fixture, ext, options);
        }).then(function(ret) {
          cleanup();
          return ret;
        })["catch"](function(err) {
          cleanup();
          throw err;
        });
      }
    },
    parseFileByExtension: function(p, fixture, ext, options) {
      if (ext == null) {
        ext = path.extname(fixture);
      }
      switch (ext) {
        case ".json":
          return this.parseJson(p, fixture);
        case ".js":
          return this.parseJs(p, fixture);
        case ".coffee":
          return this.parseCoffee(p, fixture);
        case ".html":
          return this.parseHtml(p, fixture);
        case ".png":
        case ".jpg":
        case ".jpeg":
        case ".gif":
        case ".tif":
        case ".tiff":
        case ".zip":
          return this.parse(p, fixture, "base64");
        default:
          return this.parse(p, fixture, options.encoding);
      }
    },
    parseJson: function(p, fixture) {
      return fs.readFileAsync(p, "utf8").bind(this).then(function(str) {
        var formatted;
        formatted = formatter.formatJson(str, "  ");
        if (formatted === str) {
          return str;
        } else {
          if (lastCharacterIsNewLine(str)) {
            formatted += "\n";
          }
          return fs.writeFileAsync(p, formatted)["return"](formatted);
        }
      }).then(jsonlint.parse)["catch"](function(err) {
        throw new Error("'" + fixture + "' is not valid JSON.\n" + err.message);
      });
    },
    parseJs: function(p, fixture) {
      return fs.readFileAsync(p, "utf8").bind(this).then(function(str) {
        var e, err, obj;
        try {
          obj = eval("(" + str + ")");
        } catch (error) {
          e = error;
          err = check(str, fixture);
          if (err) {
            throw err;
          }
          throw e;
        }
        return obj;
      }).then(function(obj) {
        var str;
        str = pretty(obj, 2);
        return fs.writeFileAsync(p, str)["return"](obj);
      })["catch"](function(err) {
        throw new Error("'" + fixture + "' is not a valid JavaScript object." + (err.toString()));
      });
    },
    parseCoffee: function(p, fixture) {
      var dc;
      dc = process.env.NODE_DISABLE_COLORS;
      process.env.NODE_DISABLE_COLORS = "0";
      return fs.readFileAsync(p, "utf8").bind(this).then(function(str) {
        str = coffee.compile(str, {
          bare: true
        });
        return eval(str);
      }).then(function(obj) {
        var str;
        str = pretty(obj, 2);
        return fs.writeFileAsync(p, str)["return"](obj);
      })["catch"](function(err) {
        throw new Error("'" + fixture + " is not a valid CoffeeScript object.\n" + (err.toString()));
      })["finally"](function() {
        return process.env.NODE_DISABLE_COLORS = dc;
      });
    },
    parseHtml: function(p, fixture) {
      return fs.readFileAsync(p, "utf8").bind(this).then(function(str) {
        var html;
        html = beautify(str, {
          indent_size: 2,
          extra_liners: []
        });
        if (lastCharacterIsNewLine(str)) {
          html += "\n";
        }
        return fs.writeFileAsync(p, html)["return"](html);
      });
    },
    parse: function(p, fixture, encoding) {
      if (encoding == null) {
        encoding = "utf8";
      }
      return fs.readFileAsync(p, encoding).bind(this);
    }
  };

}).call(this);

});
require.register("./lib/ids.js",function (module, exports, require) {(function() {
  var Promise, fs, glob, idRe, path;

  fs = require("fs");

  path = require("path");

  glob = require("glob");

  Promise = require("bluebird");

  fs = Promise.promisifyAll(fs);

  idRe = /\s*\[.{3}\]/g;

  module.exports = {
    files: function(pathToTestFiles) {
      return new Promise(function(resolve, reject) {
        return glob(path.join(pathToTestFiles, "**", "*+(.js|.coffee)"), {
          nodir: true
        }, function(err, files) {
          if (err) {
            reject(err);
          }
          return resolve(files);
        });
      });
    },
    get: function(pathToTestFiles) {
      var getIds;
      getIds = function(memo, file) {
        return fs.readFileAsync(file, "utf8").then(function(contents) {
          var matches;
          if (matches = contents.match(idRe)) {
            memo = memo.concat(matches);
          }
          return memo;
        });
      };
      return Promise.reduce(this.files(pathToTestFiles), getIds, []);
    },
    remove: function(pathToTestFiles) {
      var removeIds;
      removeIds = function(memo, file) {
        return fs.readFileAsync(file, "utf8").then(function(contents) {
          var matches;
          if (matches = contents.match(idRe)) {
            memo.ids += matches.length;
            memo.files += 1;
            contents = contents.replace(idRe, "");
            fs.writeFileAsync(file, contents);
          }
          return memo;
        });
      };
      return Promise.reduce(this.files(pathToTestFiles), removeIds, {
        ids: 0,
        files: 0
      });
    }
  };

}).call(this);

});
require.register("./lib/konfig.js",function (module, exports, require) {(function() {
  var getConfig, konfig;

  require("./environment");

  konfig = require("konfig");

  getConfig = function() {
    var config, previousNodeEnv;
    previousNodeEnv = process.env["NODE_ENV"];
    process.env["NODE_ENV"] = process.env["CYPRESS_ENV"];
    config = konfig().app;
    process.env["NODE_ENV"] = previousNodeEnv;
    return function(getter) {
      return config[getter];
    };
  };

  module.exports = getConfig();

}).call(this);

});
require.register("./lib/launcher.js",function (module, exports, require) {(function() {
  var Promise, _, appData, defaultArgs, extension, fs, instance, kill, launcher, path, pathToExtension, pathToTheme, profiles;

  _ = require("lodash");

  fs = require("fs-extra");

  path = require("path");

  Promise = require("bluebird");

  launcher = require("@cypress/core-launcher");

  extension = require("@cypress/core-extension");

  appData = require("./util/app_data");

  fs = Promise.promisifyAll(fs);

  profiles = appData.path("browsers");

  pathToExtension = extension.getPathToExtension();

  pathToTheme = extension.getPathToTheme();

  instance = null;

  kill = function(unbind) {
    if (!instance) {
      return;
    }
    if (unbind) {
      instance.removeAllListeners();
    }
    instance.kill();
    return instance = null;
  };

  process.once("exit", kill);

  defaultArgs = ["--test-type", "--ignore-certificate-errors", "--load-extension=" + pathToExtension + "," + pathToTheme, "--start-maximized", "--silent-debugger-extension-api", "--no-default-browser-check", "--no-first-run", "--noerrdialogs", "--enable-fixed-layout", "--disable-popup-blocking", "--disable-password-generation", "--disable-save-password-bubble", "--disable-single-click-autofill", "--disable-prompt-on-repos", "--disable-background-timer-throttling", "--disable-renderer-backgrounding", "--disable-renderer-throttling", "--disable-restore-session-state", "--disable-translate", "--disable-new-profile-management", "--disable-new-avatar-menu", "--allow-insecure-localhost", "--reduce-security-for-testing", "--metrics-recording-only", "--disable-prompt-on-repost", "--disable-hang-monitor", "--disable-sync", "--disable-background-networking", "--disable-web-resources", "--safebrowsing-disable-auto-update", "--safebrowsing-disable-download-protection", "--disable-client-side-phishing-detection", "--disable-component-update", "--disable-default-apps"];

  module.exports = {
    args: defaultArgs,
    close: kill,
    ensureProfile: function(name) {
      var p;
      p = path.join(profiles, name);
      return fs.ensureDirAsync(p)["return"](p);
    },
    getBrowsers: function() {
      return launcher.detect();
    },
    launch: function(name, url, options) {
      var args;
      if (options == null) {
        options = {};
      }
      kill(true);
      _.defaults(options, {
        args: [],
        onBrowserOpen: function() {},
        onBrowserClose: function() {}
      });
      args = defaultArgs.concat(options.args);
      return this.ensureProfile(name).then(function(dir) {
        var ps;
        args.push("--user-data-dir=" + dir);
        if (ps = options.proxyServer) {
          args.push("--proxy-server=" + ps);
        }
        if (options.chromeWebSecurity === false) {
          args.push("--disable-web-security");
          args.push("--allow-running-insecure-content");
        }
        return launcher().call("launch", name, url, args).then(function(i) {
          instance = i;
          instance.once("exit", function() {
            return options.onBrowserClose();
          });
          return Promise.delay(1000).then(function() {
            options.onBrowserOpen();
            return instance;
          });
        });
      });
    }
  };

}).call(this);

});
require.register("./lib/logger.js",function (module, exports, require) {(function() {
  var Promise, _, appData, createFile, folder, fs, getName, getPathToLog, logger, path, transports, winston,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
    slice = [].slice;

  path = require("path");

  _ = require("lodash");

  fs = require("fs-extra");

  Promise = require("bluebird");

  winston = require("winston");

  appData = require("./util/app_data");

  folder = appData.path();

  getName = function(name) {
    return name + ".log";
  };

  getPathToLog = function(name) {
    return path.join(folder, getName(name));
  };

  createFile = function(name, level, opts) {
    var file, obj;
    if (opts == null) {
      opts = {};
    }
    file = getPathToLog(name);
    fs.ensureDirSync(path.dirname(file));
    obj = {
      name: name,
      filename: file,
      colorize: true,
      tailable: true,
      maxsize: 1000000
    };
    if (level) {
      obj.level = level;
    }
    _.extend(obj, opts);
    return new winston.transports.File(obj);
  };

  transports = [
    createFile("all", null, {
      handleExceptions: true
    })
  ];

  if (process.env.CYPRESS_DEBUG) {
    transports.push(new winston.transports.Console());
  }

  logger = new winston.Logger({
    transports: transports,
    exitOnError: function(err) {
      return logger.defaultErrorHandler(err);
    }
  });

  logger.createException = function(err) {
    return require("./exception").create(err, logger.getSettings());
  };

  logger.defaultErrorHandler = function(err) {
    var exit, handleErr;
    logger.info("caught error", {
      error: err.message,
      stack: err.stack
    });
    exit = function() {
      return process.exit(1);
    };
    handleErr = function() {
      var e, ret;
      if (e = logger.errorHandler) {
        ret = e(err);
        if (ret === true) {
          return exit();
        }
      } else {
        console.log(err);
        console.log(err.stack);
        return exit();
      }
    };
    logger.createException(err).then(handleErr)["catch"](handleErr);
    return false;
  };

  logger.setSettings = function(obj) {
    return logger._settings = obj;
  };

  logger.getSettings = function() {
    return logger._settings;
  };

  logger.unsetSettings = function() {
    return delete logger._settings;
  };

  logger.setErrorHandler = function(fn) {
    return logger.errorHandler = fn;
  };

  logger.getData = function(obj) {
    var keys;
    keys = ["level", "message", "timestamp", "type"];
    return _.reduce(obj, function(memo, value, key) {
      if (indexOf.call(keys, key) < 0) {
        memo.data[key] = value;
      } else {
        memo[key] = value;
      }
      return memo;
    }, {
      data: {}
    });
  };

  logger.normalize = function(logs) {
    if (logs == null) {
      logs = [];
    }
    return _.map(logs, logger.getData);
  };

  logger.getLogs = function() {
    var transport;
    transport = "all";
    return new Promise(function(resolve, reject) {
      var opts, ref, t;
      opts = {
        limit: 500,
        order: "desc"
      };
      t = (function() {
        if ((ref = logger.transports[transport]) != null) {
          return ref;
        } else {
          throw new Error("Log transport: '" + transport + "' does not exist!");
        }
      })();
      return t.query(opts, function(err, results) {
        if (err) {
          return reject(err);
        }
        return resolve(logger.normalize(results));
      });
    });
  };

  logger.off = function() {
    return logger.removeAllListeners("logging");
  };

  logger.onLog = function(fn) {
    var name;
    name = "all";
    logger.off();
    return logger.on("logging", function(transport, level, msg, data) {
      var obj;
      if (transport.name === name) {
        obj = {
          level: level,
          message: msg
        };
        obj.type = data.type;
        obj.data = _.omit(data, "type");
        obj.timestamp = new Date;
        return fn(obj);
      }
    });
  };

  logger.clearLogs = function() {
    var files;
    files = _.map(logger.transports, function(value, key) {
      return fs.outputFileAsync(getPathToLog(key), "");
    });
    return Promise.all(files);
  };

  logger.log = _.wrap(logger.log, function() {
    var args, last, orig;
    orig = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
    last = _.last(args);
    if (_.isObject(last)) {
      _.defaults(last, {
        type: "server"
      });
    }
    return orig.apply(this, args);
  });

  process.removeAllListeners("unhandledRejection");

  process.on("unhandledRejection", function(err, promise) {
    logger.defaultErrorHandler(err);
    return false;
  });

  module.exports = logger;

}).call(this);

});
require.register("./lib/modes/ci.js",function (module, exports, require) {(function() {
  var Project, Promise, _, api, chalk, errors, git, headless, logException, logger, os, terminal, upload;

  _ = require("lodash");

  os = require("os");

  git = require("gift");

  chalk = require("chalk");

  Promise = require("bluebird");

  headless = require("./headless");

  api = require("../api");

  logger = require("../logger");

  errors = require("../errors");

  upload = require("../upload");

  Project = require("../project");

  terminal = require("../util/terminal");

  logException = function(err) {
    return logger.createException(err).timeout(1000)["catch"](function() {});
  };

  module.exports = {
    getBranchFromGit: function(repo) {
      return repo.branchAsync().get("name")["catch"](function() {
        return "";
      });
    },
    getMessage: function(repo) {
      return repo.current_commitAsync().get("message")["catch"](function() {
        return "";
      });
    },
    getEmail: function(repo) {
      return repo.current_commitAsync().get("author").get("email")["catch"](function() {
        return "";
      });
    },
    getAuthor: function(repo) {
      return repo.current_commitAsync().get("author").get("name")["catch"](function() {
        return "";
      });
    },
    getSha: function(repo) {
      return repo.current_commitAsync().get("id")["catch"](function() {
        return "";
      });
    },
    getBranch: function(repo) {
      var b, branch, i, len, ref;
      ref = ["CIRCLE_BRANCH", "TRAVIS_BRANCH", "CI_BRANCH"];
      for (i = 0, len = ref.length; i < len; i++) {
        branch = ref[i];
        if (b = process.env[branch]) {
          return Promise.resolve(b);
        }
      }
      return this.getBranchFromGit(repo);
    },
    generateProjectBuildId: function(projectId, projectPath, projectName, projectToken) {
      var repo;
      if (!projectToken) {
        return errors["throw"]("CI_KEY_MISSING");
      }
      repo = Promise.promisifyAll(git(projectPath));
      return Promise.props({
        sha: this.getSha(repo),
        branch: this.getBranch(repo),
        author: this.getAuthor(repo),
        email: this.getEmail(repo),
        message: this.getMessage(repo)
      }).then(function(git) {
        return api.createBuild({
          projectId: projectId,
          projectToken: projectToken,
          commitSha: git.sha,
          commitBranch: git.branch,
          commitAuthorName: git.author,
          commitAuthorEmail: git.email,
          commitMessage: git.message
        })["catch"](function(err) {
          switch (err.statusCode) {
            case 401:
              projectToken = projectToken.slice(0, 5) + "..." + projectToken.slice(-5);
              return errors["throw"]("CI_KEY_NOT_VALID", projectToken);
            case 404:
              return errors["throw"]("CI_PROJECT_NOT_FOUND");
            default:
              errors.warning("CI_CANNOT_CREATE_BUILD_OR_INSTANCE", err);
              return logException(err)["return"](null);
          }
        });
      });
    },
    createInstance: function(buildId, spec) {
      return api.createInstance({
        buildId: buildId,
        spec: spec
      })["catch"](function(err) {
        errors.warning("CI_CANNOT_CREATE_BUILD_OR_INSTANCE", err);
        if (err.statusCode !== 503) {
          return logException(err)["return"](null);
        } else {
          return null;
        }
      });
    },
    upload: function(options) {
      var count, nums, screenshotUrls, screenshots, send, uploads, video, videoUrl;
      if (options == null) {
        options = {};
      }
      video = options.video, screenshots = options.screenshots, videoUrl = options.videoUrl, screenshotUrls = options.screenshotUrls;
      uploads = [];
      count = 0;
      nums = function() {
        count += 1;
        return chalk.gray("(" + count + "/" + uploads.length + ")");
      };
      send = function(pathToFile, url) {
        var fail, success;
        success = function() {
          return console.log("  - Done Uploading " + (nums()), chalk.blue(pathToFile));
        };
        fail = function(err) {
          return console.log("  - Failed Uploading " + (nums()), chalk.red(pathToFile));
        };
        return uploads.push(upload(pathToFile, url).then(success)["catch"](fail));
      };
      if (videoUrl) {
        send(video, videoUrl);
      }
      if (screenshotUrls) {
        screenshotUrls.forEach(function(obj) {
          var screenshot;
          screenshot = _.find(screenshots, {
            clientId: obj.clientId
          });
          return send(screenshot.path, obj.uploadUrl);
        });
      }
      if (!uploads.length) {
        console.log("  - Nothing to Upload");
      }
      return Promise.all(uploads)["catch"](function(err) {
        errors.warning("CI_CANNOT_UPLOAD_ASSETS", err);
        return logException(err);
      });
    },
    uploadAssets: function(instanceId, stats) {
      var screenshots;
      console.log("");
      console.log("");
      terminal.header("Uploading Assets", {
        color: ["blue"]
      });
      console.log("");
      screenshots = _.map(stats.screenshots, function(screenshot) {
        return _.omit(screenshot, "path");
      });
      return api.updateInstance({
        instanceId: instanceId,
        tests: stats.tests,
        passes: stats.passes,
        failures: stats.failures,
        pending: stats.pending,
        duration: stats.duration,
        error: stats.error,
        video: !!stats.video,
        screenshots: screenshots,
        failingTests: stats.failingTests,
        cypressConfig: stats.config
      }).then((function(_this) {
        return function(resp) {
          if (resp == null) {
            resp = {};
          }
          return _this.upload({
            video: stats.video,
            screenshots: stats.screenshots,
            videoUrl: resp.videoUploadUrl,
            screenshotUrls: resp.screenshotUploadUrls
          });
        };
      })(this))["catch"](function(err) {
        errors.warning("CI_CANNOT_CREATE_BUILD_OR_INSTANCE", err);
        if (err.statusCode !== 503) {
          return logException(err);
        }
      });
    },
    run: function(options) {
      var projectPath;
      projectPath = options.projectPath;
      return Project.add(projectPath).then(function() {
        return Project.id(projectPath);
      }).then((function(_this) {
        return function(projectId) {
          return Project.config(projectPath).then(function(cfg) {
            var projectName;
            projectName = cfg.projectName;
            return _this.generateProjectBuildId(projectId, projectPath, projectName, options.key).then(function(buildId) {
              if (!buildId) {
                return;
              }
              return _this.createInstance(buildId, options.spec);
            }).then(function(instanceId) {
              options.ensureSession = false;
              options.allDone = false;
              return headless.run(options).then(function(stats) {
                if (stats == null) {
                  stats = {};
                }
                if (instanceId) {
                  return _this.uploadAssets(instanceId, stats)["return"](stats)["finally"](headless.allDone);
                } else {
                  return stats;
                }
              });
            });
          });
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/modes/exit.js",function (module, exports, require) {(function() {
  var Promise, _;

  _ = require("lodash");

  Promise = require("bluebird");

  module.exports = function(options) {
    return Promise["try"](function() {
      return _.toNumber(options.exitWithCode);
    });
  };

}).call(this);

});
require.register("./lib/modes/headed.js",function (module, exports, require) {(function() {
  var EE, Events, Position, Promise, Renderer, Updater, _, app, cyIcons, errors, image, logs, menu, os, user;

  _ = require("lodash");

  os = require("os");

  EE = require("events");

  app = require("electron").app;

  image = require("electron").nativeImage;

  Promise = require("bluebird");

  cyIcons = require("@cypress/core-icons");

  Position = require("electron-positioner");

  user = require("../user");

  errors = require("../errors");

  Updater = require("../updater");

  logs = require("../electron/handlers/logs");

  menu = require("../electron/handlers/menu");

  Events = require("../electron/handlers/events");

  Renderer = require("../electron/handlers/renderer");

  module.exports = {
    isMac: function() {
      return os.platform() === "darwin";
    },
    onWindowAllClosed: function(app) {
      return process.exit(0);
    },
    getRendererArgs: function() {
      var common;
      common = {
        backgroundColor: '#dfe2e4',
        width: 800,
        height: 550,
        minWidth: 458,
        minHeight: 400,
        type: "INDEX",
        onBlur: function() {
          if (this.webContents.isDevToolsOpened()) {
            return;
          }
          return Renderer.hideAllUnlessAnotherWindowIsFocused();
        },
        onFocus: function() {
          return Renderer.showAll();
        }
      };
      return _.extend(common, this.platformArgs());
    },
    platformArgs: function() {
      return {
        darwin: {
          show: true,
          frame: true,
          transparent: false
        },
        linux: {
          show: true,
          frame: true,
          transparent: false,
          icon: image.createFromPath(cyIcons.getPathToIcon("icon_128x128.png"))
        }
      }[os.platform()];
    },
    ready: function(options) {
      var bus;
      if (options == null) {
        options = {};
      }
      bus = new EE;
      menu.set({
        onUpdatesClicked: function() {
          return bus.emit("menu:item:clicked", "check:for:updates");
        },
        onLogOutClicked: function() {
          return bus.emit("menu:item:clicked", "log:out");
        }
      });
      return Renderer.create(this.getRendererArgs()).then((function(_this) {
        return function(win) {
          options.onFocusTests = function() {
            return win.focus();
          };
          Events.start(options, bus);
          if (options.updating) {
            Updater.install(options);
          }
          return win;
        };
      })(this));
    },
    run: function(options) {
      var waitForReady;
      app.on("window-all-closed", (function(_this) {
        return function() {
          return _this.onWindowAllClosed(app);
        };
      })(this));
      waitForReady = function() {
        return new Promise(function(resolve, reject) {
          return app.on("ready", resolve);
        });
      };
      return Promise.any([waitForReady(), Promise.delay(500)]).then((function(_this) {
        return function() {
          return _this.ready(options);
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/modes/headless.js",function (module, exports, require) {(function() {
  var Project, Promise, Renderer, Reporter, TITLE_SEPARATOR, _, automation, chalk, errors, fs, human, humanTime, inquirer, path, pkg, progress, project, random, ss, stats, terminal, trash, user, uuid, video;

  _ = require("lodash");

  fs = require("fs-extra");

  uuid = require("uuid");

  path = require("path");

  chalk = require("chalk");

  human = require("human-interval");

  Promise = require("bluebird");

  inquirer = require("inquirer");

  random = require("randomstring");

  ss = require("../screenshots");

  user = require("../user");

  stats = require("../stats");

  video = require("../video");

  errors = require("../errors");

  Project = require("../project");

  Reporter = require("../reporter");

  progress = require("../util/progress_bar");

  trash = require("../util/trash");

  terminal = require("../util/terminal");

  humanTime = require("../util/human_time");

  project = require("../electron/handlers/project");

  Renderer = require("../electron/handlers/renderer");

  automation = require("../electron/handlers/automation");

  pkg = require("../../package.json");

  fs = Promise.promisifyAll(fs);

  TITLE_SEPARATOR = " /// ";

  module.exports = {
    getId: function() {
      return random.generate({
        length: 5,
        capitalization: "lowercase"
      });
    },
    setProxy: function(proxyServer) {
      var session;
      session = require("electron").session;
      return new Promise(function(resolve) {
        return session.defaultSession.setProxy({
          proxyRules: proxyServer
        }, resolve);
      });
    },
    ensureAndOpenProjectByPath: function(id, options) {
      var open, projectPath;
      projectPath = options.projectPath;
      open = (function(_this) {
        return function() {
          return _this.openProject(id, options);
        };
      })(this);
      return Project.exists(projectPath).then((function(_this) {
        return function(bool) {
          if (bool) {
            return open();
          }
          console.log("Added this project:", chalk.cyan(projectPath));
          return Project.add(projectPath).then(open);
        };
      })(this));
    },
    openProject: function(id, options) {
      var ref;
      return project.open(options.projectPath, options, {
        sync: false,
        morgan: false,
        socketId: id,
        report: true,
        isHeadless: (ref = options.isHeadless) != null ? ref : true,
        onAutomationRequest: options.onAutomationRequest,
        afterAutomationRequest: options.afterAutomationRequest
      })["catch"]({
        portInUse: true
      }, function(err) {
        return errors["throw"]("PORT_IN_USE_LONG", err.port);
      });
    },
    createRecording: function(name) {
      var outputDir;
      outputDir = path.dirname(name);
      return fs.ensureDirAsync(outputDir).then(function() {
        console.log("\nStarted video recording: " + (chalk.cyan(name)) + "\n");
        return video.start(name, {
          onError: function(err) {
            return errors.warning("VIDEO_RECORDING_FAILED", err.stack);
          }
        });
      });
    },
    createRenderer: function(url, proxyServer, showGui, chromeWebSecurity, openProject, write) {
      return this.setProxy(proxyServer).then(function() {
        return Renderer.create({
          url: url,
          width: 1280,
          height: 720,
          show: showGui,
          frame: showGui,
          devTools: showGui,
          chromeWebSecurity: chromeWebSecurity,
          type: "PROJECT"
        });
      }).then(function(win) {
        var setFrameRate;
        setFrameRate = function(num) {
          if (win.webContents.getFrameRate() !== num) {
            return win.webContents.setFrameRate(num);
          }
        };
        if (write) {
          win.webContents.on("paint", function(event, dirty, image) {
            setFrameRate(20);
            return write(image.toJPEG(100));
          });
        }
        win.webContents.on("crashed", function(e, killed) {
          var err;
          err = errors.get("RENDERER_CRASHED");
          errors.log(err);
          return openProject.emit("exitEarlyWithErr", err.message);
        });
        win.webContents.on("new-window", function(e, url, frameName, disposition, options) {
          return options.show = false;
        });
        return win.center();
      });
    },
    displayStats: function(obj) {
      var bgColor, color;
      if (obj == null) {
        obj = {};
      }
      bgColor = obj.failures ? "bgRed" : "bgGreen";
      color = obj.failures ? "red" : "green";
      console.log("");
      terminal.header("Tests Finished", {
        color: [color]
      });
      console.log("");
      return stats.display(color, {
        tests: obj.tests,
        passes: obj.passes,
        pending: obj.pending,
        failures: obj.failures,
        duration: humanTime(obj.duration),
        screenshots: obj.screenshots && obj.screenshots.length,
        video: !!obj.video,
        version: pkg.version
      });
    },
    displayScreenshots: function(screenshots) {
      var format;
      if (screenshots == null) {
        screenshots = [];
      }
      console.log("");
      console.log("");
      terminal.header("Screenshots", {
        color: ["yellow"]
      });
      console.log("");
      format = function(s) {
        var dimensions;
        dimensions = chalk.gray("(" + s.width + "x" + s.height + ")");
        return "  - " + s.path + " " + dimensions;
      };
      return screenshots.forEach(function(screenshot) {
        return console.log(format(screenshot));
      });
    },
    postProcessRecording: function(end, name, cname, videoCompression) {
      return end().then(function() {
        var onProgress, started, tenSecs;
        console.log("");
        console.log("");
        terminal.header("Video", {
          color: ["cyan"]
        });
        console.log("");
        console.log("  - Started processing:  ", chalk.cyan("Compressing to " + videoCompression + " CRF"));
        started = new Date;
        progress = Date.now();
        tenSecs = human("10 seconds");
        onProgress = function(float) {
          var duration, finished, percentage;
          switch (false) {
            case float !== 1:
              finished = new Date - started;
              duration = "(" + (humanTime(finished)) + ")";
              return console.log("  - Finished processing: ", chalk.cyan(name), chalk.gray(duration));
            case !((new Date - progress) > tenSecs):
              progress += tenSecs;
              percentage = Math.ceil(float * 100) + "%";
              return console.log("  - Processing progress: ", chalk.cyan(percentage));
          }
        };
        return video.process(name, cname, videoCompression, onProgress);
      })["catch"]({
        recordingVideoFailed: true
      }, function(err) {})["catch"](function(err) {
        return errors.warning("VIDEO_POST_PROCESSING_FAILED", err.stack);
      });
    },
    closeAnyOpenBrowser: function() {
      return Promise.join(Renderer.destroy("PROJECT"), project.closeBrowser());
    },
    waitForRendererToConnect: function(options) {
      var attempts, browser, gui, id, launchRenderer, openProject, proxyServer, timeout, url, waitForRendererToConnect, webSecurity, write;
      if (options == null) {
        options = {};
      }
      openProject = options.openProject, id = options.id, browser = options.browser, url = options.url, proxyServer = options.proxyServer, gui = options.gui, webSecurity = options.webSecurity, write = options.write, timeout = options.timeout;
      gui = !!gui;
      launchRenderer = (function(_this) {
        return function() {
          if (browser) {
            return project.launch(browser, url, null, {
              proxyServer: proxyServer
            });
          } else {
            return _this.createRenderer(url, proxyServer, gui, webSecurity, openProject, write);
          }
        };
      })(this);
      attempts = 0;
      return (waitForRendererToConnect = (function(_this) {
        return function() {
          return Promise.join(_this.waitForSocketConnection(openProject, id), launchRenderer()).timeout(timeout != null ? timeout : 10000)["catch"](Promise.TimeoutError, function(err) {
            attempts += 1;
            console.log("");
            return _this.closeAnyOpenBrowser().then(function() {
              var word;
              switch (attempts) {
                case 1:
                case 2:
                  word = attempts === 1 ? "Retrying..." : "Retrying again...";
                  errors.warning("TESTS_DID_NOT_START_RETRYING", word);
                  return waitForRendererToConnect();
                default:
                  err = errors.get("TESTS_DID_NOT_START_FAILED");
                  errors.log(err);
                  return openProject.emit("exitEarlyWithErr", err.message);
              }
            });
          });
        };
      })(this))();
    },
    waitForSocketConnection: function(openProject, id) {
      return new Promise(function(resolve, reject) {
        var fn;
        fn = function(socketId) {
          if (socketId === id) {
            openProject.removeListener("socket:connected", fn);
            return resolve();
          }
        };
        return openProject.on("socket:connected", fn);
      });
    },
    waitForTestsToFinishRunning: function(options) {
      var cname, end, gui, name, openProject, screenshots, started, videoCompression;
      if (options == null) {
        options = {};
      }
      openProject = options.openProject, gui = options.gui, screenshots = options.screenshots, started = options.started, end = options.end, name = options.name, cname = options.cname, videoCompression = options.videoCompression;
      return new Promise((function(_this) {
        return function(resolve, reject) {
          var onEarlyExit, onEnd, onFinish;
          if (gui) {
            return;
          }
          onFinish = function(obj) {
            var finish, ft;
            finish = function() {
              return openProject.getConfig().then(function(cfg) {
                return obj.config = cfg;
              })["finally"](function() {
                return resolve(obj);
              });
            };
            if (end) {
              obj.video = name;
            }
            if (screenshots) {
              obj.screenshots = screenshots;
            }
            _this.displayStats(obj);
            if (screenshots && screenshots.length) {
              _this.displayScreenshots(screenshots);
            }
            ft = obj.failingTests;
            if (ft && ft.length) {
              obj.failingTests = Reporter.setVideoTimestamp(started, ft);
            }
            if (end) {
              return _this.postProcessRecording(end, name, cname, videoCompression).then(finish);
            } else {
              return finish();
            }
          };
          onEarlyExit = function(errMsg) {
            var obj;
            obj = {
              error: errors.stripAnsi(errMsg),
              failures: 1,
              tests: 0,
              passes: 0,
              pending: 0,
              duration: 0,
              failingTests: []
            };
            return onFinish(obj);
          };
          onEnd = function(obj) {
            return onFinish(obj);
          };
          openProject.once("end", onEnd);
          return openProject.once("exitEarlyWithErr", onEarlyExit);
        };
      })(this));
    },
    trashAssets: function(options) {
      if (options == null) {
        options = {};
      }
      if (options.trashAssetsBeforeHeadlessRuns === true) {
        return Promise.join(trash.folder(options.videosFolder), trash.folder(options.screenshotsFolder))["catch"](function(err) {
          return errors.warning("CANNOT_TRASH_ASSETS", err.stack);
        });
      } else {
        return Promise.resolve();
      }
    },
    screenshotMetadata: function(data, resp) {
      return {
        clientId: uuid.v4(),
        title: data.name,
        testId: data.testId,
        testTitle: data.titles.join(TITLE_SEPARATOR),
        path: resp.path,
        height: resp.height,
        width: resp.width
      };
    },
    copy: function(videosFolder, screenshotsFolder) {
      return Promise["try"](function() {
        var ca;
        if ((ca = process.env.CIRCLE_ARTIFACTS) && process.env["COPY_CIRCLE_ARTIFACTS"] !== "false") {
          return Promise.join(ss.copy(screenshotsFolder, ca), video.copy(videosFolder, ca));
        }
      });
    },
    allDone: function() {
      console.log("");
      console.log("");
      terminal.header("All Done", {
        color: ["gray"]
      });
      return console.log("");
    },
    runTests: function(options) {
      var browser, cname, id2, name, recording, videoRecording, videosFolder;
      if (options == null) {
        options = {};
      }
      browser = options.browser, videoRecording = options.videoRecording, videosFolder = options.videosFolder;
      if (videoRecording && !browser) {
        id2 = this.getId();
        name = path.join(videosFolder, id2 + ".mp4");
        cname = path.join(videosFolder, id2 + "-compressed.mp4");
        recording = this.createRecording(name);
      }
      return Promise.resolve(recording).then((function(_this) {
        return function(props) {
          var end, start, write;
          if (props == null) {
            props = {};
          }
          start = props.start, end = props.end, write = props.write;
          terminal.header("Tests Starting", {
            color: ["gray"]
          });
          return Promise.resolve(start).then(function(started) {
            return Promise.props({
              stats: _this.waitForTestsToFinishRunning({
                gui: options.gui,
                openProject: options.openProject,
                screenshots: options.screenshots,
                videoCompression: options.videoCompression,
                end: end,
                name: name,
                cname: cname,
                started: started
              }),
              connection: _this.waitForRendererToConnect({
                id: options.id,
                gui: options.gui,
                url: options.url,
                proxyServer: options.proxyServer,
                openProject: options.openProject,
                webSecurity: options.webSecurity,
                write: write,
                browser: browser
              })
            });
          });
        };
      })(this));
    },
    ready: function(options) {
      var id, screenshots, wantsExternalBrowser;
      if (options == null) {
        options = {};
      }
      id = this.getId();
      wantsExternalBrowser = !!options.browser;
      screenshots = [];
      options.onAutomationRequest = wantsExternalBrowser ? null : automation.perform;
      options.afterAutomationRequest = (function(_this) {
        return function(msg, data, resp) {
          if (msg === "take:screenshot") {
            screenshots.push(_this.screenshotMetadata(data, resp));
          }
          return resp;
        };
      })(this);
      return this.ensureAndOpenProjectByPath(id, options).then((function(_this) {
        return function(openProject) {
          return Promise.all([openProject.getConfig(), openProject.ensureSpecUrl(options.spec)]).spread(function(config, url) {
            return _this.trashAssets(config).then(function() {
              return _this.runTests({
                id: id,
                url: url,
                screenshots: screenshots,
                openProject: openProject,
                proxyServer: config.clientUrlDisplay,
                webSecurity: config.chromeWebSecurity,
                videosFolder: config.videosFolder,
                videoRecording: config.videoRecording,
                videoCompression: config.videoCompression,
                gui: options.showHeadlessGui,
                browser: options.browser
              });
            }).get("stats")["finally"](function() {
              return _this.copy(config.videosFolder, config.screenshotsFolder).then(function() {
                if (options.allDone !== false) {
                  return _this.allDone();
                }
              });
            });
          });
        };
      })(this));
    },
    run: function(options) {
      var app, waitForReady;
      app = require("electron").app;
      waitForReady = function() {
        return new Promise(function(resolve, reject) {
          return app.on("ready", resolve);
        });
      };
      return Promise.any([waitForReady(), Promise.delay(500)]).then((function(_this) {
        return function() {
          return _this.ready(options);
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/modes/pkg.js",function (module, exports, require) {(function() {
  var Promise, cwd, fs, path;

  fs = require("fs-extra");

  path = require("path");

  Promise = require("bluebird");

  cwd = require("../cwd");

  fs = Promise.promisifyAll(fs);

  module.exports = function() {
    return fs.readJsonAsync(cwd("package.json"));
  };

}).call(this);

});
require.register("./lib/modes/smoke_test.js",function (module, exports, require) {(function() {
  module.exports = function(options) {
    return Promise.resolve(options.pong);
  };

}).call(this);

});
require.register("./lib/project.js",function (module, exports, require) {(function() {
  var EE, Project, Promise, Reporter, Server, Watchers, _, api, cache, config, cwd, errors, fs, glob, ids, localCwd, logger, multipleForwardSlashesRe, path, savedState, scaffold, settings, user,
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  _ = require("lodash");

  fs = require("fs-extra");

  EE = require("events");

  path = require("path");

  glob = require("glob");

  Promise = require("bluebird");

  cwd = require("./cwd");

  ids = require("./ids");

  api = require("./api");

  user = require("./user");

  cache = require("./cache");

  config = require("./config");

  logger = require("./logger");

  errors = require("./errors");

  Server = require("./server");

  scaffold = require("./scaffold");

  Watchers = require("./watchers");

  Reporter = require("./reporter");

  savedState = require("./saved_state");

  settings = require("./util/settings");

  fs = Promise.promisifyAll(fs);

  glob = Promise.promisify(glob);

  localCwd = cwd();

  multipleForwardSlashesRe = /[^:\/\/](\/{2,})/g;

  Project = (function(superClass) {
    extend(Project, superClass);

    function Project(projectRoot) {
      if (!(this instanceof Project)) {
        return new Project(projectRoot);
      }
      if (!projectRoot) {
        throw new Error("Instantiating lib/project requires a projectRoot!");
      }
      this.projectRoot = path.resolve(projectRoot);
      this.watchers = Watchers();
      this.memoryCheck = null;
      this.server = Server(this.watchers);
    }

    Project.prototype.open = function(options) {
      var log;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        type: "opened",
        sync: false,
        report: false,
        onFocusTests: function() {},
        onSettingsChanged: false
      });
      if (process.env.CYPRESS_MEMORY) {
        log = function() {
          return console.log("memory info", process.memoryUsage());
        };
        this.memoryCheck = setInterval(log, 1000);
      }
      return this.getConfig(options).then((function(_this) {
        return function(cfg) {
          process.chdir(_this.projectRoot);
          return _this.server.open(cfg, _this).then(function(port) {
            if (!cfg.port) {
              cfg.port = port;
              _.extend(cfg, config.setUrls(cfg));
            }
            _this.cfg = cfg;
            options.onSavedStateChanged = function() {
              return _this._setSavedState(_this.cfg);
            };
            _this.sync(options);
            return Promise.join(_this.watchSettingsAndStartWebsockets(options, cfg), _this.scaffold(cfg)).then(function() {
              return _this.watchSupportFile(cfg);
            });
          });
        };
      })(this))["return"](this);
    };

    Project.prototype.sync = function(options) {
      return this.ensureProjectId().then((function(_this) {
        return function(id) {
          return _this.updateProject(id, options);
        };
      })(this))["catch"](function() {});
    };

    Project.prototype.close = function(options) {
      var ref, ref1;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        sync: false,
        type: "closed"
      });
      if (this.memoryCheck) {
        clearInterval(this.memoryCheck);
      }
      this.sync(options);
      this.removeAllListeners();
      return Promise.join((ref = this.server) != null ? ref.close() : void 0, (ref1 = this.watchers) != null ? ref1.close() : void 0).then(function() {
        return process.chdir(localCwd);
      });
    };

    Project.prototype.resetState = function() {
      return this.server.resetState();
    };

    Project.prototype.updateProject = function(id, options) {
      if (options == null) {
        options = {};
      }
      return Promise["try"]((function(_this) {
        return function() {
          if (!options.sync) {
            return;
          }
          return Promise.all([user.ensureSession(), _this.getConfig()]).spread(function(session, cfg) {
            return api.updateProject(id, options.type, cfg.projectName, session);
          });
        };
      })(this));
    };

    Project.prototype.watchSupportFile = function(config) {
      var relativePath, supportFile;
      if (supportFile = config.supportFile) {
        relativePath = path.relative(config.projectRoot, config.supportFile);
        return this.watchers.watchBundle(relativePath, config, {
          onChange: _.bind(this.server.onTestFileChange, this.server, relativePath)
        })["catch"](function() {});
      }
    };

    Project.prototype.watchSettings = function(onSettingsChanged) {
      var obj;
      if (!onSettingsChanged) {
        return;
      }
      obj = {
        onChange: (function(_this) {
          return function(filePath, stats) {
            if (_this.generatedProjectIdTimestamp && (new Date - _this.generatedProjectIdTimestamp) < 1000) {
              return;
            }
            return onSettingsChanged.call(_this);
          };
        })(this)
      };
      return this.watchers.watch(settings.pathToCypressJson(this.projectRoot), obj);
    };

    Project.prototype.watchSettingsAndStartWebsockets = function(options, config) {
      var reporter;
      if (options == null) {
        options = {};
      }
      if (config == null) {
        config = {};
      }
      this.watchSettings(options.onSettingsChanged);
      if (config.report) {
        reporter = Reporter.create(config.reporter, config.reporterOptions, config.projectRoot);
      }
      return this.server.startWebsockets(this.watchers, config, {
        onReloadBrowser: options.onReloadBrowser,
        onAutomationRequest: options.onAutomationRequest,
        afterAutomationRequest: options.afterAutomationRequest,
        onFocusTests: options.onFocusTests,
        onSpecChanged: options.onSpecChanged,
        onSavedStateChanged: options.onSavedStateChanged,
        onConnect: (function(_this) {
          return function(id) {
            return _this.emit("socket:connected", id);
          };
        })(this),
        onSetRunnables: function(runnables) {
          return reporter != null ? reporter.setRunnables(runnables) : void 0;
        },
        onMocha: (function(_this) {
          return function(event, runnable) {
            var stats;
            if (!reporter) {
              return;
            }
            reporter.emit(event, runnable);
            if (event === "end") {
              stats = reporter.stats();
              _this.server.end();
              return _this.emit("end", stats);
            }
          };
        })(this)
      });
    };

    Project.prototype.determineIsNewProject = function(integrationFolder) {
      var checkIfBothMatch, getCurrentSize, nameIsDefault;
      nameIsDefault = function(file) {
        return path.basename(file) === scaffold.integrationExampleName();
      };
      getCurrentSize = function(file) {
        return fs.statAsync(file).get("size");
      };
      checkIfBothMatch = function(current, scaffold) {
        return current === scaffold;
      };
      return glob("**/*", {
        cwd: integrationFolder,
        realpath: true
      }).then(function(files) {
        var def, exampleSpec;
        if (files.length === 0) {
          return true;
        }
        if (files.length !== 1) {
          return false;
        }
        exampleSpec = files[0];
        if (!(def = nameIsDefault(exampleSpec))) {
          return false;
        }
        return Promise.join(getCurrentSize(exampleSpec), scaffold.integrationExampleSize(), checkIfBothMatch);
      });
    };

    Project.prototype.changeToUrl = function(url) {
      return this.server.changeToUrl(url);
    };

    Project.prototype.setBrowsers = function(browsers) {
      if (browsers == null) {
        browsers = [];
      }
      return this.getConfig().then(function(cfg) {
        return cfg.browsers = browsers;
      });
    };

    Project.prototype.getConfig = function(options) {
      var getConfig;
      if (options == null) {
        options = {};
      }
      getConfig = (function(_this) {
        return function() {
          var c;
          if (c = _this.cfg) {
            return Promise.resolve(c);
          } else {
            return config.get(_this.projectRoot, options).then(function(cfg) {
              return _this.determineIsNewProject(cfg.integrationFolder).then(function(bool) {
                return cfg.isNewProject = bool;
              })["return"](cfg);
            });
          }
        };
      })(this);
      return getConfig().then((function(_this) {
        return function(cfg) {
          return _this._setSavedState(cfg);
        };
      })(this));
    };

    Project.prototype._setSavedState = function(cfg) {
      return savedState.get().then(function(state) {
        cfg.state = state;
        return cfg;
      });
    };

    Project.prototype.ensureSpecUrl = function(spec) {
      return this.getConfig().then((function(_this) {
        return function(cfg) {
          if (spec) {
            return _this.ensureSpecExists(spec).then(function(pathToSpec) {
              var prefixedPath;
              prefixedPath = _this.getPrefixedPathToSpec(cfg.integrationFolder, pathToSpec);
              return _this.getUrlBySpec(cfg.clientUrl, prefixedPath);
            });
          } else {
            return _this.getUrlBySpec(cfg.clientUrl, "/__all");
          }
        };
      })(this));
    };

    Project.prototype.ensureSpecExists = function(spec) {
      var specFile;
      specFile = path.resolve(this.projectRoot, spec);
      return fs.statAsync(specFile)["return"](specFile)["catch"](function() {
        return errors["throw"]("SPEC_FILE_NOT_FOUND", specFile);
      });
    };

    Project.prototype.getPrefixedPathToSpec = function(integrationFolder, pathToSpec) {
      return "/" + path.join("integration", path.relative(integrationFolder, pathToSpec));
    };

    Project.prototype.getUrlBySpec = function(clientUrl, specUrl) {
      var replacer;
      replacer = function(match, p1) {
        return match.replace("//", "/");
      };
      return [clientUrl, "#/tests", specUrl].join("/").replace(multipleForwardSlashesRe, replacer);
    };

    Project.prototype.scaffold = function(config) {
      var push, scaffolds;
      scaffolds = [];
      push = scaffolds.push.bind(scaffolds);
      push(scaffold.support(config.supportFolder, config));
      if (!config.isHeadless) {
        push(scaffold.integration(config.integrationFolder));
        push(scaffold.fixture(config.fixturesFolder));
      }
      return Promise.all(scaffolds);
    };

    Project.prototype.writeProjectId = function(id) {
      var attrs;
      attrs = {
        projectId: id
      };
      logger.info("Writing Project ID", _.clone(attrs));
      this.generatedProjectIdTimestamp = new Date;
      return settings.write(this.projectRoot, attrs)["return"](id);
    };

    Project.prototype.createProjectId = function() {
      var id;
      if (id = process.env.CYPRESS_PROJECT_ID) {
        return this.writeProjectId(id);
      }
      return Promise.all([user.ensureSession(), this.getConfig()]).bind(this).spread(function(session, cfg) {
        return api.createProject(cfg.projectName, session);
      }).then(this.writeProjectId);
    };

    Project.prototype.getProjectId = function() {
      return this.verifyExistence().then((function(_this) {
        return function() {
          var id;
          if (id = process.env.CYPRESS_PROJECT_ID) {
            return {
              projectId: id
            };
          } else {
            return settings.read(_this.projectRoot);
          }
        };
      })(this)).then((function(_this) {
        return function(settings) {
          var id;
          if (settings && (id = settings.projectId)) {
            return id;
          }
          return errors["throw"]("NO_PROJECT_ID", _this.projectRoot);
        };
      })(this));
    };

    Project.prototype.verifyExistence = function() {
      return fs.statAsync(this.projectRoot)["return"](this)["catch"]((function(_this) {
        return function() {
          return errors["throw"]("NO_PROJECT_FOUND_AT_PROJECT_ROOT", _this.projectRoot);
        };
      })(this));
    };

    Project.prototype.ensureProjectId = function() {
      return this.getProjectId().bind(this)["catch"]({
        type: "NO_PROJECT_ID"
      }, this.createProjectId);
    };

    Project.paths = function() {
      return cache.getProjectPaths();
    };

    Project.remove = function(path) {
      return cache.removeProject(path);
    };

    Project.add = function(path) {
      return cache.insertProject(path);
    };

    Project.removeIds = function(p) {
      return Project(p).verifyExistence().call("getConfig").then(function(cfg) {
        return ids.remove(cfg.integrationFolder);
      });
    };

    Project.id = function(path) {
      return Project(path).getProjectId();
    };

    Project.exists = function(path) {
      return this.paths().then(function(paths) {
        return indexOf.call(paths, path) >= 0;
      });
    };

    Project.config = function(path) {
      return Project(path).getConfig();
    };

    Project.getSecretKeyByPath = function(path) {
      return Project.id(path).then(function(id) {
        return user.ensureSession().then(function(session) {
          return api.getProjectToken(id, session)["catch"](function() {
            return errors["throw"]("CANNOT_FETCH_PROJECT_TOKEN");
          });
        });
      });
    };

    Project.generateSecretKeyByPath = function(path) {
      return Project.id(path).then(function(id) {
        return user.ensureSession().then(function(session) {
          return api.updateProjectToken(id, session)["catch"](function() {
            return errors["throw"]("CANNOT_CREATE_PROJECT_TOKEN");
          });
        });
      });
    };

    return Project;

  })(EE);

  module.exports = Project;

}).call(this);

});
require.register("./lib/reporter.js",function (module, exports, require) {(function() {
  var Mocha, Reporter, STATS, _, chalk, createRunnable, createSuite, events, mergeErr, mergeRunnable, mochaReporters, path, reporters, safelyMergeRunnable,
    slice = [].slice;

  _ = require("lodash");

  Mocha = require("mocha");

  chalk = require("chalk");

  path = require("path");

  mochaReporters = require("mocha/lib/reporters");

  STATS = "suites tests passes pending failures start end duration".split(" ");

  createSuite = function(obj, parent) {
    var suite;
    suite = new Mocha.Suite(obj.title, {});
    if (parent) {
      suite.parent = parent;
    }
    if (obj.file) {
      console.log('has file:', obj.file);
    }
    suite.file = obj.file;
    return suite;
  };

  createRunnable = function(obj, parent) {
    var body, fn, runnable;
    body = obj.body;
    if (body) {
      fn = function() {};
      fn.toString = function() {
        return body;
      };
    }
    runnable = new Mocha.Test(obj.title, fn);
    runnable.timedOut = obj.timedOut;
    runnable.async = obj.async;
    runnable.sync = obj.sync;
    runnable.duration = obj.duration;
    runnable.state = obj.state;
    if (runnable.body == null) {
      runnable.body = body;
    }
    if (parent) {
      runnable.parent = parent;
    }
    return runnable;
  };

  mergeRunnable = function(testProps, runnables) {
    var runnable;
    runnable = runnables[testProps.id];
    if (!runnable.started) {
      testProps.started = Date.now();
    }
    return _.extend(runnable, testProps);
  };

  safelyMergeRunnable = function(testProps, runnables) {
    return _.extend({}, runnables[testProps.id], testProps);
  };

  mergeErr = function(test, runnables) {
    var runnable;
    runnable = runnables[test.id];
    runnable.err = test.err;
    runnable.state = "failed";
    if (runnable.duration == null) {
      runnable.duration = test.duration;
    }
    runnable = _.extend({}, runnable, {
      title: test.title
    });
    return [runnable, test.err];
  };

  events = {
    "start": true,
    "end": true,
    "suite": mergeRunnable,
    "suite end": mergeRunnable,
    "test": mergeRunnable,
    "test end": mergeRunnable,
    "hook": safelyMergeRunnable,
    "hook end": safelyMergeRunnable,
    "pass": mergeRunnable,
    "pending": mergeRunnable,
    "fail": mergeErr
  };

  reporters = {
    teamcity: "mocha-teamcity-reporter",
    junit: "mocha-junit-reporter"
  };

  Reporter = (function() {
    function Reporter(reporterName, reporterOptions, projectRoot) {
      if (reporterName == null) {
        reporterName = "spec";
      }
      if (reporterOptions == null) {
        reporterOptions = {};
      }
      if (!(this instanceof Reporter)) {
        return new Reporter(reporterName);
      }
      this.reporterName = reporterName;
      this.projectRoot = projectRoot;
      this.reporterOptions = reporterOptions;
    }

    Reporter.prototype.setRunnables = function(rootRunnable) {
      var err, r, reporter;
      if (rootRunnable == null) {
        rootRunnable = {};
      }
      this.runnables = {};
      rootRunnable = this._createRunnable(rootRunnable, "suite");
      if (r = reporters[this.reporterName]) {
        reporter = require(r);
      } else if (r = mochaReporters[this.reporterName]) {
        reporter = this.reporterName;
      } else {
        try {
          reporter = require(path.join(this.projectRoot, this.reporterName));
        } catch (error) {
          err = error;
          reporter = require(path.join(this.projectRoot, "node_modules", this.reporterName));
        }
      }
      this.mocha = new Mocha({
        reporter: reporter
      });
      this.mocha.suite = rootRunnable;
      this.runner = new Mocha.Runner(rootRunnable);
      this.reporter = new this.mocha._reporter(this.runner, {
        reporterOptions: this.reporterOptions
      });
      return this.runner.ignoreLeaks = true;
    };

    Reporter.prototype._createRunnable = function(runnableProps, type, parent) {
      var runnable, suite;
      runnable = (function() {
        switch (type) {
          case "suite":
            suite = createSuite(runnableProps, parent);
            suite.tests = _.map(runnableProps.tests, (function(_this) {
              return function(testProps) {
                return _this._createRunnable(testProps, "test", suite);
              };
            })(this));
            suite.suites = _.map(runnableProps.suites, (function(_this) {
              return function(suiteProps) {
                return _this._createRunnable(suiteProps, "suite", suite);
              };
            })(this));
            return suite;
          case "test":
            return createRunnable(runnableProps, parent);
          default:
            throw new Error("Unknown runnable type: '" + type + "'");
        }
      }).call(this);
      this.runnables[runnableProps.id] = runnable;
      return runnable;
    };

    Reporter.prototype.emit = function() {
      var args, event;
      event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (args = this.parseArgs(event, args)) {
        return this.runner.emit.apply(this.runner, args);
      }
    };

    Reporter.prototype.parseArgs = function(event, args) {
      var e;
      if (e = events[event]) {
        if (_.isFunction(e)) {
          args = e.apply(this, args.concat(this.runnables));
        }
        return [event].concat(args);
      }
    };

    Reporter.prototype.normalize = function(test) {
      var err, getParentTitle, ref, titles;
      if (test == null) {
        test = {};
      }
      getParentTitle = function(runnable, titles) {
        var p, t;
        if (p = runnable.parent) {
          if (t = p.title) {
            titles.unshift(t);
          }
          return getParentTitle(p, titles);
        } else {
          return titles;
        }
      };
      err = (ref = test.err) != null ? ref : {};
      titles = [test.title];
      return {
        clientId: test.id,
        title: getParentTitle(test, titles).join(" /// "),
        duration: test.duration,
        stack: err.stack,
        error: err.message,
        started: test.started
      };
    };

    Reporter.prototype.stats = function() {
      var failingTests;
      failingTests = _.chain(this.runnables).filter({
        state: "failed"
      }).map(this.normalize).value();
      return _.extend({
        reporter: this.reporterName,
        failingTests: failingTests
      }, _.pick(this.reporter.stats, STATS));
    };

    Reporter.setVideoTimestamp = function(videoStart, tests) {
      if (tests == null) {
        tests = [];
      }
      return _.map(tests, function(test) {
        test.videoTimestamp = test.started - videoStart;
        return test;
      });
    };

    Reporter.create = function(reporterName, reporterOptions, projectRoot) {
      return new Reporter(reporterName, reporterOptions, projectRoot);
    };

    return Reporter;

  })();

  module.exports = Reporter;

}).call(this);

});
require.register("./lib/request.js",function (module, exports, require) {(function() {
  var Cookie, CookieJar, Promise, _, automation, createCookieString, extension, flattenCookies, getOriginalHeaders, moment, newCookieJar, pick, r, reduceCookieToArray, rp, statusCode, tough, url;

  _ = require("lodash");

  r = require("request");

  rp = require("request-promise");

  url = require("url");

  tough = require("tough-cookie");

  moment = require("moment");

  Promise = require("bluebird");

  extension = require("@cypress/core-extension");

  automation = require("./automation");

  statusCode = require("./util/status_code");

  Cookie = tough.Cookie;

  CookieJar = tough.CookieJar;

  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

  getOriginalHeaders = function(req) {
    var ref, ref1;
    if (req == null) {
      req = {};
    }
    return (ref = (ref1 = req.req) != null ? ref1.headers : void 0) != null ? ref : req.headers;
  };

  pick = function(resp) {
    var headers, ref, ref1, ref2, req;
    if (resp == null) {
      resp = {};
    }
    req = (ref = resp.request) != null ? ref : {};
    headers = getOriginalHeaders(req);
    return {
      "Request Body": (ref1 = req.body) != null ? ref1 : null,
      "Request Headers": headers,
      "Request URL": req.href,
      "Response Body": (ref2 = resp.body) != null ? ref2 : null,
      "Response Headers": resp.headers,
      "Response Status": resp.statusCode
    };
  };

  newCookieJar = function() {
    var j;
    j = new CookieJar(void 0, {
      looseMode: true
    });
    return {
      _jar: j,
      toJSON: function() {
        return j.toJSON();
      },
      setCookie: function(cookieOrStr, uri, options) {
        return j.setCookieSync(cookieOrStr, uri, options);
      },
      getCookieString: function(uri) {
        return j.getCookieStringSync(uri, {
          expire: false
        });
      },
      getCookies: function(uri) {
        return j.getCookiesSync(uri, {
          expire: false
        });
      }
    };
  };

  flattenCookies = function(cookies) {
    return _.reduce(cookies, function(memo, cookie) {
      memo[cookie.name] = cookie.value;
      return memo;
    }, {});
  };

  reduceCookieToArray = function(c) {
    return _.reduce(c, function(memo, val, key) {
      memo.push([key.trim(), val.trim()].join("="));
      return memo;
    }, []);
  };

  createCookieString = function(c) {
    return reduceCookieToArray(c).join("; ");
  };

  module.exports = function(options) {
    var defaults, ref;
    if (options == null) {
      options = {};
    }
    defaults = {
      timeout: (ref = options.timeout) != null ? ref : 20000
    };
    r = r.defaults(defaults);
    rp = rp.defaults(defaults);
    return {
      r: require("request"),
      rp: require("request-promise"),
      reduceCookieToArray: reduceCookieToArray,
      createCookieString: createCookieString,
      create: function(strOrOpts, promise) {
        var opts, p;
        switch (false) {
          case !_.isString(strOrOpts):
            opts = {
              url: strOrOpts
            };
            break;
          default:
            opts = strOrOpts;
        }
        opts.url = url.parse(opts.url);
        if (p = opts.url.port) {
          opts.url.port = _.toNumber(p);
        }
        if (promise) {
          return rp(opts);
        } else {
          return r(opts);
        }
      },
      contentTypeIsJson: function(response) {
        var ref1, ref2;
        return response != null ? (ref1 = response.headers) != null ? (ref2 = ref1["content-type"]) != null ? ref2.includes("application/json") : void 0 : void 0 : void 0;
      },
      parseJsonBody: function(body) {
        var e;
        try {
          return JSON.parse(body);
        } catch (error) {
          e = error;
          return body;
        }
      },
      normalizeResponse: function(push, response) {
        var ref1, req;
        req = (ref1 = response.request) != null ? ref1 : {};
        push(response);
        response = _.pick(response, "statusCode", "body", "headers");
        response.status = response.statusCode;
        delete response.statusCode;
        _.extend(response, {
          statusText: statusCode.getText(response.status),
          isOkStatusCode: statusCode.isOk(response.status),
          requestHeaders: getOriginalHeaders(req),
          requestBody: req.body
        });
        if (_.isString(response.body) && this.contentTypeIsJson(response)) {
          response.body = this.parseJsonBody(response.body);
        }
        return response;
      },
      setJarCookies: function(jar, automationFn) {
        var setCookie;
        setCookie = function(cookie) {
          var ex, ho;
          cookie.name = cookie.key;
          if (cookie.name && cookie.name.startsWith("__cypress")) {
            return;
          }
          cookie.url = extension.getCookieUrl(cookie);
          if (ho = cookie.hostOnly) {
            cookie = _.omit(cookie, "domain");
          }
          switch (false) {
            case cookie.maxAge == null:
              cookie.expiry = moment().unix() + cookie.maxAge;
              break;
            case !(ex = cookie.expires):
              cookie.expiry = moment(ex).unix();
          }
          return automationFn("set:cookie", cookie).then(function() {
            return automation.normalizeCookieProps(cookie);
          });
        };
        return Promise["try"](function() {
          var store;
          store = jar.toJSON();
          return Promise.each(store.cookies, setCookie);
        });
      },
      sendStream: function(headers, automation, options) {
        var send, setCookies, ua;
        if (options == null) {
          options = {};
        }
        _.defaults(options, {
          headers: {},
          jar: true
        });
        if (ua = headers["user-agent"]) {
          options.headers["user-agent"] = ua;
        }
        if (options.jar === true) {
          options.jar = newCookieJar();
        }
        _.extend(options, {
          strictSSL: false
        });
        setCookies = (function(_this) {
          return function(cookies) {
            if (_.isEmpty(cookies)) {
              return;
            }
            return options.headers["Cookie"] = createCookieString(cookies);
          };
        })(this);
        send = (function(_this) {
          return function() {
            var str;
            str = _this.create(options);
            str.getJar = function() {
              return options.jar;
            };
            return str;
          };
        })(this);
        return automation("get:cookies", {
          url: options.url
        }).then(flattenCookies).then(setCookies).then(send);
      },
      send: function(headers, automation, options) {
        var a, c, send, setCookies, ua;
        if (options == null) {
          options = {};
        }
        _.defaults(options, {
          headers: {},
          gzip: true,
          jar: true,
          cookies: true,
          followRedirect: true
        });
        if (ua = headers["user-agent"]) {
          options.headers["user-agent"] = ua;
        }
        if (a = options.headers.Accept) {
          delete options.headers.Accept;
          options.headers.accept = a;
        }
        _.defaults(options.headers, {
          accept: "*/*"
        });
        if (options.jar === true) {
          options.jar = newCookieJar();
        }
        _.extend(options, {
          strictSSL: false,
          simple: false,
          resolveWithFullResponse: true
        });
        options.followAllRedirects = options.followRedirect;
        if (options.form === true) {
          options.form = options.body;
          delete options.json;
          delete options.body;
        }
        setCookies = (function(_this) {
          return function(cookies) {
            if (_.isEmpty(cookies)) {
              return;
            }
            return options.headers["Cookie"] = createCookieString(cookies);
          };
        })(this);
        send = (function(_this) {
          return function() {
            var ms, normalizeUrl, push, redirects, requestResponses;
            ms = Date.now();
            redirects = [];
            requestResponses = [];
            push = function(response) {
              return requestResponses.push(pick(response));
            };
            normalizeUrl = function(loc) {
              return url.resolve(options.url, loc);
            };
            if (options.followRedirect) {
              options.followRedirect = function(incomingRes) {
                var newUrl;
                newUrl = normalizeUrl(incomingRes.headers.location);
                redirects.push([incomingRes.statusCode, newUrl].join(": "));
                push(incomingRes);
                return true;
              };
            }
            return _this.create(options, true).then(_this.normalizeResponse.bind(_this, push)).then(function(resp) {
              var loc;
              resp.duration = Date.now() - ms;
              resp.allRequestResponses = requestResponses;
              if (redirects.length) {
                resp.redirects = redirects;
              }
              if (options.followRedirect === false && (loc = resp.headers.location)) {
                resp.redirectedToUrl = normalizeUrl(loc);
              }
              if (options.jar) {
                return _this.setJarCookies(options.jar, automation)["return"](resp);
              } else {
                return resp;
              }
            });
          };
        })(this);
        if (c = options.cookies) {
          if (_.isObject(c)) {
            setCookies(c);
            return send();
          } else {
            return automation("get:cookies", {
              url: options.url
            }).then(flattenCookies).then(setCookies).then(send);
          }
        } else {
          return send();
        }
      }
    };
  };

}).call(this);

});
require.register("./lib/routes.js",function (module, exports, require) {(function() {
  var CacheBuster, builds, client, cwd, errors, files, logger, path, proxy, runner, spec, xhrs;

  path = require("path");

  CacheBuster = require("./util/cache_buster");

  cwd = require("./cwd");

  logger = require("./logger");

  spec = require("./controllers/spec");

  errors = require("./controllers/errors");

  runner = require("./controllers/runner");

  xhrs = require("./controllers/xhrs");

  client = require("./controllers/client");

  files = require("./controllers/files");

  proxy = require("./controllers/proxy");

  builds = require("./controllers/builds");

  module.exports = function(app, config, request, getRemoteState, watchers, project) {
    app.get("/__cypress/tests", function(req, res, next) {
      var test;
      test = CacheBuster.strip(req.query.p);
      return spec.handle(test, req, res, config, next, watchers, project);
    });
    app.get("/__cypress/errors/:error", function(req, res) {
      return errors.handle(req, res, config);
    });
    app.get("/__cypress/socket.io.js", function(req, res) {
      return client.handle(req, res);
    });
    app.get("/__cypress/runner/*", function(req, res) {
      return runner.handle(req, res);
    });
    app.get("/__cypress/files", function(req, res) {
      return files.handleFiles(req, res, config);
    });
    app.get("/__cypress/iframes/*", function(req, res) {
      return files.handleIframe(req, res, config, getRemoteState);
    });
    app.get("/__cypress/builds", function(req, res, next) {
      return builds.handleBuilds(req, res, config, next);
    });
    app.all("/__cypress/xhrs/*", function(req, res, next) {
      return xhrs.handle(req, res, config, next);
    });
    app.get("/__root/*", function(req, res, next) {
      var file;
      file = path.join(config.projectRoot, req.params[0]);
      return res.sendFile(file, {
        etag: false
      });
    });
    app.get(config.clientRoute, function(req, res) {
      return runner.serve(req, res, config, getRemoteState);
    });
    app.all("*", function(req, res, next) {
      return proxy.handle(req, res, config, getRemoteState, request);
    });
    return app.use(function(err, req, res, next) {
      console.log(err.stack);
      res.set("x-cypress-error", err.message);
      res.set("x-cypress-stack", JSON.stringify(err.stack));
      return res.sendStatus(500);
    });
  };

}).call(this);

});
require.register("./lib/saved_state.js",function (module, exports, require) {(function() {
  var Conf, Promise, appData, config;

  Conf = require("conf");

  Promise = require("bluebird");

  appData = require("./util/app_data");

  config = new Conf({
    configName: "state",
    cwd: appData.path()
  });

  module.exports = {
    get: function(key) {
      return Promise["try"](function() {
        return config.get(key);
      });
    },
    set: function(state) {
      return Promise["try"](function() {
        return config.set(state);
      });
    },
    path: config.path
  };

}).call(this);

});
require.register("./lib/scaffold.js",function (module, exports, require) {(function() {
  var INTEGRATION_EXAMPLE_SPEC, Promise, _, cwd, cypressEx, fs, glob, hbs, path;

  _ = require("lodash");

  fs = require("fs-extra");

  Promise = require("bluebird");

  path = require("path");

  cypressEx = require("@cypress/core-example");

  glob = require("glob");

  hbs = require("hbs");

  cwd = require("./cwd");

  glob = Promise.promisify(glob);

  fs = Promise.promisifyAll(fs);

  INTEGRATION_EXAMPLE_SPEC = cypressEx.getPathToExample();

  module.exports = {
    integration: function(folder) {
      return this.verifyScaffolding(folder, (function(_this) {
        return function() {
          return _this.copy(INTEGRATION_EXAMPLE_SPEC, folder);
        };
      })(this));
    },
    fixture: function(folder) {
      return this.verifyScaffolding(folder, (function(_this) {
        return function() {
          return _this.copy("example.json", folder);
        };
      })(this));
    },
    support: function(folder, config) {
      if (config.resolved.supportFile.from !== "default") {
        return Promise.resolve();
      }
      return this.verifyScaffolding(folder, (function(_this) {
        return function() {
          return Promise.join(_this.copy("defaults.js", folder), _this.copy("commands.js", folder));
        };
      })(this)).then(function() {
        var err;
        try {
          return require.resolve(config.supportFile);
        } catch (error) {
          err = error;
          if (err.code !== 'MODULE_NOT_FOUND') {
            throw err;
          }
          return Promise.join(fs.readFileAsync(cwd("lib", "scaffold", "index.js.hbs"), "utf8"), glob(path.join(folder, "**", "*"), {
            nodir: true
          }).map(function(filePath) {
            var ext;
            ext = path.extname(filePath);
            filePath = filePath.replace(ext, "");
            return path.relative(config.supportFolder, filePath);
          })).spread(function(indexTemplate, supportFiles) {
            var contents;
            indexTemplate = hbs.handlebars.compile(indexTemplate);
            contents = indexTemplate({
              files: supportFiles
            });
            return fs.outputFileAsync(path.join(folder, "index.js"), contents);
          });
        }
      });
    },
    copy: function(file, folder) {
      var dest, src;
      src = path.resolve(cwd("lib", "scaffold"), file);
      dest = path.join(folder, path.basename(file));
      return fs.copyAsync(src, dest);
    },
    integrationExampleSize: function() {
      return fs.statAsync(INTEGRATION_EXAMPLE_SPEC).get("size");
    },
    integrationExampleName: function() {
      return path.basename(INTEGRATION_EXAMPLE_SPEC);
    },
    verifyScaffolding: function(folder, fn) {
      return fs.statAsync(folder)["catch"]((function(_this) {
        return function() {
          return fn.call(_this);
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/screenshots.js",function (module, exports, require) {(function() {
  var Promise, RUNNABLE_SEPARATOR, bytes, dataUriToBuffer, fs, glob, invalidCharsRe, mime, path, sizeOf;

  fs = require("fs-extra");

  mime = require("mime");

  path = require("path");

  glob = require("glob");

  bytes = require("bytes");

  sizeOf = require("image-size");

  Promise = require("bluebird");

  dataUriToBuffer = require("data-uri-to-buffer");

  fs = Promise.promisifyAll(fs);

  glob = Promise.promisify(glob);

  RUNNABLE_SEPARATOR = " -- ";

  invalidCharsRe = /[^0-9a-zA-Z-_\s]/g;

  module.exports = {
    copy: function(src, dest) {
      return fs.copyAsync(src, dest, {
        clobber: true
      })["catch"]({
        code: "ENOENT"
      }, function() {});
    },
    get: function(screenshotsFolder) {
      screenshotsFolder = path.join(screenshotsFolder, "**", "*");
      return glob(screenshotsFolder, {
        nodir: true
      });
    },
    take: function(data, dataUrl, screenshotsFolder) {
      var buffer, name, pathToScreenshot, ref;
      buffer = dataUriToBuffer(dataUrl);
      name = (ref = data.name) != null ? ref : data.titles.join(RUNNABLE_SEPARATOR);
      name = name.replace(invalidCharsRe, "");
      name = [name, mime.extension(buffer.type)].join(".");
      pathToScreenshot = path.join(screenshotsFolder, name);
      return fs.outputFileAsync(pathToScreenshot, buffer).then(function() {
        return fs.statAsync(pathToScreenshot).get("size");
      }).then(function(size) {
        var dimensions;
        dimensions = sizeOf(buffer);
        return {
          size: bytes(size, {
            unitSeparator: " "
          }),
          path: pathToScreenshot,
          width: dimensions.width,
          height: dimensions.height
        };
      });
    }
  };

}).call(this);

});
require.register("./lib/server.js",function (module, exports, require) {(function() {
  var DEFAULT_DOMAIN_NAME, Promise, Request, Server, Socket, _, allowDestroy, appData, buffers, cookie, cors, cwd, errors, evilDns, express, fileServer, fullyQualifiedRe, hbs, headersUtil, http, httpProxy, httpsProxy, logger, setProxiedUrl, statusCode, stream, url;

  _ = require("underscore");

  hbs = require("hbs");

  url = require("url");

  http = require("http");

  cookie = require("cookie");

  stream = require("stream");

  express = require("express");

  Promise = require("bluebird");

  evilDns = require("evil-dns");

  httpProxy = require("http-proxy");

  httpsProxy = require("@cypress/core-https-proxy");

  allowDestroy = require("server-destroy-vvo");

  cors = require("./util/cors");

  headersUtil = require("./util/headers");

  appData = require("./util/app_data");

  buffers = require("./util/buffers");

  statusCode = require("./util/status_code");

  cwd = require("./cwd");

  errors = require("./errors");

  logger = require("./logger");

  Socket = require("./socket");

  Request = require("./request");

  fileServer = require("./file_server");

  DEFAULT_DOMAIN_NAME = "localhost";

  fullyQualifiedRe = /^https?:\/\//;

  setProxiedUrl = function(req) {
    if (req.proxiedUrl) {
      return;
    }
    req.proxiedUrl = req.url;
    logger.info("Setting proxied url", {
      proxiedUrl: req.proxiedUrl
    });
    return req.url = url.parse(req.url).path;
  };

  Server = (function() {
    function Server(watchers) {
      if (!(this instanceof Server)) {
        return new Server(watchers);
      }
      this.watchers = watchers;
      this._request = null;
      this._middleware = null;
      this._server = null;
      this._socket = null;
      this._wsProxy = null;
      this._fileServer = null;
      this._httpsProxy = null;
    }

    Server.prototype.createExpressApp = function(morgan) {
      var app;
      app = express();
      app.set("view engine", "html");
      app.engine("html", hbs.__express);
      app.use((function(_this) {
        return function(req, res, next) {
          var m;
          setProxiedUrl(req);
          if (m = _this._middleware) {
            m(req, res);
          }
          return next();
        };
      })(this));
      app.use(require("cookie-parser")());
      app.use(require("compression")());
      if (morgan) {
        app.use(require("morgan")("dev"));
      }
      app.use("/__cypress/static", express["static"](cwd("lib", "public")));
      app.use(require("errorhandler")());
      app.disable("x-powered-by");
      return app;
    };

    Server.prototype.createRoutes = function() {
      return require("./routes").apply(null, arguments);
    };

    Server.prototype.getHttpServer = function() {
      return this._server;
    };

    Server.prototype.portInUseErr = function(port) {
      var e;
      e = errors.get("PORT_IN_USE_SHORT", port);
      e.port = port;
      e.portInUse = true;
      return e;
    };

    Server.prototype.resetState = function() {
      buffers.reset();
      if (this._remoteProps) {
        return this._onDomainSet("<root>");
      }
    };

    Server.prototype.open = function(config, project) {
      if (config == null) {
        config = {};
      }
      return Promise["try"]((function(_this) {
        return function() {
          var app, getRemoteState;
          buffers.reset();
          app = _this.createExpressApp(config.morgan);
          logger.setSettings(config);
          _this._request = Request({
            timeout: config.responseTimeout
          });
          getRemoteState = function() {
            return _this._getRemoteState();
          };
          _this.createHosts(config.hosts);
          _this.createRoutes(app, config, _this._request, getRemoteState, _this.watchers, project);
          return _this.createServer(app, config, _this._request);
        };
      })(this));
    };

    Server.prototype.createHosts = function(hosts) {
      if (hosts == null) {
        hosts = {};
      }
      return _.each(hosts, function(ip, host) {
        return evilDns.add(host, ip);
      });
    };

    Server.prototype.createServer = function(app, config, request) {
      return new Promise((function(_this) {
        return function(resolve, reject) {
          var callListeners, fileServerFolder, onError, onSniUpgrade, onUpgrade, port, socketIoRoute;
          port = config.port, fileServerFolder = config.fileServerFolder, socketIoRoute = config.socketIoRoute;
          _this._server = http.createServer(app);
          _this._wsProxy = httpProxy.createProxyServer();
          allowDestroy(_this._server);
          onError = function(err) {
            if (err.code === "EADDRINUSE") {
              return reject(_this.portInUseErr(port));
            }
          };
          onUpgrade = function(req, socket, head) {
            return _this.proxyWebsockets(_this._wsProxy, socketIoRoute, req, socket, head);
          };
          callListeners = function(req, res) {
            var listeners;
            listeners = _this._server.listeners("request").slice(0);
            return _this._callRequestListeners(_this._server, listeners, req, res);
          };
          onSniUpgrade = function(req, socket, head) {
            var i, len, results, upgrade, upgrades;
            upgrades = _this._server.listeners("upgrade").slice(0);
            results = [];
            for (i = 0, len = upgrades.length; i < len; i++) {
              upgrade = upgrades[i];
              results.push(upgrade.call(_this._server, req, socket, head));
            }
            return results;
          };
          _this._server.on("connect", function(req, socket, head) {
            return _this._httpsProxy.connect(req, socket, head, {
              onDirectConnection: function(req) {
                var dc, str;
                dc = !cors.urlMatchesOriginPolicyProps("https://" + req.url, _this._remoteProps);
                if (dc) {
                  str = "Making";
                } else {
                  str = "Not making";
                }
                logger.info(str + (" direction connection to: '" + req.url + "'"));
                return dc;
              }
            });
          });
          _this._server.on("upgrade", onUpgrade);
          _this._server.once("error", onError);
          return _this._listen(port, onError).then(function(port) {
            return Promise.all([
              httpsProxy.create(appData.path("proxy"), port, {
                onRequest: callListeners,
                onUpgrade: onSniUpgrade
              }), fileServer.create(fileServerFolder)
            ]).spread(function(httpsProxy, fileServer) {
              _this._httpsProxy = httpsProxy;
              _this._fileServer = fileServer;
              _this._onDomainSet("<root>");
              return resolve(port);
            });
          });
        };
      })(this));
    };

    Server.prototype._port = function() {
      var ref;
      return (ref = this._server) != null ? ref.address().port : void 0;
    };

    Server.prototype._listen = function(port, onError) {
      return new Promise((function(_this) {
        return function(resolve) {
          var args, listener;
          listener = function() {
            port = _this._server.address().port;
            _this.isListening = true;
            logger.info("Server listening", {
              port: port
            });
            _this._server.removeListener("error", onError);
            return resolve(port);
          };
          args = _.compact([port, listener]);
          return _this._server.listen.apply(_this._server, args);
        };
      })(this));
    };

    Server.prototype._getRemoteState = function() {
      return _.extend({}, {
        props: this._remoteProps,
        origin: this._remoteOrigin,
        strategy: this._remoteStrategy,
        visiting: this._remoteVisitingUrl,
        domainName: this._remoteDomainName,
        fileServer: this._remoteFileServer
      });
    };

    Server.prototype._onRequest = function(headers, automationRequest, options) {
      return this._request.send(headers, automationRequest, options);
    };

    Server.prototype._onResolveUrl = function(urlStr, headers, automationRequest) {
      var handlingLocalFile, obj, originalUrl, p, previousState, request;
      request = this._request;
      handlingLocalFile = false;
      previousState = _.clone(this._getRemoteState());
      urlStr = url.parse(urlStr);
      urlStr.hash = null;
      urlStr = urlStr.format();
      originalUrl = urlStr;
      if (obj = buffers.getByOriginalUrl(urlStr)) {
        return request.setJarCookies(obj.jar, automationRequest).then(function(c) {
          return obj.details;
        });
      } else {
        return p = new Promise((function(_this) {
          return function(resolve, reject) {
            var error, handleReqStream, newUrl, redirects, restorePreviousState, urlFile;
            redirects = [];
            newUrl = null;
            if (!fullyQualifiedRe.test(urlStr)) {
              handlingLocalFile = true;
              _this._remoteVisitingUrl = true;
              _this._onDomainSet(urlStr);
              urlFile = url.resolve(_this._remoteFileServer, urlStr);
              urlStr = url.resolve(_this._remoteOrigin, urlStr);
            }
            error = function(err) {
              if (p.isPending()) {
                restorePreviousState();
              }
              return reject(err);
            };
            handleReqStream = function(str) {
              var pt;
              return pt = str.on("error", error).on("response", function(incomingRes) {
                var jar;
                str.removeListener("error", error);
                str.on("error", function(err) {
                  if (pt.listeners("error").length) {
                    return pt.emit("error", err);
                  } else {
                    return pt.error = err;
                  }
                });
                jar = str.getJar();
                return request.setJarCookies(jar, automationRequest).then(function(c) {
                  var contentType, details, fp, isHtml, isOk;
                  _this._remoteVisitingUrl = false;
                  if (newUrl == null) {
                    newUrl = urlStr;
                  }
                  isOk = statusCode.isOk(incomingRes.statusCode);
                  contentType = headersUtil.getContentType(incomingRes);
                  isHtml = contentType === "text/html";
                  details = {
                    isOkStatusCode: isOk,
                    isHtml: isHtml,
                    contentType: contentType,
                    url: newUrl,
                    status: incomingRes.statusCode,
                    cookies: c,
                    statusText: statusCode.getText(incomingRes.statusCode),
                    redirects: redirects,
                    originalUrl: originalUrl
                  };
                  if (fp = incomingRes.headers["x-cypress-file-path"]) {
                    details.filePath = fp;
                  }
                  if (isOk && isHtml) {
                    if (!handlingLocalFile) {
                      _this._onDomainSet(newUrl);
                    }
                    buffers.set({
                      url: newUrl,
                      jar: jar,
                      stream: pt,
                      details: details,
                      originalUrl: originalUrl,
                      response: incomingRes
                    });
                  } else {
                    restorePreviousState();
                  }
                  return resolve(details);
                })["catch"](error);
              }).pipe(stream.PassThrough());
            };
            restorePreviousState = function() {
              _this._remoteProps = previousState.props;
              _this._remoteOrigin = previousState.origin;
              _this._remoteStrategy = previousState.strategy;
              _this._remoteFileServer = previousState.fileServer;
              _this._remoteDomainName = previousState.domainName;
              return _this._remoteVisitingUrl = previousState.visiting;
            };
            return request.sendStream(headers, automationRequest, {
              gzip: false,
              url: urlFile != null ? urlFile : urlStr,
              headers: {
                accept: "text/html,*/*"
              },
              followRedirect: function(incomingRes) {
                var curr, next, status;
                status = incomingRes.statusCode;
                next = incomingRes.headers.location;
                curr = newUrl != null ? newUrl : urlStr;
                newUrl = url.resolve(curr, next);
                redirects.push([status, newUrl].join(": "));
                return true;
              }
            }).then(handleReqStream)["catch"](error);
          };
        })(this));
      }
    };

    Server.prototype._onDomainSet = function(fullyQualifiedUrl) {
      var log, parsed;
      log = function(type, url) {
        return logger.info("Setting " + type, {
          value: url
        });
      };
      if (fullyQualifiedUrl === "<root>" || !fullyQualifiedRe.test(fullyQualifiedUrl)) {
        this._remoteOrigin = "http://" + DEFAULT_DOMAIN_NAME + ":" + (this._port());
        this._remoteStrategy = "file";
        this._remoteFileServer = "http://" + DEFAULT_DOMAIN_NAME + ":" + (this._fileServer.port());
        this._remoteDomainName = DEFAULT_DOMAIN_NAME;
        this._remoteProps = null;
        log("remoteOrigin", this._remoteOrigin);
        log("remoteStrategy", this._remoteStrategy);
        log("remoteHostAndPort", this._remoteProps);
        log("remoteDocDomain", this._remoteDomainName);
        log("remoteFileServer", this._remoteFileServer);
      } else {
        parsed = url.parse(fullyQualifiedUrl);
        parsed.hash = null;
        parsed.search = null;
        parsed.query = null;
        parsed.path = null;
        parsed.pathname = null;
        this._remoteOrigin = url.format(parsed);
        this._remoteStrategy = "http";
        this._remoteFileServer = null;
        this._remoteProps = cors.parseUrlIntoDomainTldPort(this._remoteOrigin);
        this._remoteDomainName = _.compact([this._remoteProps.domain, this._remoteProps.tld]).join(".");
        log("remoteOrigin", this._remoteOrigin);
        log("remoteHostAndPort", this._remoteProps);
        log("remoteDocDomain", this._remoteDomainName);
      }
      return this._getRemoteState();
    };

    Server.prototype._callRequestListeners = function(server, listeners, req, res) {
      var i, len, listener, results;
      results = [];
      for (i = 0, len = listeners.length; i < len; i++) {
        listener = listeners[i];
        results.push(listener.call(server, req, res));
      }
      return results;
    };

    Server.prototype._normalizeReqUrl = function(server) {
      var listeners;
      listeners = server.listeners("request").slice(0);
      server.removeAllListeners("request");
      return server.on("request", (function(_this) {
        return function(req, res) {
          setProxiedUrl(req);
          return _this._callRequestListeners(server, listeners, req, res);
        };
      })(this));
    };

    Server.prototype.proxyWebsockets = function(proxy, socketIoRoute, req, socket, head) {
      var host, hostname, port, protocol, remoteOrigin;
      if (req.url.startsWith(socketIoRoute)) {
        return;
      }
      if ((host = req.headers.host) && this._remoteProps && (remoteOrigin = this._remoteOrigin)) {
        port = this._remoteProps.port;
        protocol = url.parse(remoteOrigin).protocol;
        hostname = url.parse("http://" + host).hostname;
        return proxy.ws(req, socket, head, {
          secure: false,
          target: {
            host: hostname,
            port: port,
            protocol: protocol
          }
        });
      } else {
        if (socket.writable) {
          return socket.end();
        }
      }
    };

    Server.prototype._close = function() {
      return new Promise((function(_this) {
        return function(resolve) {
          logger.unsetSettings();
          evilDns.clear();
          if (!_this._server || !_this.isListening) {
            return resolve();
          }
          logger.info("Server closing");
          return _this._server.destroy(function() {
            _this.isListening = false;
            return resolve();
          });
        };
      })(this));
    };

    Server.prototype.close = function() {
      var ref, ref1, ref2;
      return Promise.join(this._close(), (ref = this._socket) != null ? ref.close() : void 0, (ref1 = this._fileServer) != null ? ref1.close() : void 0, (ref2 = this._httpsProxy) != null ? ref2.close() : void 0).then((function(_this) {
        return function() {
          return _this._middleware = null;
        };
      })(this));
    };

    Server.prototype.end = function() {
      return this._socket && this._socket.end();
    };

    Server.prototype.changeToUrl = function(url) {
      return this._socket && this._socket.changeToUrl(url);
    };

    Server.prototype.onTestFileChange = function(filePath) {
      return this._socket && this._socket.onTestFileChange(filePath);
    };

    Server.prototype.onRequest = function(fn) {
      return this._middleware = fn;
    };

    Server.prototype.onNextRequest = function(fn) {
      return this.onRequest((function(_this) {
        return function() {
          fn.apply(_this, arguments);
          return _this._middleware = null;
        };
      })(this));
    };

    Server.prototype.startWebsockets = function(watchers, config, options) {
      if (options == null) {
        options = {};
      }
      options.onResolveUrl = this._onResolveUrl.bind(this);
      options.onRequest = this._onRequest.bind(this);
      this._socket = Socket();
      this._socket.startListening(this._server, watchers, config, options);
      return this._normalizeReqUrl(this._server);
    };

    return Server;

  })();

  module.exports = Server;

}).call(this);

});
require.register("./lib/socket.js",function (module, exports, require) {(function() {
  var Promise, Socket, _, automation, cwd, errors, exec, existingState, files, fixture, fs, launcher, logger, open, path, pathHelpers, reporterEvents, retry, runnerEvents, savedState, socketIo, str, uuid;

  _ = require("lodash");

  fs = require("fs-extra");

  str = require("underscore.string");

  path = require("path");

  uuid = require("node-uuid");

  Promise = require("bluebird");

  socketIo = require("@cypress/core-socket");

  open = require("./util/open");

  pathHelpers = require("./util/path_helpers");

  cwd = require("./cwd");

  exec = require("./exec");

  files = require("./files");

  fixture = require("./fixture");

  errors = require("./errors");

  logger = require("./logger");

  launcher = require("./launcher");

  automation = require("./automation");

  savedState = require("./saved_state");

  existingState = null;

  runnerEvents = ["reporter:restart:test:run", "runnables:ready", "run:start", "test:before:hooks", "reporter:log:add", "reporter:log:state:changed", "paused", "test:after:hooks", "run:end"];

  reporterEvents = ["runner:restart", "runner:abort", "runner:console:log", "runner:console:error", "runner:show:snapshot", "runner:hide:snapshot", "reporter:restarted"];

  retry = function(fn) {
    return Promise.delay(25).then(fn);
  };

  Socket = (function() {
    function Socket() {
      if (!(this instanceof Socket)) {
        return new Socket;
      }
    }

    Socket.prototype.onTestFileChange = function(filePath) {
      logger.info("onTestFileChange", {
        filePath: filePath
      });
      if (!/\.(js|jsx|coffee|cjsx)$/.test(filePath)) {
        return;
      }
      return fs.statAsync(filePath).then((function(_this) {
        return function() {
          return _this.io.emit("watched:file:changed");
        };
      })(this))["catch"](function() {});
    };

    Socket.prototype.watchTestFileByPath = function(config, originalFilePath, watchers, options) {
      var filePath;
      filePath = path.join("cypress", originalFilePath);
      if ((filePath === this.testFilePath) || (config.watchForFileChanges === false)) {
        return;
      }
      logger.info("watching test file", {
        path: filePath
      });
      if (this.testFilePath) {
        watchers.removeBundle(this.testFilePath);
      }
      this.testFilePath = filePath;
      return watchers.watchBundle(filePath, config, {
        onChange: this.onTestFileChange.bind(this)
      })["catch"](function() {});
    };

    Socket.prototype.onFixture = function(config, file, options, cb) {
      return fixture.get(config.fixturesFolder, file, options).then(cb)["catch"](function(err) {
        return cb({
          __error: err.message
        });
      });
    };

    Socket.prototype.onReadFile = function(config, file, options, cb) {
      return files.readFile(config.projectRoot, file, options).then(cb)["catch"](function(err) {
        return cb({
          __error: {
            message: err.message,
            code: err.code,
            filePath: err.filePath
          }
        });
      });
    };

    Socket.prototype.onWriteFile = function(config, file, contents, options, cb) {
      return files.writeFile(config.projectRoot, file, contents, options).then(cb)["catch"](function(err) {
        return cb({
          __error: {
            message: err.message,
            code: err.code,
            filePath: err.filePath
          }
        });
      });
    };

    Socket.prototype.onExec = function(projectRoot, options, cb) {
      return exec.run(projectRoot, options).then(cb)["catch"](function(err) {
        return cb({
          __error: err.message,
          timedout: err.timedout
        });
      });
    };

    Socket.prototype.toReporter = function(event, data) {
      return this.io && this.io.to("reporter").emit(event, data);
    };

    Socket.prototype.toRunner = function(event, data) {
      return this.io && this.io.to("runner").emit(event, data);
    };

    Socket.prototype.onAutomation = function(messages, message, data) {
      return Promise["try"]((function(_this) {
        return function() {
          if (_.isEmpty(_this.io.sockets.adapter.rooms.automation)) {
            throw new Error("Could not process '" + message + "'. No automation servers connected.");
          } else {
            return new Promise(function(resolve, reject) {
              var id;
              id = uuid.v4();
              messages[id] = function(obj) {
                var e, err;
                if (e = obj.__error) {
                  err = new Error(e);
                  err.name = obj.__name;
                  err.stack = obj.__stack;
                  return reject(err);
                } else {
                  return resolve(obj.response);
                }
              };
              return _this.io.to("automation").emit("automation:request", id, message, data);
            });
          }
        };
      })(this));
    };

    Socket.prototype.createIo = function(server, path, cookie) {
      return socketIo.server(server, {
        path: path,
        destroyUpgrade: false,
        serveClient: false,
        cookie: cookie
      });
    };

    Socket.prototype._startListening = function(server, watchers, config, options) {
      var integrationFolder, messages, socketIoCookie, socketIoRoute;
      _.defaults(options, {
        socketId: null,
        onAutomationRequest: null,
        afterAutomationRequest: null,
        onSetRunnables: function() {},
        onMocha: function() {},
        onConnect: function() {},
        onRequest: function() {},
        onResolveUrl: function() {},
        onFocusTests: function() {},
        onSpecChanged: function() {},
        onChromiumRun: function() {},
        onReloadBrowser: function() {},
        checkForAppErrors: function() {},
        onSavedStateChanged: function() {},
        onTestFileChange: function() {}
      });
      messages = {};
      integrationFolder = config.integrationFolder, socketIoRoute = config.socketIoRoute, socketIoCookie = config.socketIoCookie;
      this.testsDir = integrationFolder;
      this.io = this.createIo(server, socketIoRoute, socketIoCookie);
      return this.io.on("connection", (function(_this) {
        return function(socket) {
          var automationRequest, headers, ref, ref1, respond;
          logger.info("socket connected");
          headers = (ref = (ref1 = socket.request) != null ? ref1.headers : void 0) != null ? ref : {};
          respond = function(id, resp) {
            var message;
            if (message = messages[id]) {
              delete messages[id];
              return message(resp);
            }
          };
          automationRequest = function(message, data) {
            var automate, ref2;
            automate = (ref2 = options.onAutomationRequest) != null ? ref2 : function(message, data) {
              return _this.onAutomation(messages, message, data);
            };
            return automation(config.namespace, socketIoCookie, config.screenshotsFolder).request(message, data, automate).then(function(resp) {
              var aar;
              if (aar = options.afterAutomationRequest) {
                return aar(message, data, resp);
              } else {
                return resp;
              }
            });
          };
          socket.on("automation:connected", function() {
            if (socket.inAutomationRoom) {
              return;
            }
            socket.inAutomationRoom = true;
            socket.join("automation");
            socket.on("disconnect", function() {
              return Promise.delay(500).then(function() {
                if (socket.connected) {
                  return;
                }
                errors.warning("AUTOMATION_SERVER_DISCONNECTED");
                return _this.io.emit("automation:disconnected");
              });
            });
            socket.on("automation:push:request", function(msg, data, cb) {
              var fn;
              if (cb == null) {
                cb = function() {};
              }
              fn = function(data) {
                _this.io.emit("automation:push:message", msg, data);
                return cb();
              };
              return automation(config.namespace, socketIoCookie).pushMessage(msg, data, fn);
            });
            return socket.on("automation:response", respond);
          });
          socket.on("automation:request", function(message, data, cb) {
            return automationRequest(message, data).then(function(resp) {
              return cb({
                response: resp
              });
            })["catch"](function(err) {
              return cb({
                __error: err.message,
                __name: err.name,
                __stack: err.stack
              });
            });
          });
          socket.on("reporter:connected", function() {
            if (socket.inReporterRoom) {
              return;
            }
            socket.inReporterRoom = true;
            return socket.join("reporter");
          });
          socket.on("runner:connected", function() {
            if (socket.inRunnerRoom) {
              return;
            }
            socket.inRunnerRoom = true;
            return socket.join("runner");
          });
          socket.on("adapter:connected", function() {
            logger.info("adapter:connected");
            return socket.on("adapter:response", respond);
          });
          socket.on("adapter:request", function(message, data, cb) {
            var id;
            if (!_.isFunction(cb)) {
              cb = data;
              data = null;
            }
            id = uuid.v4();
            logger.info("adapter:request", {
              id: id,
              msg: message,
              data: data
            });
            if (_.keys(_this.io.sockets.adapter.rooms.adapter).length > 0) {
              messages[id] = cb;
              return _this.io.to("adapter").emit("adapter:request", id, message, data);
            } else {
              return cb({
                __error: "Could not process '" + message + "'. No adapter servers connected."
              });
            }
          });
          socket.on("spec:changed", function(spec) {
            return options.onSpecChanged(spec);
          });
          socket.on("watch:test:file", function(filePath, cb) {
            if (cb == null) {
              cb = function() {};
            }
            _this.watchTestFileByPath(config, filePath, watchers, options);
            return cb();
          });
          socket.on("fixture", function(fixturePath, options, cb) {
            return _this.onFixture(config, fixturePath, options, cb);
          });
          socket.on("read:file", function(file, options, cb) {
            return _this.onReadFile(config, file, options, cb);
          });
          socket.on("write:file", function(file, contents, options, cb) {
            return _this.onWriteFile(config, file, contents, options, cb);
          });
          socket.on("exec", function(options, cb) {
            return _this.onExec(config.projectRoot, options, cb);
          });
          socket.on("app:connect", function(socketId) {
            return options.onConnect(socketId, socket);
          });
          socket.on("set:runnables", function(runnables, cb) {
            options.onSetRunnables(runnables);
            return cb();
          });
          socket.on("mocha", function() {
            return options.onMocha.apply(options, arguments);
          });
          socket.on("open:finder", function(p, cb) {
            if (cb == null) {
              cb = function() {};
            }
            return open.opn(p).then(function() {
              return cb();
            });
          });
          socket.on("reload:browser", function(url, browser) {
            return options.onReloadBrowser(url, browser);
          });
          socket.on("focus:tests", function() {
            return options.onFocusTests();
          });
          socket.on("is:automation:connected", function(data, cb) {
            var isConnected, ref2, tryConnected;
            if (data == null) {
              data = {};
            }
            isConnected = function() {
              return automationRequest("is:automation:connected", data);
            };
            tryConnected = function() {
              return Promise["try"](isConnected)["catch"](function() {
                return retry(tryConnected);
              });
            };
            return Promise["try"](tryConnected).timeout((ref2 = data.timeout) != null ? ref2 : 1000).then(function() {
              return cb(true);
            })["catch"](Promise.TimeoutError, function(err) {
              return cb(false);
            });
          });
          socket.on("resolve:url", function(url, cb) {
            return options.onResolveUrl(url, headers, automationRequest).then(cb)["catch"](function(err) {
              return cb({
                __error: errors.clone(err)
              });
            });
          });
          socket.on("request", function(params, cb) {
            return options.onRequest(headers, automationRequest, params).then(cb)["catch"](function(err) {
              return cb({
                __error: errors.clone(err)
              });
            });
          });
          socket.on("preserve:run:state", function(state, cb) {
            existingState = state;
            return cb();
          });
          socket.on("get:existing:run:state", function(cb) {
            var s;
            if ((s = existingState)) {
              existingState = null;
              return cb(s);
            } else {
              return cb();
            }
          });
          socket.on("go:to:file", function(p) {
            return launcher.launch("chrome", "http://localhost:2020/__#" + p, {
              host: "http://localhost:2020"
            });
          });
          socket.on("save:app:state", function(state) {
            return savedState.set(state).then(function() {
              return options.onSavedStateChanged();
            });
          });
          reporterEvents.forEach(function(event) {
            return socket.on(event, function(data) {
              return _this.toRunner(event, data);
            });
          });
          return runnerEvents.forEach(function(event) {
            return socket.on(event, function(data) {
              return _this.toReporter(event, data);
            });
          });
        };
      })(this));
    };

    Socket.prototype.end = function() {
      return this.io && this.io.emit("tests:finished");
    };

    Socket.prototype.changeToUrl = function(url) {
      return this.toRunner("change:to:url", url);
    };

    Socket.prototype.startListening = function(server, watchers, config, options) {
      if (process.env["CYPRESS_ENV"] === "development") {
        this.listenToCssChanges(watchers);
      }
      return this._startListening(server, watchers, config, options);
    };

    Socket.prototype.listenToCssChanges = function(watchers) {
      return watchers.watch(cwd("lib", "public", "css"), {
        ignored: (function(_this) {
          return function(path, stats) {
            if (fs.statSync(path).isDirectory()) {
              return false;
            }
            return !/\.css$/.test(path);
          };
        })(this),
        onChange: (function(_this) {
          return function(filePath, stats) {
            filePath = path.basename(filePath);
            return _this.io.emit("cypress:css:changed", {
              file: filePath
            });
          };
        })(this)
      });
    };

    Socket.prototype.close = function() {
      var ref;
      return (ref = this.io) != null ? ref.close() : void 0;
    };

    return Socket;

  })();

  module.exports = Socket;

}).call(this);

});
require.register("./lib/stats.js",function (module, exports, require) {(function() {
  var KEYS, LENS, MAX, TRANSLATION, _, chalk;

  _ = require("lodash");

  chalk = require("chalk");

  TRANSLATION = {
    tests: "Tests",
    passes: "Passes",
    failures: "Failures",
    pending: "Pending",
    duration: "Duration",
    screenshots: "Screenshots",
    video: "Video Recorded",
    version: "Cypress Version"
  };

  KEYS = _.keys(TRANSLATION);

  LENS = _.map(TRANSLATION, function(val, key) {
    return val.length;
  });

  MAX = Math.max.apply(Math, LENS);

  module.exports = {
    format: function(color, val, key) {
      var word;
      word = "  - " + TRANSLATION[key] + ":";
      key = _.padEnd(word, MAX + 6);
      return chalk.white(key) + chalk[color](val);
    },
    display: function(color, stats) {
      if (stats == null) {
        stats = {};
      }
      stats = _.pick(stats, KEYS);
      return _.each(stats, (function(_this) {
        return function(val, key) {
          return console.log(_this.format(color, val, key));
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/updater.js",function (module, exports, require) {(function() {
  var NwUpdater, Promise, Updater, _, argsUtil, chmodr, cwd, fs, glob, home, konfig, linuxAppRe, localCwd, logger, os, osxAppRe, path, request, semver, tar, trash,
    slice = [].slice;

  _ = require("lodash");

  os = require("os");

  fs = require("fs-extra");

  tar = require("tar-fs");

  path = require("path");

  glob = require("glob");

  home = require("home-or-tmp");

  trash = require("trash");

  chmodr = require("chmodr");

  semver = require("semver");

  request = require("request");

  Promise = require("bluebird");

  NwUpdater = require("node-webkit-updater");

  cwd = require("./cwd");

  konfig = require("./konfig");

  logger = require("./logger");

  argsUtil = require("./util/args");

  chmodr = Promise.promisify(chmodr);

  localCwd = cwd();

  osxAppRe = /\.app$/;

  linuxAppRe = /Cypress$/i;

  NwUpdater.prototype.checkNewVersion = function(cb) {
    var gotManifest;
    gotManifest = function(err, req, data) {
      var e, newVersion;
      if (err) {
        return cb(err);
      }
      if (req.statusCode < 200 || req.statusCode > 299) {
        return cb(new Error(req.statusCode));
      }
      try {
        data = JSON.parse(data);
      } catch (error) {
        e = error;
        return cb(e);
      }
      try {
        newVersion = semver.gt(data.version, this.manifest.version);
      } catch (error) {
        e = error;
        newVersion = false;
      }
      return cb(null, newVersion, data);
    };
    return request.get(this.manifest.manifestUrl, gotManifest.bind(this));
  };

  Updater = (function() {
    function Updater(callbacks) {
      if (!(this instanceof Updater)) {
        return new Updater(callbacks);
      }
      this.client = new NwUpdater(this.getPackage());
      this.request = null;
      this.cancelled = false;
      this.callbacks = callbacks;
      if (process.env["CYPRESS_ENV"] !== "production") {
        this.patchAppPath();
      }
    }

    Updater.prototype.getArgs = function() {
      var args, c, currentCwd;
      c = this.getClient();
      currentCwd = process.cwd();
      process.chdir(localCwd);
      args = _.compact(["--app-path=" + c.getAppPath(), "--exec-path=" + c.getAppExec(), "--updating"]);
      process.chdir(currentCwd);
      return args;
    };

    Updater.prototype.patchAppPath = function() {
      return this.getClient().getAppPath = function() {
        return cwd();
      };
    };

    Updater.prototype.getPackage = function() {
      var pkg;
      pkg = fs.readJsonSync(cwd("package.json"));
      pkg.manifestUrl = konfig("desktop_manifest_url");
      return pkg;
    };

    Updater.prototype.getClient = function() {
      var ref;
      return (function() {
        if ((ref = this.client) != null) {
          return ref;
        } else {
          throw new Error("missing Updater#client");
        }
      }).call(this);
    };

    Updater.prototype.trash = function(appPath) {
      logger.info("trashing current app", {
        appPath: appPath
      });
      return Promise.resolve(trash([appPath]));
    };

    Updater.prototype.install = function(argsObj) {
      var appPath, args, c, execPath;
      if (argsObj == null) {
        argsObj = {};
      }
      c = this.getClient();
      argsObj = this.normalizeArgs(argsObj);
      appPath = argsObj.appPath, execPath = argsObj.execPath;
      argsObj = _.omit(argsObj, "updating", "execPath", "appPath");
      args = argsUtil.toArray(argsObj);
      return this.trash(appPath).then((function(_this) {
        return function() {
          logger.info("installing updated app", {
            appPath: appPath,
            execPath: execPath
          });
          return _this.copyTmpToAppPath(c.getAppPath(), appPath).then(function() {
            c.run(execPath, args);
            return process.exit(0);
          });
        };
      })(this));
    };

    Updater.prototype.normalizeArgs = function(args) {
      var appPath, execPath, p;
      if (args == null) {
        args = {};
      }
      appPath = args.appPath, execPath = args.execPath;
      switch (os.platform()) {
        case "darwin":
          if (!osxAppRe.test(appPath)) {
            args.appPath = args.execPath = "/Applications/Cypress.app";
          }
          break;
        case "linux":
          if (!linuxAppRe.test(appPath)) {
            p = path.join(this.getHome(), ".cypress", "Cypress");
            args.appPath = p;
            args.execPath = path.join(p, "Cypress");
          }
      }
      return args;
    };

    Updater.prototype.getHome = function() {
      return home;
    };

    Updater.prototype.copyTmpToAppPath = function(tmp, appPath) {
      return new Promise(function(resolve, reject) {
        var obj;
        obj = {
          fs: require("original-fs")
        };
        return tar.pack(tmp, obj).pipe(tar.extract(appPath, obj)).on("error", reject).on("finish", resolve);
      });
    };

    Updater.prototype.runInstaller = function(newAppPath) {
      var args;
      args = this.getArgs();
      logger.info("running installer from tmp", {
        destination: newAppPath,
        args: args
      });
      this.getClient().runInstaller(newAppPath, args, {});
      return process.exit();
    };

    Updater.prototype.unpack = function(destinationPath, manifest) {
      var fn;
      logger.info("unpacking new version", {
        destination: destinationPath
      });
      this.trigger("apply");
      fn = (function(_this) {
        return function(err, newAppPath) {
          if (err) {
            return _this.trigger("error", err);
          }
          if (_this.cancelled) {
            return;
          }
          return _this.runInstaller(newAppPath);
        };
      })(this);
      return this.getClient().unpack(destinationPath, fn, manifest);
    };

    Updater.prototype.download = function(manifest) {
      var fn;
      logger.info("downloading new version", {
        version: manifest.version
      });
      this.trigger("download", manifest.version);
      fn = (function(_this) {
        return function(err, destinationPath) {
          if (err) {
            return _this.trigger("error", err);
          }
          return setTimeout(function() {
            if (_this.cancelled) {
              return;
            }
            return _this.unpack(destinationPath, manifest);
          }, 1000);
        };
      })(this);
      return this.request = this.getClient().download(fn, manifest);
    };

    Updater.prototype.cancel = function() {
      this.cancelled = true;
      try {
        return this.request.abort();
      } catch (error) {}
    };

    Updater.prototype.trigger = function() {
      var args, cb, event;
      event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      event = "on" + event[0].toUpperCase() + event.slice(1);
      if (cb = this.callbacks && this.callbacks[event]) {
        return cb.apply(this, args);
      }
    };

    Updater.prototype.check = function(options) {
      if (options == null) {
        options = {};
      }
      logger.info("checking for new version");
      return this.getClient().checkNewVersion((function(_this) {
        return function(err, newVersionExists, manifest) {
          if (err) {
            return _this.trigger("error", err);
          }
          if (newVersionExists) {
            logger.info("new version exists", {
              version: manifest.version
            });
            return typeof options.onNewVersion === "function" ? options.onNewVersion(manifest) : void 0;
          } else {
            logger.info("new version does not exist");
            return typeof options.onNoNewVersion === "function" ? options.onNoNewVersion() : void 0;
          }
        };
      })(this));
    };

    Updater.prototype.run = function() {
      this.trigger("start");
      this.check({
        onNewVersion: (function(_this) {
          return function(manifest) {
            return _this.download(manifest);
          };
        })(this),
        onNoNewVersion: (function(_this) {
          return function() {
            return _this.trigger("none");
          };
        })(this)
      });
      return this;
    };

    Updater.install = function(options) {
      return Updater().install(options);
    };

    Updater.check = function(options) {
      if (options == null) {
        options = {};
      }
      return Updater().check(options);
    };

    Updater.run = function(callbacks) {
      if (callbacks == null) {
        callbacks = {};
      }
      return Updater(callbacks).run();
    };

    return Updater;

  })();

  module.exports = Updater;

}).call(this);

});
require.register("./lib/upload.js",function (module, exports, require) {(function() {
  var Promise, fs, r, rp;

  fs = require("fs-extra");

  r = require("request");

  rp = require("request-promise");

  Promise = require("bluebird");

  fs = Promise.promisifyAll(fs);

  module.exports = function(pathToFile, url) {
    return fs.readFileAsync(pathToFile).then(function(buf) {
      return rp({
        url: url,
        method: "PUT",
        body: buf
      });
    });
  };

}).call(this);

});
require.register("./lib/user.js",function (module, exports, require) {(function() {
  var api, cache, errors;

  api = require("./api");

  cache = require("./cache");

  errors = require("./errors");

  module.exports = {
    get: function() {
      return cache.getUser();
    },
    set: function(user) {
      return cache.setUser(user);
    },
    getLoginUrl: function() {
      return api.getLoginUrl();
    },
    logIn: function(code) {
      return api.createSignin(code).then((function(_this) {
        return function(user) {
          return _this.set(user)["return"](user);
        };
      })(this));
    },
    logOut: function() {
      var remove;
      remove = function() {
        return cache.removeUser();
      };
      return this.get().then(function(user) {
        var session;
        session = user && user.sessionToken;
        if (session) {
          return api.createSignout(session).then(remove);
        } else {
          return remove();
        }
      });
    },
    ensureSession: function() {
      return this.get().then(function(user) {
        var st;
        if (user && (st = user.sessionToken)) {
          return st;
        } else {
          return errors["throw"]("NOT_LOGGED_IN");
        }
      });
    }
  };

}).call(this);

});
require.register("./lib/util/app_data.js",function (module, exports, require) {(function() {
  var Promise, cwd, data, fs, isProduction, name, ospath, path, pkg,
    slice = [].slice;

  fs = require("fs-extra");

  path = require("path");

  ospath = require("ospath");

  Promise = require("bluebird");

  cwd = require("../cwd");

  pkg = require("../../package.json");

  fs = Promise.promisifyAll(fs);

  name = pkg.productName || pkg.name;

  data = ospath.data();

  isProduction = function() {
    return process.env.CYPRESS_ENV === "production";
  };

  module.exports = {
    ensure: function() {
      var ensure;
      ensure = (function(_this) {
        return function() {
          return _this.removeSymlink().then(function() {
            return Promise.join(fs.ensureDirAsync(_this.path()), !isProduction() ? _this.symlink() : void 0);
          });
        };
      })(this);
      return ensure()["catch"](ensure);
    },
    symlink: function() {
      var dest, src;
      src = path.dirname(this.path());
      dest = cwd(".cy");
      return fs.ensureSymlinkAsync(src, dest, "dir");
    },
    removeSymlink: function() {
      return fs.removeAsync(cwd(".cy"))["catch"](function() {});
    },
    path: function() {
      var paths;
      paths = 1 <= arguments.length ? slice.call(arguments, 0) : [];
      return path.join.apply(path, [data, name, "cy", process.env.CYPRESS_ENV].concat(slice.call(paths)));
    },
    remove: function() {
      return Promise.join(fs.removeAsync(this.path()), this.removeSymlink());
    }
  };

}).call(this);

});
require.register("./lib/util/args.js",function (module, exports, require) {(function() {
  var _, anyUnderscoredValuePairs, backup, coerce, config, cwd, minimist, parseNestedValues, path, whitelist,
    slice = [].slice;

  _ = require("lodash");

  path = require("path");

  minimist = require("minimist");

  coerce = require("./coerce");

  config = require("../config");

  cwd = require("../cwd");

  whitelist = "appPath execPath apiKey smokeTest getKey generateKey runProject project spec ci updating ping key logs clearLogs returnPkg version mode autoOpen removeIds showHeadlessGui config exitWithCode hosts browser headless".split(" ");

  whitelist = whitelist.concat(config.getConfigKeys());

  parseNestedValues = function(vals) {
    return _(vals.split(",")).map(function(pair) {
      return pair.split("=");
    }).fromPairs().mapValues(coerce).value();
  };

  backup = function(key, options) {
    return options["_" + key] = options[key];
  };

  anyUnderscoredValuePairs = function(val, key, obj) {
    var v;
    if (v = obj["_" + key]) {
      return v;
    }
    return val;
  };

  module.exports = {
    toObject: function(argv) {
      var c, envs, hosts, options, p, ref, ro, rp;
      options = minimist(argv, {
        alias: {
          "app-path": "appPath",
          "exec-path": "execPath",
          "api-key": "apiKey",
          "smoke-test": "smokeTest",
          "remove-ids": "removeIds",
          "get-key": "getKey",
          "new-key": "generateKey",
          "run-project": "runProject",
          "clear-logs": "clearLogs",
          "return-pkg": "returnPkg",
          "auto-open": "autoOpen",
          "env": "environmentVariables",
          "headless": "isHeadless",
          "show-headless-gui": "showHeadlessGui",
          "exit-with-code": "exitWithCode",
          "reporter-options": "reporterOptions"
        }
      });
      _.extend(options, _.pick.apply(_, [argv].concat(slice.call(whitelist))), {
        env: process.env["CYPRESS_ENV"]
      });
      if (options.updating && !options.appPath) {
        ref = options._.slice(-2), options.appPath = ref[0], options.execPath = ref[1];
      }
      if (hosts = options.hosts) {
        backup("hosts", options);
        options.hosts = parseNestedValues(hosts);
      }
      if (envs = options.environmentVariables) {
        backup("environmentVariables", options);
        options.environmentVariables = parseNestedValues(envs);
      }
      if (ro = options.reporterOptions) {
        backup("reporterOptions", options);
        options.reporterOptions = parseNestedValues(ro);
      }
      if (c = options.config) {
        backup("config", options);
        c = parseNestedValues(c);
        options.config = c;
        _.extend(options, config.whitelist(c));
      }
      if (rp = options.runProject || (p = options.project)) {
        options.projectPath = path.resolve(cwd(), rp != null ? rp : p);
      }
      if (options.smokeTest) {
        options.pong = options.ping;
      }
      return options;
    },
    toArray: function(obj) {
      var ref;
      if (obj == null) {
        obj = {};
      }
      return (ref = _.chain(obj).mapValues(anyUnderscoredValuePairs)).pick.apply(ref, whitelist).mapValues(function(val, key) {
        return "--" + key + "=" + val;
      }).values().value();
    }
  };

}).call(this);

});
require.register("./lib/util/buffers.js",function (module, exports, require) {(function() {
  var _, buffers, url;

  _ = require("lodash");

  url = require("url");

  buffers = [];

  module.exports = {
    all: function() {
      return buffers;
    },
    keys: function() {
      return _.map(buffers, "url");
    },
    reset: function() {
      return buffers = [];
    },
    set: function(obj) {
      if (obj == null) {
        obj = {};
      }
      return buffers.push(_.pick(obj, "url", "originalUrl", "jar", "stream", "response", "details"));
    },
    getByOriginalUrl: function(str) {
      return _.find(buffers, {
        originalUrl: str
      });
    },
    get: function(str) {
      var b, find, parsed;
      find = function(str) {
        return _.find(buffers, {
          url: str
        });
      };
      b = find(str);
      if (b) {
        return b;
      }
      parsed = url.parse(str);
      if (parsed.protocol === "https:" && parsed.port) {
        parsed.host = parsed.host.split(":")[0];
        parsed.port = null;
        return find(parsed.format());
      }
    },
    take: function(str) {
      var buffer;
      if (buffer = this.get(str)) {
        buffers = _.without(buffers, buffer);
      }
      return buffer;
    }
  };

}).call(this);

});
require.register("./lib/util/bundle.js",function (module, exports, require) {(function() {
  var EE, Promise, _, appData, babelify, browserify, cjsxify, fs, path, pluginAddModuleExports, presetLatest, presetReact, str, stringStream, through, watchify;

  _ = require("lodash");

  fs = require("fs-extra");

  EE = require("events");

  str = require("underscore.string");

  path = require("path");

  through = require("through");

  cjsxify = require("cjsxify");

  Promise = require("bluebird");

  babelify = require("babelify");

  watchify = require("watchify");

  browserify = require("browserify");

  presetReact = require("babel-preset-react");

  presetLatest = require("babel-preset-latest");

  stringStream = require("string-to-stream");

  pluginAddModuleExports = require("babel-plugin-add-module-exports");

  appData = require("./app_data");

  fs = Promise.promisifyAll(fs);

  module.exports = {
    shouldWatch: function(watchForFileChanges) {
      return watchForFileChanges !== false;
    },
    build: function(filePath, config) {
      var absolutePath, bundle, bundler, emitter, latestBundle, ref, shouldWatch;
      emitter = new EE();
      shouldWatch = this.shouldWatch(config.watchForFileChanges);
      absolutePath = path.join(config.projectRoot, filePath);
      bundler = browserify({
        entries: [absolutePath],
        extensions: [".js", ".jsx", ".coffee", ".cjsx"],
        cache: {},
        packageCache: {},
        plugin: shouldWatch ? [watchify] : []
      });
      bundle = (function(_this) {
        return function() {
          return new Promise(function(resolve, reject) {
            var outputPath;
            outputPath = appData.path("bundles", filePath);
            return fs.ensureDirAsync(path.dirname(outputPath)).then(function() {
              return bundler.bundle().on("error", function(err) {
                if (shouldWatch) {
                  stringStream(_this.clientSideError(err)).pipe(fs.createWriteStream(outputPath));
                  return resolve();
                } else {
                  err.filePath = absolutePath;
                  return reject(err);
                }
              }).on("end", function() {
                return resolve();
              }).pipe(fs.createWriteStream(outputPath));
            });
          });
        };
      })(this);
      bundler.transform(cjsxify).transform(babelify, {
        ast: false,
        babelrc: false,
        plugins: [pluginAddModuleExports],
        presets: [presetLatest, presetReact]
      }).external(["react/addons", "react/lib/ReactContext", "react/lib/ExecutionEnvironment"]);
      if (shouldWatch) {
        bundler.on("update", function(filePaths) {
          var latestBundle;
          return latestBundle = bundle().then(function() {
            var i, len, updatedFilePath;
            for (i = 0, len = filePaths.length; i < len; i++) {
              updatedFilePath = filePaths[i];
              emitter.emit("update", updatedFilePath);
            }
          });
        });
      }
      latestBundle = bundle();
      return {
        close: (ref = bundler.close) != null ? ref : function() {},
        getLatestBundle: function() {
          return latestBundle;
        },
        addChangeListener: function(onChange) {
          return emitter.on("update", onChange);
        }
      };
    },
    errorMessage: function(err) {
      var ref, ref1, ref2;
      if (err == null) {
        err = {};
      }
      return ((ref = (ref1 = (ref2 = err.stack) != null ? ref2 : err.annotated) != null ? ref1 : err.message) != null ? ref : err.toString()).replace(/\n\s*at.*/g, "").replace("From previous event:", "");
    },
    clientSideError: function(err) {
      err = this.errorMessage(err).replace(/\n/g, '{newline}').replace(/\[\d{1,3}m/g, '');
      return "(function () {\n  Cypress.trigger(\"script:error\", {\n    type: \"BUNDLE_ERROR\",\n    error: " + (JSON.stringify(err)) + "\n  })\n}())";
    }
  };

}).call(this);

});
require.register("./lib/util/cache_buster.js",function (module, exports, require) {(function() {
  var DIGITS, SEPERATOR, _;

  _ = require('lodash');

  DIGITS = 3;

  SEPERATOR = "-";

  module.exports = {
    get: function() {
      return SEPERATOR + Math.random().toFixed(DIGITS).slice(2, 5);
    },
    strip: function(str) {
      if (this._hasCacheBuster(str)) {
        return str.slice(0, -4);
      } else {
        return str;
      }
    },
    _hasCacheBuster: function(str) {
      return str.split("").slice(-4, -3).join("") === SEPERATOR;
    }
  };

}).call(this);

});
require.register("./lib/util/coerce.js",function (module, exports, require) {(function() {
  var str;

  str = require("underscore.string");

  module.exports = function(value) {
    var ref, ref1;
    switch (false) {
      case ((ref = str.toNumber(value)) != null ? ref.toString() : void 0) !== value:
        return str.toNumber(value);
      case ((ref1 = str.toBoolean(value)) != null ? ref1.toString() : void 0) !== value:
        return str.toBoolean(value);
      default:
        return value;
    }
  };

}).call(this);

});
require.register("./lib/util/cors.js",function (module, exports, require) {(function() {
  var _, localHostOrIpAddressRe, parseDomain, url;

  _ = require("lodash");

  url = require("url");

  parseDomain = require("parse-domain");

  localHostOrIpAddressRe = /localhost|\.local|^[\d\.]+$/;

  module.exports = {
    parseUrlIntoDomainTldPort: function(str) {
      var hostname, obj, parsed, port, protocol, ref, segments;
      ref = url.parse(str), hostname = ref.hostname, port = ref.port, protocol = ref.protocol;
      if (port == null) {
        port = protocol === "https:" ? "443" : "80";
      }
      if (!(parsed = parseDomain(hostname, {
        customTlds: localHostOrIpAddressRe
      }))) {
        segments = hostname.split(".");
        parsed = {
          tld: segments[segments.length - 1],
          domain: segments[segments.length - 2]
        };
      }
      obj = {};
      obj.port = port;
      obj.tld = parsed.tld;
      obj.domain = parsed.domain;
      return obj;
    },
    urlMatchesOriginPolicyProps: function(url, props) {
      var parsedUrl;
      if (!props) {
        return false;
      }
      parsedUrl = this.parseUrlIntoDomainTldPort(url);
      return _.isEqual(parsedUrl, props);
    }
  };

}).call(this);

});
require.register("./lib/util/escape_regexp.js",function (module, exports, require) {(function() {
  var reSymbols;

  reSymbols = /[-\/\\^$*+?.()|[\]{}]/g;

  module.exports = function(str) {
    return str.replace(reSymbols, '\\$&');
  };

}).call(this);

});
require.register("./lib/util/headers.js",function (module, exports, require) {(function() {
  var contentType;

  contentType = require("content-type");

  module.exports = {
    getContentType: function(res, type) {
      var err;
      try {
        return contentType.parse(res).type;
      } catch (error) {
        err = error;
        return null;
      }
    },
    hasContentType: function(res, type) {
      var err;
      try {
        return contentType.parse(res).type === type;
      } catch (error) {
        err = error;
        return false;
      }
    }
  };

}).call(this);

});
require.register("./lib/util/http_overrides.js",function (module, exports, require) {(function() {
  var Promise, addRequest, cache, dns, getCachedFamily, http, net, setCache;

  net = require("net");

  dns = require("dns");

  http = require("http");

  Promise = require("bluebird");

  cache = {};

  addRequest = http.Agent.prototype.addRequest;

  setCache = function(options, family) {
    return cache[options.host + ":" + options.port] = family;
  };

  getCachedFamily = function(options) {
    return cache[options.host + ":" + options.port];
  };

  http.Agent.prototype.addRequest = function(req, options) {
    var agent, family, makeRequest;
    agent = this;
    makeRequest = function() {
      return addRequest.call(agent, req, options);
    };
    if (family = getCachedFamily(options)) {
      options.family = family;
      return makeRequest();
    }
    return dns.lookup(options.host, {
      all: true
    }, function(err, addresses) {
      var connect;
      if (err) {
        return makeRequest();
      }
      connect = function(address) {
        return new Promise(function(resolve, reject) {
          var client;
          client = net.connect(options.port, address.address);
          client.on("connect", function() {
            client.end();
            return resolve(address);
          });
          return client.on("error", reject);
        });
      };
      return Promise["try"](function() {
        return addresses.map(connect);
      }).any().then(function(address) {
        setCache(options, address.family);
        return options.family = address.family;
      }).then(makeRequest)["catch"](makeRequest);
    });
  };

}).call(this);

});
require.register("./lib/util/human_time.js",function (module, exports, require) {(function() {
  var moment, pluralize;

  moment = require("moment");

  pluralize = require("pluralize");

  module.exports = function(ms) {
    var duration, hours, mins, msg, secs, word;
    msg = [];
    mins = 0;
    duration = moment.duration(ms);
    hours = duration.hours();
    mins = hours * 60;
    if (mins += duration.minutes()) {
      word = pluralize("minute", mins);
      msg.push(mins + " " + word);
    }
    secs = duration.seconds();
    word = pluralize("second", secs);
    msg.push(secs + " " + word);
    return msg.join(", ");
  };

}).call(this);

});
require.register("./lib/util/inject.js",function (module, exports, require) {(function() {
  module.exports = {
    partial: function(domain) {
      return "<script type='text/javascript'> document.domain = '" + domain + "'; </script>";
    },
    full: function(domain) {
      return "<script type='text/javascript'> document.domain = '" + domain + "'; var Cypress = window.Cypress = parent.Cypress; if (!Cypress){ throw new Error('Something went terribly wrong and we cannot proceed. We expected to find the global Cypress in the parent window but it is missing!. This should never happen and likely is a bug. Please open an issue!'); }; window.onerror = function(){ Cypress.onUncaughtException.apply(Cypress, arguments); } </script> <script type='text/javascript' src='/__cypress/static/js/sinon.js'></script> <script type='text/javascript'> Cypress.onBeforeLoad(window); </script>";
    }
  };

}).call(this);

});
require.register("./lib/util/network_failures.js",function (module, exports, require) {(function() {
  var convertNewLinesToBr;

  convertNewLinesToBr = function(text) {
    return text.split("\n").join("<br />");
  };

  module.exports = {
    http: function(err, url) {
      return "Cypress errored attempting to make an http request to this url:\n\n" + url + "\n\n\nThe error was:\n\n" + err.message + "\n\n\nThe stack trace was:\n\n" + err.stack;
    },
    file: function(url, status) {
      return "Cypress errored trying to serve this file from your system:\n\n" + url + "\n\n" + (status === 404 ? "The file was not found." : "");
    },
    wrap: function(contents) {
      return "<!DOCTYPE html>\n<html>\n<body>\n  " + (convertNewLinesToBr(contents)) + "\n</body>\n</html>";
    },
    get: function(err, url, status, strategy) {
      var contents;
      contents = (function() {
        switch (strategy) {
          case "http":
            return this.http(err, url);
          case "file":
            return this.file(url, status);
        }
      }).call(this);
      return this.wrap(contents);
    }
  };

}).call(this);

});
require.register("./lib/util/open.js",function (module, exports, require) {(function() {
  var opn, os;

  os = require("os");

  opn = require("opn");

  module.exports = {
    opn: function(arg, opts) {
      if (opts == null) {
        opts = {};
      }
      if (os.platform() === "darwin") {
        opts.args = "-R";
      }
      return opn(arg, opts);
    }
  };

}).call(this);

});
require.register("./lib/util/path_helpers.js",function (module, exports, require) {(function() {
  var isIntegrationTestRe, isUnitTestRe, path;

  path = require("path");

  isIntegrationTestRe = /^integration/;

  isUnitTestRe = /^unit/;

  module.exports = {
    getAbsolutePathToSpec: function(spec, config) {
      switch (false) {
        case !isIntegrationTestRe.test(spec):
          spec = path.relative("integration", spec);
          return spec = path.join(config.integrationFolder, spec);
        default:
          return spec;
      }
    }
  };

}).call(this);

});
require.register("./lib/util/progress_bar.js",function (module, exports, require) {(function() {
  var ProgressBar, _, chalk;

  _ = require("lodash");

  chalk = require("chalk");

  ProgressBar = require("progress");

  module.exports = {
    create: function(message, options) {
      var ascii, bar, clear, tick, tickTotal, ticked, total;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        total: 100,
        width: 30
      });
      ascii = [chalk.white("  -"), chalk.blue(message), chalk.yellow("[:bar]"), chalk.white(":percent"), chalk.gray(":etas")];
      bar = new ProgressBar(ascii.join(" "), {
        total: options.total,
        width: options.width
      });
      ticked = 0;
      total = options.total;
      clear = function() {
        bar.clear = true;
        return bar.terminate();
      };
      tick = function(num) {
        ticked += num;
        return bar.tick(num);
      };
      tickTotal = function(float) {
        var abs, diff;
        abs = total * float;
        diff = abs - ticked;
        return tick(diff);
      };
      return {
        bar: bar,
        tick: tick,
        clear: clear,
        tickTotal: tickTotal
      };
    }
  };

}).call(this);

});
require.register("./lib/util/provider.js",function (module, exports, require) {(function() {
  var _, getProviderKey, isCodeship, isGitlab, isWercker, providers;

  _ = require("lodash");

  isCodeship = function() {
    return process.env.CI_NAME && process.env.CI_NAME === "codeship";
  };

  isGitlab = function() {
    return process.env.GITLAB_CI || process.env.CI_SERVER_NAME && process.env.CI_SERVER_NAME === "GitLab CI";
  };

  isWercker = function() {
    return process.env.WERCKER || process.env.WERCKER_MAIN_PIPELINE_STARTED;
  };

  providers = {
    "appveyor": "APPVEYOR",
    "bamboo": "bamboo_planKey",
    "buildkite": "BUILDKITE",
    "circle": "CIRCLECI",
    "codeship": isCodeship,
    "drone": "DRONE",
    "gitlab": isGitlab,
    "hudson": "HUDSON_URL",
    "jenkins": "JENKINS_URL",
    "semaphore": "SEMAPHORE",
    "shippable": "SHIPPABLE",
    "snap": "SNAP_CI",
    "teamcity": "TEAMCITY_VERSION",
    "teamfoundation": "TF_BUILD",
    "travis": "TRAVIS",
    "wercker": isWercker
  };

  getProviderKey = function() {
    return _.findKey(providers, function(value, key) {
      switch (false) {
        case !_.isString(value):
          return process.env[value];
        case !_.isFunction(value):
          return value();
      }
    });
  };

  module.exports = {
    get: function() {
      var ref;
      return (ref = getProviderKey()) != null ? ref : "unknown";
    }
  };

}).call(this);

});
require.register("./lib/util/routes.js",function (module, exports, require) {(function() {
  var Routes, UrlParse, _, api_url, konfig, parseArgs, routes,
    slice = [].slice;

  _ = require("lodash");

  UrlParse = require("url-parse");

  konfig = require("../konfig");

  api_url = konfig("api_url");

  routes = {
    api: "",
    auth: "auth",
    ping: "ping",
    signin: "signin",
    signout: "signout",
    usage: "user/usage",
    builds: "builds",
    instances: "builds/:id/instances",
    instance: "instances/:id",
    projects: "projects",
    project: "projects/:id",
    projectToken: "projects/:id/token",
    exceptions: "exceptions"
  };

  parseArgs = function(url, args) {
    if (args == null) {
      args = [];
    }
    _.each(args, function(value) {
      switch (false) {
        case !_.isObject(value):
          return url.set("query", _.extend(url.query, value));
        case !(_.isString(value) || _.isNumber(value)):
          return url.set("pathname", url.pathname.replace(":id", value));
      }
    });
    return url;
  };

  Routes = _.reduce(routes, function(memo, value, key) {
    memo[key] = function() {
      var args, url;
      args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
      url = new UrlParse(api_url, true);
      if (value) {
        url.set("pathname", value);
      }
      if (args.length) {
        url = parseArgs(url, args);
      }
      return url.toString();
    };
    return memo;
  }, {});

  module.exports = Routes;

}).call(this);

});
require.register("./lib/util/settings.js",function (module, exports, require) {(function() {
  var Promise, _, errors, flattenCypress, fs, path, renameCommandTimeout, renameSupportFolder, renameVisitToPageLoad;

  _ = require("lodash");

  Promise = require("bluebird");

  path = require("path");

  fs = require("fs-extra");

  errors = require("../errors");

  fs = Promise.promisifyAll(fs);

  flattenCypress = function(obj) {
    var cypress;
    if (cypress = obj.cypress) {
      return cypress;
    }
  };

  renameVisitToPageLoad = function(obj) {
    var v;
    if (v = obj.visitTimeout) {
      obj = _.omit(obj, "visitTimeout");
      obj.pageLoadTimeout = v;
      return obj;
    }
  };

  renameCommandTimeout = function(obj) {
    var c;
    if (c = obj.commandTimeout) {
      obj = _.omit(obj, "commandTimeout");
      obj.defaultCommandTimeout = c;
      return obj;
    }
  };

  renameSupportFolder = function(obj) {
    var sf;
    if (sf = obj.supportFolder) {
      obj = _.omit(obj, "supportFolder");
      obj.supportFile = sf;
      return obj;
    }
  };

  module.exports = {
    _pathToFile: function(projectRoot, file) {
      return path.join(projectRoot, file);
    },
    _err: function(type, file, err) {
      var e;
      e = errors.get(type, file, err);
      e.code = err.code;
      e.errno = err.errno;
      throw e;
    },
    _logReadErr: function(file, err) {
      return this._err("ERROR_READING_FILE", file, err);
    },
    _logWriteErr: function(file, err) {
      return this._err("ERROR_WRITING_FILE", file, err);
    },
    _write: function(file, obj) {
      if (obj == null) {
        obj = {};
      }
      return fs.writeJsonAsync(file, obj, {
        spaces: 2
      })["return"](obj)["catch"]((function(_this) {
        return function(err) {
          return _this._logWriteErr(file, err);
        };
      })(this));
    },
    _applyRewriteRules: function(obj) {
      if (obj == null) {
        obj = {};
      }
      return _.reduce([flattenCypress, renameVisitToPageLoad, renameCommandTimeout, renameSupportFolder], function(memo, fn) {
        var ret;
        if (ret = fn(memo)) {
          return ret;
        } else {
          return memo;
        }
      }, _.cloneDeep(obj));
    },
    read: function(projectRoot) {
      var file;
      file = this._pathToFile(projectRoot, "cypress.json");
      return fs.readJsonAsync(file)["catch"]({
        code: "ENOENT"
      }, (function(_this) {
        return function() {
          return _this._write(file, {});
        };
      })(this)).then((function(_this) {
        return function(json) {
          var changed;
          if (json == null) {
            json = {};
          }
          changed = _this._applyRewriteRules(json);
          if (_.isEqual(json, changed)) {
            return json;
          } else {
            return _this._write(file, changed);
          }
        };
      })(this))["catch"]((function(_this) {
        return function(err) {
          if (errors.isCypressErr(err)) {
            throw err;
          }
          return _this._logReadErr(file, err);
        };
      })(this));
    },
    readEnv: function(projectRoot) {
      var file;
      file = this._pathToFile(projectRoot, "cypress.env.json");
      return fs.readJsonAsync(file)["catch"]({
        code: "ENOENT"
      }, function() {
        return {};
      })["catch"]((function(_this) {
        return function(err) {
          if (errors.isCypressErr(err)) {
            throw err;
          }
          return _this._logReadErr(file, err);
        };
      })(this));
    },
    write: function(projectRoot, obj) {
      if (obj == null) {
        obj = {};
      }
      return this.read(projectRoot).then((function(_this) {
        return function(settings) {
          var file;
          _.extend(settings, obj);
          file = _this._pathToFile(projectRoot, "cypress.json");
          return _this._write(file, settings);
        };
      })(this));
    },
    remove: function(projectRoot) {
      return fs.unlinkSync(this._pathToFile(projectRoot, "cypress.json"));
    },
    pathToCypressJson: function(projectRoot) {
      return this._pathToFile(projectRoot, "cypress.json");
    }
  };

}).call(this);

});
require.register("./lib/util/status_code.js",function (module, exports, require) {(function() {
  var isOkStatusCodeRe, statuses;

  statuses = require("http-status-codes");

  isOkStatusCodeRe = /^[2|3]\d+$/;

  module.exports = {
    isOk: function(code) {
      return code && isOkStatusCodeRe.test(code);
    },
    getText: function(code) {
      var e;
      try {
        return statuses.getStatusText(code);
      } catch (error) {
        e = error;
        return "Unknown Status Code";
      }
    }
  };

}).call(this);

});
require.register("./lib/util/support_folder.js",function (module, exports, require) {(function () {
  Cypress.trigger("script:error", {
    type: "SUPPORT_FOLDER",
    error: ""
  })
}())

});
require.register("./lib/util/terminal.js",function (module, exports, require) {(function() {
  var _, chalk;

  _ = require("lodash");

  chalk = require("chalk");

  module.exports = {
    header: function(message, options) {
      var c, colors;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        color: null
      });
      message = "  (" + chalk.underline.bold(message) + ")";
      if (c = options.color) {
        colors = [].concat(c);
        message = _.reduce(colors, function(memo, color) {
          return chalk[color](memo);
        }, message);
      }
      return console.log(message);
    },
    divider: function(message, options) {
      var a, c, w;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        width: 100,
        preBreak: false,
        postBreak: false
      });
      w = options.width / 2;
      a = function() {
        return Array(Math.floor(w));
      };
      message = " " + message + " ";
      message = a().concat(message, a()).join("=");
      if (c = options.color) {
        message = chalk[c](message);
      }
      if (options.preBreak) {
        console.log("");
      }
      console.log(message);
      if (options.postBreak) {
        return console.log("");
      }
    }
  };

}).call(this);

});
require.register("./lib/util/trash.js",function (module, exports, require) {(function() {
  var Promise, path, trash;

  path = require("path");

  trash = require("trash");

  Promise = require("bluebird");

  module.exports = {
    folder: function(pathToFolder) {
      return Promise.resolve(trash([pathToFolder]));
    }
  };

}).call(this);

});
require.register("./lib/video.js",function (module, exports, require) {(function() {
  var Promise, _, ffmpeg, ffmpegPath, fs, stream, utils;

  _ = require("lodash");

  fs = require("fs-extra");

  utils = require("fluent-ffmpeg/lib/utils");

  ffmpeg = require("fluent-ffmpeg");

  stream = require("stream");

  Promise = require("bluebird");

  ffmpegPath = require("@ffmpeg-installer/ffmpeg").path;

  fs = Promise.promisifyAll(fs);

  ffmpeg.setFfmpegPath(ffmpegPath);

  module.exports = {
    copy: function(src, dest) {
      return fs.copyAsync(src, dest, {
        clobber: true
      })["catch"]({
        code: "ENOENT"
      }, function() {});
    },
    start: function(name, options) {
      var cmd, done, end, ended, errored, pt, skipped, started, wantsWrite, write;
      if (options == null) {
        options = {};
      }
      pt = stream.PassThrough();
      started = Promise.pending();
      ended = Promise.pending();
      done = false;
      errored = false;
      wantsWrite = true;
      skipped = 0;
      _.defaults(options, {
        onError: function() {}
      });
      end = function() {
        pt.end();
        done = true;
        if (errored) {
          errored.recordingVideoFailed = true;
          return Promise.reject(errored);
        } else {
          return Promise.resolve(ended.promise);
        }
      };
      write = function(data) {
        if (done) {
          return;
        }
        if (wantsWrite) {
          if (!(wantsWrite = pt.write(data))) {
            return pt.once("drain", function() {
              return wantsWrite = true;
            });
          }
        } else {
          return skipped += 1;
        }
      };
      cmd = ffmpeg({
        source: pt,
        priority: 20
      }).inputFormat("image2pipe").inputOptions("-use_wallclock_as_timestamps 1").videoCodec("libx264").outputOptions("-preset ultrafast").save(name).on("start", function(line) {
        return started.resolve(new Date);
      }).on("error", function(err, stdout, stderr) {
        options.onError(err, stdout, stderr);
        return errored = err;
      }).on("end", function() {
        return ended.resolve();
      });
      return {
        cmd: cmd,
        end: end,
        start: started.promise,
        write: write
      };
    },
    process: function(name, cname, videoCompression, onProgress) {
      var total;
      if (onProgress == null) {
        onProgress = function() {};
      }
      total = null;
      return new Promise(function(resolve, reject) {
        var cmd;
        return cmd = ffmpeg().input(name).videoCodec("libx264").outputOptions(["-preset fast", "-crf " + videoCompression]).save(cname).on("codecData", function(data) {
          return total = utils.timemarkToSeconds(data.duration);
        }).on("progress", function(progress) {
          var progressed;
          if (!total) {
            return;
          }
          progressed = utils.timemarkToSeconds(progress.timemark);
          return onProgress(progressed / total);
        }).on("error", function(err, stdout, stderr) {
          return reject(err);
        }).on("end", function() {
          onProgress(1);
          return fs.moveAsync(cname, name, {
            clobber: true
          }).then(function() {
            return resolve();
          });
        });
      });
    }
  };

}).call(this);

});
require.register("./lib/watchers.js",function (module, exports, require) {(function() {
  var Watchers, _, bundle, chokidar, pathHelpers;

  _ = require("lodash");

  chokidar = require("chokidar");

  bundle = require("./util/bundle");

  pathHelpers = require("./util/path_helpers");

  Watchers = (function() {
    function Watchers() {
      if (!(this instanceof Watchers)) {
        return new Watchers;
      }
      this.watchers = {};
      this.bundleWatchers = {};
    }

    Watchers.prototype.close = function() {
      var filePath, results;
      for (filePath in this.watchers) {
        this._remove(filePath);
      }
      results = [];
      for (filePath in this.bundleWatchers) {
        results.push(this.removeBundle(filePath));
      }
      return results;
    };

    Watchers.prototype.watch = function(filePath, options) {
      var w;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        interval: 250,
        usePolling: true,
        useFsEvents: false,
        ignored: null,
        onChange: null,
        onReady: null,
        onError: null
      });
      w = chokidar.watch(filePath, options);
      this._add(filePath, w);
      if (_.isFunction(options.onChange)) {
        w.on("change", options.onChange);
      }
      if (_.isFunction(options.onReady)) {
        w.on("ready", options.onReady);
      }
      if (_.isFunction(options.onError)) {
        w.on("error", options.onError);
      }
      return this;
    };

    Watchers.prototype._add = function(filePath, watcher) {
      this._remove(filePath);
      return this.watchers[filePath] = watcher;
    };

    Watchers.prototype._remove = function(filePath) {
      var watcher;
      if (!(watcher = this.watchers[filePath])) {
        return;
      }
      watcher.close();
      return delete this.watchers[filePath];
    };

    Watchers.prototype.watchBundle = function(filePath, config, options) {
      var watcher;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        onChange: null,
        onReady: null
      });
      if (!(watcher = this.bundleWatchers[filePath])) {
        watcher = bundle.build(filePath, config);
        this._addBundle(filePath, watcher);
      }
      if (_.isFunction(options.onChange)) {
        watcher.addChangeListener(options.onChange);
      }
      return watcher.getLatestBundle();
    };

    Watchers.prototype._addBundle = function(filePath, watcher) {
      return this.bundleWatchers[filePath] = watcher;
    };

    Watchers.prototype.removeBundle = function(filePath) {
      var watcher;
      if (!(watcher = this.bundleWatchers[filePath])) {
        return;
      }
      watcher.close();
      return delete this.bundleWatchers[filePath];
    };

    return Watchers;

  })();

  module.exports = Watchers;

}).call(this);

});
this_module.exports = require("./index.js");
}(require, module));