(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) {require("coffee-script/register")
require("./lib/cypress").start(process.argv)
});
require.register("./lib/api.js",function (module, exports, require) {(function() {
  var Routes, errors, os, pkg, provider, r, rp;

  os = require("os");

  r = require("request");

  rp = require("request-promise");

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

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

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

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

  module.exports = {
    ping: function() {
      return rp.get(Routes.ping());
    },
    createCi: function(options) {
      if (options == null) {
        options = {};
      }
      return rp.post({
        url: Routes.ci(options.projectId),
        json: true,
        headers: {
          "x-project-token": options.key,
          "x-git-branch": options.branch,
          "x-git-author": options.author,
          "x-git-message": options.message,
          "x-version": pkg.version,
          "x-platform": os.platform(),
          "x-provider": provider.get()
        }
      }).promise().get("ci_guid");
    },
    updateCi: function(options) {
      if (options == null) {
        options = {};
      }
      return rp.put({
        url: Routes.ci(options.projectId),
        json: true,
        body: options.stats,
        timeout: 10000,
        headers: {
          "x-ci-id": options.ciId,
          "x-project-token": options.key,
          "x-version": pkg.version,
          "x-platform": os.platform(),
          "x-provider": provider.get()
        }
      });
    },
    createRaygunException: function(body, session, timeout) {
      if (timeout == null) {
        timeout = 3000;
      }
      return rp.post({
        url: Routes.exceptions(),
        body: body,
        json: true,
        headers: {
          "x-session": session
        }
      }).promise().timeout(timeout);
    },
    createSignin: function(code) {
      return rp.post({
        url: Routes.signin({
          code: code
        }),
        json: true,
        headers: {
          "x-platform": os.platform(),
          "x-version": pkg.version
        }
      })["catch"](errors.StatusCodeError, function(err) {
        err.message = err.message.split(" - ").slice(1).join("");
        throw err;
      });
    },
    createSignout: function(session) {
      return rp.post({
        url: Routes.signout(),
        headers: {
          "x-session": session,
          "x-platform": os.platform(),
          "x-version": pkg.version
        }
      });
    },
    createProject: function(session) {
      return rp.post({
        url: Routes.projects(),
        json: true,
        headers: {
          "x-session": session,
          "x-platform": os.platform(),
          "x-version": pkg.version
        }
      }).promise().get("uuid");
    },
    updateProject: function(projectId, type, session) {
      return rp.get({
        url: Routes.project(projectId),
        json: true,
        headers: {
          "x-type": type,
          "x-session": session,
          "x-platform": os.platform(),
          "x-version": pkg.version
        }
      });
    },
    getBuilds: function(projectId, session) {
      return r.get({
        url: Routes.projectCi(projectId),
        json: true,
        headers: {
          "x-session": session
        }
      });
    },
    getLoginUrl: function() {
      return rp.get({
        url: Routes.auth(),
        json: true
      }).promise().get("url");
    },
    _token: function(method, session) {
      return rp({
        method: method,
        url: Routes.token(),
        json: true,
        headers: {
          "x-session": session
        }
      }).promise().get("api_token");
    },
    getToken: function(session) {
      return this._token("get", session);
    },
    updateToken: function() {
      return this._token("put", session);
    },
    _projectToken: function(method, projectId, session) {
      return rp({
        method: method,
        url: Routes.projectToken(projectId),
        json: true,
        headers: {
          "x-session": session
        }
      }).promise().get("api_token");
    },
    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/cache.js",function (module, exports, require) {(function() {
  var CACHE, PSemaphore, Promise, _, api, config, errors, fs, logger, path, queue, request,
    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;

  _ = require("lodash");

  fs = require("fs-extra");

  path = require("path");

  Promise = require("bluebird");

  PSemaphore = require("promise-semaphore");

  request = require("request-promise");

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

  api = require("./api");

  config = require("./config");

  logger = require("./logger");

  CACHE = config.app.cache_path;

  fs = Promise.promisifyAll(fs);

  queue = new PSemaphore;

  module.exports = {
    path: CACHE,
    ensureExists: function() {
      return queue.add((function(_this) {
        return function() {
          return fs.readJsonAsync(CACHE).then(function(json) {
            if (!json.USER) {
              json.USER = {};
            }
            if (!json.PROJECTS) {
              json.PROJECTS = [];
            }
            return _this.write(json, false);
          }).then(function(json) {
            if (!_.isArray(json.PROJECTS)) {
              json = _this.convertLegacyCache(json);
              return _this.write(json, false);
            }
          })["return"](true)["catch"](function() {
            return _this.write(_this.defaults(), false);
          });
        };
      })(this));
    },
    exists: function() {
      return this.ensureExists()["return"](true)["catch"](false);
    },
    defaults: function() {
      return {
        USER: {},
        PROJECTS: []
      };
    },
    convertLegacyCache: function(json) {
      json.PROJECTS = _.chain(json.PROJECTS).values().map("PATH").compact().value();
      return json;
    },
    read: function() {
      return this.ensureExists().then(function() {
        return queue.add((function(_this) {
          return function() {
            return fs.readJsonAsync(CACHE);
          };
        })(this));
      });
    },
    write: function(obj, enableQueue) {
      var write;
      if (obj == null) {
        obj = {};
      }
      if (enableQueue == null) {
        enableQueue = true;
      }
      logger.info("writing to .cy cache", {
        cache: obj
      });
      write = function() {
        return fs.outputJsonAsync(CACHE, obj, {
          spaces: 2
        })["return"](obj);
      };
      if (enableQueue) {
        return queue.add(write);
      } else {
        return write();
      }
    },
    _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];
      });
    },
    insertProject: function(path) {
      return this._getProjects().then((function(_this) {
        return function(projects) {
          if (indexOf.call(projects, path) >= 0) {
            return projects;
          }
          projects.push(path);
          return _this._set("PROJECTS", projects);
        };
      })(this));
    },
    _getProjects: function() {
      return this._get("PROJECTS");
    },
    _removeProjects: function(projects, paths) {
      projects = _.without.apply(_, [projects].concat(slice.call([].concat(paths))));
      return this._set({
        PROJECTS: projects
      });
    },
    getProjectPaths: function() {
      return this._getProjects().then((function(_this) {
        return function(projects) {
          var pathsToRemove;
          pathsToRemove = Promise.reduce(projects, function(memo, path) {
            return queue.add(function() {
              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 this._getProjects().then((function(_this) {
        return function(projects) {
          return _this._removeProjects(projects, path);
        };
      })(this));
    },
    getUser: function() {
      logger.info("getting user");
      return this._get("USER");
    },
    setUser: function(user) {
      logger.info("setting user", {
        user: user
      });
      return this._set({
        USER: user
      });
    },
    removeUser: function() {
      return this._set({
        USER: {}
      });
    },
    remove: function() {
      return fs.removeAsync(CACHE);
    },
    removeSync: function() {
      return fs.removeSync(CACHE);
    }
  };

}).call(this);

});
require.register("./lib/config.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();
    process.env["NODE_ENV"] = previousNodeEnv;
    return config;
  };

  module.exports = getConfig();

}).call(this);

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

  request = require("request");

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

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

  Builds = (function() {
    function Builds(app) {
      if (!(this instanceof Builds)) {
        return new Builds(app);
      }
      if (!app) {
        throw new Error("Instantiating controllers/proxy requires an app!");
      }
      this.app = app;
    }

    Builds.prototype.handleBuilds = function(req, res, next) {
      return user.get().then((function(_this) {
        return function(user) {
          return api.getBuilds(_this.app.get("cypress").projectId, user != null ? user.session_token : void 0).on("error", next).pipe(res);
        };
      })(this));
    };

    return Builds;

  })();

  module.exports = Builds;

}).call(this);

});
require.register("./lib/controllers/files.js",function (module, exports, require) {(function() {
  var CacheBuster, Files, Promise, _, cwd, glob, path;

  _ = require("underscore");

  _.str = require("underscore.string");

  path = require("path");

  glob = require("glob");

  Promise = require("bluebird");

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

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

  Files = (function() {
    function Files(app) {
      if (!(this instanceof Files)) {
        return new Files(app);
      }
      if (!app) {
        throw new Error("Instantiating controllers/proxy requires an app!");
      }
      this.app = app;
    }

    Files.prototype.handleFiles = function(req, res) {
      return this.getTestFiles().then(function(files) {
        res.set("X-Files-Path", files.path);
        return res.json(files);
      });
    };

    Files.prototype.handleIframe = function(req, res) {
      var filePath, test;
      test = req.params[0];
      filePath = cwd("lib", "html", "empty_inject.html");
      return this.getSpecs(test).bind(this).then(function(specs) {
        return this.getJavascripts().bind(this).then(function(js) {
          return res.render(filePath, {
            title: this.getTitle(test),
            javascripts: js,
            utilities: this.getUtilities(),
            specs: specs
          });
        });
      });
    };

    Files.prototype.getTitle = function(test) {
      if (test === "__all") {
        return "All Tests";
      } else {
        return test;
      }
    };

    Files.prototype.convertToAbsolutePath = function(files) {
      files = _([files]).flatten();
      return files.map(function(files) {
        if (/^\//.test(files)) {
          return files;
        } else {
          return "/" + files;
        }
      });
    };

    Files.prototype.convertToSpecPath = function(specs, options) {
      var ref, rootFolder, supportFolder, testFolder;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        test: true
      });
      ref = this.app.get("cypress"), testFolder = ref.testFolder, rootFolder = ref.rootFolder, supportFolder = ref.supportFolder;
      return _(specs).map(function(spec) {
        if (_.str.contains(spec, supportFolder)) {
          spec = _.str.trim(spec, "/");
        } else {
          if (options.test) {
            spec = testFolder + "/" + spec;
          } else {
            spec = _.compact([rootFolder, spec]);
            spec = path.join.apply(path, spec);
            spec = _.str.trim(spec, "/");
          }
        }
        spec += CacheBuster.get();
        return "/__cypress/tests?p=" + spec;
      });
    };

    Files.prototype.getSpecs = function(test) {
      if (test === "__all") {
        return this.getTestFiles().then((function(_this) {
          return function(specs) {
            return _this.convertToSpecPath(_(specs).pluck("name"));
          };
        })(this));
      } else {
        return Promise.resolve(this.convertToSpecPath([test]));
      }
    };

    Files.prototype.getStylesheets = function() {
      return this.convertToAbsolutePath(this.app.get("cypress").stylesheets);
    };

    Files.prototype.getJavascripts = function() {
      var files, javascripts, paths, projectRoot, ref, supportFolder;
      ref = this.app.get("cypress"), projectRoot = ref.projectRoot, javascripts = ref.javascripts, supportFolder = ref.supportFolder;
      files = [].concat(path.join(supportFolder, "**", "*"), javascripts);
      paths = this.convertToAbsolutePath(_.chain(files).compact().uniq().value());
      return Promise.map(paths, function(p) {
        if (!p.includes("*")) {
          return p;
        }
        return new Promise(function(resolve, reject) {
          p = path.join(projectRoot, p);
          return glob(p, function(err, files) {
            if (err) {
              reject(err);
            }
            return resolve(files);
          });
        });
      }).then(function(files) {
        return _.chain(files).flatten().map(function(file) {
          return file.replace(projectRoot, "");
        }).value();
      }).then((function(_this) {
        return function(files) {
          return _this.convertToSpecPath(files, {
            test: false
          });
        };
      })(this));
    };

    Files.prototype.getUtilities = function() {
      var utils;
      utils = ["iframe"];
      if (this.app.get("cypress").sinon) {
        utils.push("sinon");
      }
      if (this.app.get("cypress").fixtures) {
        utils.push("fixtures");
      }
      return utils.map(function(util) {
        return "/__cypress/static/js/" + util + ".js";
      });
    };

    Files.prototype.getTestFiles = function() {
      var cypress, fixturesFolderPath, javascriptsPath, supportFolderPath, testFolderPath;
      cypress = this.app.get("cypress");
      testFolderPath = path.join(cypress.projectRoot, cypress.testFolder);
      fixturesFolderPath = path.join(cypress.projectRoot, cypress.fixturesFolder, "**", "*");
      supportFolderPath = path.join(cypress.projectRoot, cypress.supportFolder, "**", "*");
      javascriptsPath = _.map(cypress.javascripts, function(js) {
        return path.join(cypress.projectRoot, js);
      });
      return new Promise(function(resolve, reject) {
        var options;
        options = {
          sort: true,
          ignore: [].concat(javascriptsPath, supportFolderPath, fixturesFolderPath)
        };
        return glob(testFolderPath + "/**/*.+(js|coffee)", options, function(err, files) {
          var testFolderLength;
          if (err) {
            reject(err);
          }
          testFolderLength = testFolderPath.split("/").length;
          files = _(files).map(function(file) {
            return {
              name: file.split("/").slice(testFolderLength).join("/")
            };
          });
          files.path = testFolderPath;
          return resolve(files);
        });
      });
    };

    return Files;

  })();

  module.exports = Files;

}).call(this);

});
require.register("./lib/controllers/index.js",function (module, exports, require) {(function() {
  module.exports = function(app) {
    return {
      xhrs: require("./xhrs")(app),
      files: require("./files")(app),
      builds: require("./builds")(app),
      proxy: require("./proxy")(app),
      specProcessor: require("./spec_processor")(app)
    };
  };

}).call(this);

});
require.register("./lib/controllers/proxy.js",function (module, exports, require) {(function() {
  var Domain, Proxy, UrlHelpers, _, badCookieParamRe, cwd, escapeRegExp, fs, headRe, htmlRe, jsUri, logger, mime, okStatusRe, path, request, through, trumpet, urlHelpers;

  _ = require("lodash");

  path = require("path");

  fs = require("fs");

  request = require("request");

  mime = require("mime");

  path = require("path");

  Domain = require("domain");

  through = require("through");

  jsUri = require("jsuri");

  trumpet = require("trumpet");

  urlHelpers = require("url");

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

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

  UrlHelpers = require("../util/url_helpers");

  escapeRegExp = require("../util/escape_regexp");

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

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

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

  badCookieParamRe = /^(httponly|secure|domain=.+)$/i;

  Proxy = (function() {
    function Proxy(app) {
      if (!(this instanceof Proxy)) {
        return new Proxy(app);
      }
      if (!app) {
        throw new Error("Instantiating controllers/proxy requires an app!");
      }
      this.app = app;
    }

    Proxy.prototype.handle = function(req, res, next) {
      var d, getRemoteHost;
      if (req.cookies["__cypress.unload"]) {
        return res.redirect(this.app.get("cypress").clientRoute);
      }
      getRemoteHost = (function(_this) {
        return function(req) {
          var ref, ref1, ref2;
          return (ref = (ref1 = (ref2 = _this.getOriginFromFqdnUrl(req)) != null ? ref2 : req.cookies["__cypress.remoteHost"]) != null ? ref1 : _this.app.get("cypress").baseUrl) != null ? ref : _this.app.get("__cypress.remoteHost");
        };
      })(this);
      d = Domain.create();
      d.on('error', (function(_this) {
        return function(e) {
          return _this.errorHandler(e, req, res, getRemoteHost(req));
        };
      })(this));
      return d.run((function(_this) {
        return function() {
          var remoteHost, thr;
          remoteHost = getRemoteHost(req);
          logger.info("handling initial request", {
            url: req.url,
            remoteHost: remoteHost
          });
          if (!remoteHost) {
            return res.redirect(_this.app.get("cypress").clientRoute);
          }
          thr = through(function(d) {
            return this.queue(d);
          });
          return _this.getContent(thr, req, res, remoteHost).on("error", function(e) {
            return _this.errorHandler(e, req, res, remoteHost);
          }).pipe(res);
        };
      })(this));
    };

    Proxy.prototype.getOriginFromFqdnUrl = function(req) {
      var origin;
      if (origin = UrlHelpers.getOriginFromFqdnUrl(req.url)) {
        req.url = "/" + req.url.replace(origin, "").replace(/^\/+/, "");
        return origin;
      }
    };

    Proxy.prototype.getContent = function(thr, req, res, remoteHost) {
      switch (remoteHost) {
        case "<root>":
          return this.getFileContent(thr, req, res, remoteHost);
        default:
          return this.getHttpContent(thr, req, res, remoteHost);
      }
    };

    Proxy.prototype.getHttpContent = function(thr, req, res, remoteHost) {
      var opts, remoteUrl, rq, setCookies;
      process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
      remoteUrl = urlHelpers.resolve(remoteHost, req.url);
      setCookies = (function(_this) {
        return function(initial, remoteHost) {
          if (req.cookies["__cypress.initial"] !== "true") {
            return;
          }
          res.cookie("__cypress.initial", initial);
          res.cookie("__cypress.remoteHost", remoteHost);
          return _this.app.set("__cypress.remoteHost", remoteHost);
        };
      })(this);
      opts = {
        url: remoteUrl,
        gzip: false,
        followRedirect: false,
        strictSSL: false
      };
      if (req.cookies["__cypress.initial"] === "true") {
        delete req.headers["accept-encoding"];
      }
      req.headers = this.mapHeaders(req.headers, req.protocol + "://" + req.get("host"), req.cookies["__cypress.remoteHost"]);
      rq = request(opts);
      rq.on("error", function(err) {
        return thr.emit("error", err);
      });
      rq.on("response", (function(_this) {
        return function(incomingRes) {
          var cookies, isInitial, newUrl;
          _this.setResHeaders(req, res, incomingRes, remoteHost);
          if (cookies = incomingRes.headers["set-cookie"]) {
            res.append("Set-Cookie", _this.stripCookieParams(cookies));
          }
          if (/^30(1|2|3|7|8)$/.test(incomingRes.statusCode)) {
            newUrl = new jsUri(UrlHelpers.mergeOrigin(remoteUrl, incomingRes.headers.location));
            setCookies(true, newUrl.origin());
            logger.info("redirecting to new url", {
              status: incomingRes.statusCode,
              url: newUrl.toString()
            });
            isInitial = req.cookies["__cypress.initial"] === "true";
            return res.redirect(_this.getUrlForRedirect(newUrl, req.cookies["__cypress.remoteHost"], isInitial));
          } else {
            res.status(incomingRes.statusCode);
            if (!okStatusRe.test(incomingRes.statusCode)) {
              return _this.errorHandler(null, req, res, remoteHost);
            }
            logger.info("received absolute file content");
            setCookies(false, remoteHost);
            if (req.cookies["__cypress.initial"] === "true") {
              return rq.pipe(_this.rewrite(req, res, remoteHost)).pipe(thr);
            } else {
              return rq.pipe(thr);
            }
          }
        };
      })(this));
      req.pipe(rq);
      return thr;
    };

    Proxy.prototype.getFileContent = function(thr, req, res, remoteHost) {
      var args, file, stream;
      args = _.compact([this.app.get("cypress").projectRoot, this.app.get("cypress").rootFolder, req.url]);
      file = decodeURI(urlHelpers.parse(path.join.apply(path, args)).pathname);
      req.formattedUrl = file;
      logger.info("getting relative file content", {
        file: file
      });
      res.contentType(mime.lookup(file));
      res.cookie("__cypress.initial", false);
      res.cookie("__cypress.remoteHost", remoteHost);
      this.app.set("__cypress.remoteHost", remoteHost);
      stream = fs.createReadStream(file, "utf8");
      if (req.cookies["__cypress.initial"] === "true") {
        stream.pipe(this.rewrite(req, res, remoteHost)).pipe(thr);
      } else {
        stream.pipe(thr);
      }
      return thr;
    };

    Proxy.prototype.errorHandler = function(e, req, res, remoteHost) {
      var f, filePath, htmlPath, url;
      url = urlHelpers.resolve(remoteHost, req.url);
      if (process.env["CYPRESS_ENV"] !== "production" && e && e.code !== "ENOENT") {
        console.error(e.stack);
        debugger;
      }
      logger.info("error handling initial request", {
        url: url,
        error: e
      });
      if (e) {
        res.set("x-cypress-error", e.message);
        res.set("x-cypress-stack", e.stack.replace("\n", "\\n"));
      }
      filePath = (function() {
        switch (false) {
          case !(f = req.formattedUrl):
            return "file://" + f;
          default:
            return url;
        }
      })();
      htmlPath = cwd("lib", "html", "initial_500.html");
      return res.status(500).render(htmlPath, {
        url: filePath,
        fromFile: !!req.formattedUrl
      });
    };

    Proxy.prototype.mapHeaders = function(headers, currentHost, remoteHost) {
      var hostRe;
      hostRe = new RegExp(escapeRegExp(currentHost), "ig");
      return _.mapValues(headers, function(value, key) {
        key = key.toLowerCase();
        if (key === "referer" || key === "origin" || key.startsWith("x-")) {
          return value.replace(hostRe, remoteHost);
        } else {
          return value;
        }
      });
    };

    Proxy.prototype.setResHeaders = function(req, res, incomingRes, remoteHost) {
      var headers;
      headers = _.omit(incomingRes.headers, "set-cookie", "x-frame-options", "content-length", "content-security-policy");
      headers = this.mapHeaders(headers, remoteHost, req.get("host"));
      headers["cache-control"] = "no-cache, no-store, must-revalidate";
      return res.set(headers);
    };

    Proxy.prototype.getUrlForRedirect = function(newUrl, remoteHostCookie, isInitial) {
      if (isInitial || (newUrl.origin() === remoteHostCookie)) {
        return newUrl.toString().replace(newUrl.origin(), "");
      } else {
        return "/" + newUrl.toString();
      }
    };

    Proxy.prototype.stripCookieParams = function(cookies) {
      var stripHttpOnlyAndSecure;
      stripHttpOnlyAndSecure = (function(_this) {
        return function(cookie) {
          var parts;
          parts = _.invoke(cookie.split(";"), "trim");
          parts = _.reject(parts, function(part) {
            return badCookieParamRe.test(part);
          });
          return parts.join("; ");
        };
      })(this);
      return _.map([].concat(cookies), stripHttpOnlyAndSecure);
    };

    Proxy.prototype.rewrite = function(req, res, remoteHost) {
      var changeToAbsoluteRelative, removeRemoteHostOrMakeAbsoluteRelative, rewrite, tr;
      through = through;
      tr = trumpet();
      changeToAbsoluteRelative = function(str) {
        return "/" + req.protocol + ":" + str;
      };
      removeRemoteHostOrMakeAbsoluteRelative = function(str) {
        if (str.startsWith(remoteHost)) {
          return str.replace(remoteHost, "");
        } else {
          return "/" + str;
        }
      };
      rewrite = function(selector, type, attr, fn) {
        var options;
        options = {};
        switch (false) {
          case !_.isFunction(attr):
            fn = attr;
            attr = null;
            break;
          case !_.isPlainObject(attr):
            options = attr;
        }
        if (options.method == null) {
          options.method = "selectAll";
        }
        return tr[options.method](selector, function(elem) {
          var stream;
          switch (type) {
            case "attr":
              return elem.getAttribute(attr, function(val) {
                return elem.setAttribute(attr, fn(val));
              });
            case "removeAttr":
              return elem.removeAttribute(attr);
            case "html":
              if (options.outer == null) {
                options.outer = true;
              }
              stream = elem.createStream({
                outer: options.outer
              });
              return stream.pipe(through(function(buf) {
                return this.queue(fn(buf.toString()));
              })).pipe(stream);
          }
        });
      };
      rewrite("head", "html", (function(_this) {
        return function(str) {
          return str.replace(headRe, "$1 " + (_this.getHeadContent()));
        };
      })(this));
      rewrite("[href^='//']", "attr", "href", changeToAbsoluteRelative);
      rewrite("form[action^='//']", "attr", "action", changeToAbsoluteRelative);
      rewrite("form[action^='http']", "attr", "action", removeRemoteHostOrMakeAbsoluteRelative);
      rewrite("[href^='http']", "attr", "href", removeRemoteHostOrMakeAbsoluteRelative);
      return tr;
    };

    Proxy.prototype.getHeadContent = function() {
      return "<script type='text/javascript'> window.onerror = function(){ parent.onerror.apply(parent, arguments); } </script> <script type='text/javascript' src='/__cypress/static/js/sinon.js'></script> <script type='text/javascript'> var Cypress = parent.Cypress; if (!Cypress){ throw new Error('Cypress must exist in the parent window!'); }; Cypress.onBeforeLoad(window); </script>";
    };

    return Proxy;

  })();

  module.exports = Proxy;

}).call(this);

});
require.register("./lib/controllers/spec_processor.js",function (module, exports, require) {(function() {
  var Domain, Snockets, SpecProcessor, Stream, _, browserify, coffee, coffeeify, fs, gutil, path, requirejs;

  fs = require('fs');

  _ = require('lodash');

  path = require('path');

  gutil = require('gulp-util');

  Stream = require('stream');

  coffee = require('coffee-script');

  browserify = require('browserify');

  coffeeify = require('coffeeify');

  Domain = require('domain');

  Snockets = require('snockets');

  requirejs = require('requirejs');

  SpecProcessor = (function() {
    function SpecProcessor(app) {
      if (!(this instanceof SpecProcessor)) {
        return new SpecProcessor(app);
      }
      this.app = app;
    }

    SpecProcessor.prototype.browserify = function(opts, fileStream) {
      return browserify([fileStream], opts).transform({}, coffeeify).bundle();
    };

    SpecProcessor.prototype.handle = function(spec, req, res, next) {
      var config, contents, dependencies, domain, filePath, settings, snockets, stream;
      res.set({
        "Cache-Control": "no-cache, no-store, must-revalidate",
        "Pragma": "no-cache",
        "Expires": "0"
      });
      res.type("js");
      settings = this.app.get("cypress");
      filePath = path.join(settings.projectRoot, spec);
      config = {
        baseUrl: settings.projectRoot,
        name: filePath,
        out: "main.js"
      };
      if (settings.requirejs) {
        requirejs.optimize(config, function(buildResponse) {
          var contents;
          contents = fs.readFileSync(config.out, 'utf8');
          debugger;
        });
      }
      snockets = new Snockets();
      dependencies = snockets.getCompiledChain(filePath, {
        async: false
      });
      contents = _.pluck(dependencies, "js").join(";\n");
      stream = new Stream.Readable();
      stream.push(contents);
      stream.push(null);
      domain = Domain.create();
      domain.on('error', function() {
        gutil.beep();
        return next.apply(null, arguments);
      });
      return domain.run((function(_this) {
        return function() {
          var opts;
          if (opts = settings.browserify) {
            return _this.browserify(opts, stream).pipe(res);
          } else {
            return stream.pipe(res);
          }
        };
      })(this));
    };

    return SpecProcessor;

  })();

  module.exports = SpecProcessor;

}).call(this);

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

  _ = require("lodash");

  mime = require("mime");

  request = require("request");

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

  Promise = require("bluebird");

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

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

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

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

  Xhr = (function() {
    function Xhr(app) {
      if (!(this instanceof Xhr)) {
        return new Xhr(app);
      }
      if (!app) {
        throw new Error("Instantiating controllers/xhr requires an app!");
      }
      this.app = app;
    }

    Xhr.prototype._get = function(resp) {
      var file, fixturesFolder, projectRoot, ref;
      file = resp.replace(fixturesRe, "");
      ref = this.app.get("cypress"), projectRoot = ref.projectRoot, fixturesFolder = ref.fixturesFolder;
      return fixture.get(projectRoot, fixturesFolder, file);
    };

    Xhr.prototype.getStream = function(resp) {
      if (fixturesRe.test(resp)) {
        return this._get(resp).then(function(contents) {
          return str(contents);
        });
      } else {
        return str(resp);
      }
    };

    Xhr.prototype.getResponse = function(resp) {
      if (fixturesRe.test(resp)) {
        return this._get(resp);
      } else {
        return Promise.resolve(resp);
      }
    };

    Xhr.prototype.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");
      }
    };

    Xhr.prototype.parseHeaders = function(headers, response) {
      try {
        headers = JSON.parse(headers);
      } catch (undefined) {}
      if (headers == null) {
        headers = {};
      }
      if (headers["content-type"] == null) {
        headers["content-type"] = this.parseContentType(response);
      }
      return headers;
    };

    Xhr.prototype.handleXhr = function(req, res, next) {
      var delay, headers, ref, ref1, ref2, respond, response, status;
      delay = ~~req.get("x-cypress-delay");
      status = (ref = req.get("x-cypress-status")) != null ? ref : 200;
      headers = (ref1 = req.get("x-cypress-headers")) != null ? ref1 : null;
      response = (ref2 = req.get("x-cypress-response")) != null ? ref2 : "";
      respond = (function(_this) {
        return function() {
          return _this.getResponse(response).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();
      }
    };

    return Xhr;

  })();

  module.exports = Xhr;

}).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 Project, Promise, _, api, argsUtil, cp, errors, exit, exit0, exitErr, logger, logs, path, returnPkg, smokeTest;

  require("./environment");

  _ = require("lodash");

  cp = require("child_process");

  path = require("path");

  Promise = require("bluebird");

  api = require("./api");

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

  logger = require("./logger");

  errors = require("./errors");

  Project = require("./project");

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

  smokeTest = require("./modes/smoke_test");

  returnPkg = require("./modes/pkg");

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

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

  exitErr = function(err) {
    return 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() {
          var args;
          if (_this.isCurrentlyRunningElectron()) {
            return require("./electron")(mode, options);
          } else {
            api.ping()["catch"](function(err) {
              console.log(err.message);
              return errors.warning("DEV_NO_SERVER");
            });
            args = ["."].concat(argsUtil.toArray(options));
            return new Promise(function(resolve, reject) {
              var electron;
              electron = cp.spawn("electron", args, {
                stdio: "inherit"
              });
              return electron.on("close", function(code, signal) {
                return resolve(code);
              });
            });
          }
        };
      })(this));
    },
    openProject: function(options) {
      return Project(options.project).open();
    },
    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: ["--", "--mode", "openProject", "--project", options.project]
      });
      args = _.chain(args).values().flatten().value();
      cp.spawn("nodemon", args, {
        stdio: "inherit"
      });
      if (options.autoOpen) {
        _.delay(function() {
          return require("open")("http://localhost:2020/__");
        }, 2000);
      }
      if (options.debug) {
        cp.spawn("node-inspector", [], {
          stdio: "inherit"
        });
        return require("open")("http://127.0.0.1:8080/debug?ws=127.0.0.1:8080&port=5858");
      }
    },
    start: function(argv) {
      var mode, options;
      if (argv == null) {
        argv = [];
      }
      logger.info("starting desktop app", {
        args: argv
      });
      options = argsUtil.toObject(argv);
      switch (false) {
        case !options.removeIds:
          options.mode = "removeIds";
          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.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);
    },
    startInMode: function(mode, options) {
      switch (mode) {
        case "removeIds":
          return 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 "smokeTest":
          return smokeTest(options).then(function(pong) {
            return console.log(pong);
          }).then(exit0)["catch"](exitErr);
        case "returnPkg":
          return returnPkg(options).then(function(pkg) {
            return console.log(JSON.stringify(pkg));
          }).then(exit0)["catch"](exitErr);
        case "logs":
          return logs.print().then(exit0)["catch"](exitErr);
        case "clearLogs":
          return logs.clear().then(exit0)["catch"](exitErr);
        case "getKey":
          return Project.getSecretKeyByPath(options.projectPath).then(function(key) {
            return console.log(key);
          }).then(exit0)["catch"](exitErr);
        case "generateKey":
          return Project.generateSecretKeyByPath(options.projectPath).then(function(key) {
            return console.log(key);
          }).then(exit0)["catch"](exitErr);
        case "headless":
          return this.runElectron(mode, options).then(exit0)["catch"](exitErr);
        case "headed":
          return this.runElectron(mode, options);
        case "ci":
          return this.runElectron(mode, options).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/cookies.js",function (module, exports, require) {(function() {
  var Promise;

  Promise = require("bluebird");

  module.exports = {
    clearGithub: function(cookies) {
      var removeCookie;
      cookies = Promise.promisifyAll(cookies);
      removeCookie = function(cookie) {
        var prefix, url;
        prefix = cookie.secure ? "https://" : "http://";
        if (cookie.domain[0] === ".") {
          prefix += "www";
        }
        url = prefix + cookie.domain + cookie.path;
        return cookies.removeAsync(url, cookie.name);
      };
      return cookies.getAsync({
        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(Renderer.get("INDEX"), 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, cypressIcons, dialog, errors, handleEvent, ipc, logs, pgk, project, shell, user;

  _ = require("lodash");

  ipc = require("electron").ipcMain;

  shell = require("electron").shell;

  cypressIcons = require("cypress-icons");

  dialog = require("./dialog");

  project = require("./project");

  pgk = require("./package");

  cookies = require("./cookies");

  logs = require("./logs");

  Renderer = require("./renderer");

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

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

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

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

  handleEvent = function(options, event, id, type, arg) {
    var echo, send, sendErr, sendResponse, upd, win;
    sendResponse = function(data) {
      if (data == null) {
        data = {};
      }
      try {
        return event.sender.send("response", data);
      } catch (undefined) {}
    };
    sendErr = function(err) {
      return sendResponse({
        id: id,
        __error: errors.clone(err)
      });
    };
    send = function(data) {
      return sendResponse({
        id: id,
        data: data
      });
    };
    switch (type) {
      case "quit":
        logs.off();
        return options.app.exit(0);
      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 "window:open":
        return Renderer.create(arg).then(send)["catch"](sendErr);
      case "window:close":
        return Renderer.getByWebContents(event.sender).destroy();
      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:about:logo:src":
        return send(cypressIcons.getPathToIcon("icon_32x32@2x.png"));
      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":
        return project.open(arg, {
          sync: true,
          changeEvents: true
        }).call("getConfig").then(send)["catch"](sendErr);
      case "close:project":
        return project.close({
          sync: true
        }).then(send)["catch"](sendErr);
      case "on:project:settings:change":
        return project.onSettingsChanged().then(function() {
          return send(null);
        })["catch"](sendErr);
      default:
        throw new Error("No ipc event registered for: '" + type + "'");
    }
  };

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

}).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/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, errors, openProject;

  Promise = require("bluebird");

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

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

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

  openProject = null;

  module.exports = {
    open: function(path, options) {
      if (options == null) {
        options = {};
      }
      openProject = Project(path);
      return openProject.open(options);
    },
    opened: function() {
      return openProject;
    },
    onSettingsChanged: function() {
      return Promise["try"]((function(_this) {
        return function() {
          if (!openProject) {
            return errors["throw"]("NO_CURRENTLY_OPEN_PROJECT");
          } else {
            return new Promise(function(resolve, reject) {
              return openProject.on("settings:changed", function() {
                return resolve();
              });
            });
          }
        };
      })(this));
    },
    close: function(options) {
      var nullify;
      if (options == null) {
        options = {};
      }
      nullify = function() {
        openProject = null;
        return Promise.resolve(null);
      };
      if (!openProject) {
        return nullify();
      } else {
        return openProject.close(options).then(nullify);
      }
    }
  };

}).call(this);

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

  _ = require("lodash");

  path = require("path");

  uri = require("url");

  cypressGui = require("cypress-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 cypressGui.getPathToAbout();
      case "DEBUG":
        return cypressGui.getPathToDebug();
      case "UPDATES":
        return cypressGui.getPathToUpdates();
      case "INDEX":
        return cypressGui.getPathToIndex();
      default:
        throw new Error("No acceptable window type found for: '" + type + "'");
    }
  };

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

  module.exports = {
    reset: function() {
      return windows = {};
    },
    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, urlChanged, 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,
        preload: cwd("lib", "ipc", "ipc.js"),
        webPreferences: {
          nodeIntegration: 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);
        }
      };
      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) {
        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/tray.js",function (module, exports, require) {(function() {
  var Tray, _, cypressIcons, nativeImage, tray;

  _ = require("lodash");

  cypressIcons = require("cypress-icons");

  nativeImage = require("electron").nativeImage;

  Tray = require("electron").Tray;

  tray = null;

  module.exports = {
    display: function(options) {
      var black, white;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        onDrop: function() {},
        onClick: function() {},
        onRightClick: function() {},
        onDragEnter: function() {},
        onDragLeave: function() {}
      });
      black = nativeImage.createFromPath(cypressIcons.getPathToTray("mac-normal.png"));
      white = nativeImage.createFromPath(cypressIcons.getPathToTray("mac-normal-inverse.png"));
      tray = new Tray(null);
      tray.on("click", options.onClick);
      tray.on("right-click", options.onRightClick);
      tray.on("drop", options.onDrop);
      tray.on("drag-enter", options.onDragEnter);
      tray.on("drag-leave", options.onDragLeave);
      tray.on("double-click", options.onClick);
      tray.setImage(black);
      tray.setPressedImage(white);
      tray.setToolTip("Cypress");
      return tray;
    }
  };

}).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 cwd, fs, getEnv, pkg;

  require("./util/http_overrides");

  fs = require("fs-extra");

  cwd = require("./cwd");

  Error.stackTraceLimit = Infinity;

  pkg = cwd("package.json");

  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, exceptions,
    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; },
    hasProp = {}.hasOwnProperty;

  _ = require("lodash");

  chalk = require("chalk");

  ansi_up = require("ansi_up");

  Promise = require("bluebird");

  exceptions = "CI_CANNOT_COMMUNICATE".split(" ");

  API = {
    getMsgByType: function(type, arg1, arg2) {
      switch (type) {
        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":
          return "Can't start tests, the remote client never connected.";
        case "PROJECT_DOES_NOT_EXIST":
          return "You need to add a project to run tests.";
        case "NOT_CI_ENVIRONMENT":
          return "Can't run CI outside of a CI provider and environment.";
        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 "CI_CANNOT_COMMUNICATE":
          return "Can't communicate with remote Cypress servers. This is a temporary problem. Try again later.";
        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 "NO_CURRENTLY_OPEN_PROJECT":
          return "Can't find open project.";
      }
    },
    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) {
      var ref;
      return err.type && this.getMsgByType(err.type) && (ref = err.type, indexOf.call(exceptions, ref) < 0);
    },
    warning: function(type) {
      var err;
      err = this.get(type);
      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;
          }
          switch (process.env["CYPRESS_ENV"]) {
            case "production":
              break;
            default:
              return console.log(err.stack);
          }
        };
      })(this));
    },
    "throw": function(type, arg) {
      throw this.get(type, arg);
    },
    clone: function(err) {
      var obj, prop, val;
      obj = _.pick(err, "type", "name", "stack", "fileName", "lineNumber", "columnNumber");
      obj.message = ansi_up.ansi_to_html(err.message, {
        use_classes: true
      });
      for (prop in err) {
        if (!hasProp.call(err, prop)) continue;
        val = err[prop];
        obj[prop] = val;
      }
      return obj;
    }
  };

  module.exports = _.bindAll(API);

}).call(this);

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

  request = require("request-promise");

  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.session_token;
      });
    },
    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/fixture.js",function (module, exports, require) {(function() {
  var Promise, beautify, check, coffee, cwd, extensions, formatter, fs, jsonlint, lastCharacterIsNewLine, path, pretty, queue;

  Promise = require("bluebird");

  fs = require("fs-extra");

  path = require("path");

  jsonlint = require("jsonlint");

  check = require("syntax-error");

  coffee = require("coffee-script");

  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 .png .jpg .jpeg .gif .tif .tiff .zip".split(" ");

  queue = {};

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

  module.exports = {
    get: function() {
      var ext, fixture, p, tryParsingFile;
      p = path.join.apply(path, arguments);
      fixture = path.basename(p);
      if (ext = path.extname(p)) {
        return this.parseFile(p, fixture, ext);
      } 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);
            });
          };
        })(this);
        return Promise.resolve(tryParsingFile(0));
      }
    },
    fileExists: function(p) {
      return fs.statAsync(p).bind(this);
    },
    parseFile: function(p, fixture, ext) {
      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);
        }).then(function(ret) {
          cleanup();
          return ret;
        })["catch"](function(err) {
          cleanup();
          throw err;
        });
      }
    },
    parseFileByExtension: function(p, fixture, ext) {
      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 ".txt":
          return this.parseText(p, fixture);
        case ".png":
        case ".jpg":
        case ".jpeg":
        case ".gif":
        case ".tif":
        case ".tiff":
        case ".zip":
          return this.parseBase64(p, fixture);
        default:
          throw new Error("Invalid fixture extension: '" + ext + "'. Acceptable file extensions are: " + (extensions.join(", ")));
      }
    },
    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, error, 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);
      });
    },
    parseText: function(p, fixture) {
      return fs.readFileAsync(p, "utf8").bind(this);
    },
    parseBase64: function(p, fixture) {
      return fs.readFileAsync(p, "base64").bind(this);
    },
    copyExample: function(fixturesDir) {
      var dest, src;
      src = cwd("lib", "scaffold", "example.json");
      dest = path.join(fixturesDir, "example.json");
      return fs.copyAsync(src, dest);
    },
    scaffold: function() {
      var p;
      p = path.join.apply(path, arguments);
      return fs.statAsync(p).bind(this)["catch"](function() {
        return this.copyExample(p);
      });
    }
  };

}).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/logger.js",function (module, exports, require) {(function() {
  var Promise, _, config, createFile, 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");

  config = require("./config");

  fs.ensureDirSync(config.app.log_path);

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

  getPathToLog = function(name) {
    return path.join(config.app.log_path, getName(name));
  };

  createFile = function(name, level, opts) {
    var obj;
    if (opts == null) {
      opts = {};
    }
    obj = {
      name: name,
      filename: getPathToLog(name),
      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.error(err);
        console.error(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, errors, git, headless, os;

  os = require("os");

  git = require("gift");

  Promise = require("bluebird");

  headless = require("./headless");

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

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

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

  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 "";
      });
    },
    getAuthor: function(repo) {
      return repo.current_commitAsync().get("author").get("name")["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);
    },
    ensureCi: function() {
      return Promise["try"]((function(_this) {
        return function() {
          if (os.platform() === "linux") {
            return;
          }
          return errors["throw"]("NOT_CI_ENVIRONMENT");
        };
      })(this));
    },
    ensureProjectAPIToken: function(projectId, projectPath, key) {
      var repo;
      if (!key) {
        return errors["throw"]("CI_KEY_MISSING");
      }
      repo = Promise.promisifyAll(git(projectPath));
      return Promise.props({
        branch: this.getBranch(repo),
        author: this.getAuthor(repo),
        message: this.getMessage(repo)
      }).then(function(git) {
        return api.createCi({
          key: key,
          projectId: projectId,
          branch: git.branch,
          author: git.author,
          message: git.message
        })["catch"](function(err) {
          switch (err.statusCode) {
            case 401:
              key = key.slice(0, 5) + "..." + key.slice(-5);
              return errors["throw"]("CI_KEY_NOT_VALID", key);
            case 404:
              return errors["throw"]("CI_PROJECT_NOT_FOUND");
            default:
              return errors["throw"]("CI_CANNOT_COMMUNICATE");
          }
        });
      });
    },
    reportStats: function(projectId, ciId, key, stats) {
      return api.updateCi({
        key: key,
        ciId: ciId,
        stats: stats,
        projectId: projectId
      })["catch"](function(err) {});
    },
    run: function(options) {
      var projectPath;
      projectPath = options.projectPath;
      return this.ensureCi().then(function() {
        return Project.add(projectPath);
      }).then((function(_this) {
        return function() {
          return Project.id(projectPath);
        };
      })(this)).then((function(_this) {
        return function(id) {
          return _this.ensureProjectAPIToken(id, projectPath, options.key).then(function(ciId) {
            options.ensureSession = false;
            return headless.run(options).then(function(stats) {
              if (stats == null) {
                stats = {};
              }
              return _this.reportStats(id, ciId, options.key, stats)["return"](stats.failures);
            });
          });
        };
      })(this));
    }
  };

}).call(this);

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

  _ = require("lodash");

  os = require("os");

  app = require("electron").app;

  image = require("electron").nativeImage;

  cyIcons = require("cypress-icons");

  Position = require("electron-positioner");

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

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

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

  Tray = require("../electron/handlers/tray");

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

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

  module.exports = {
    onDrop: function() {},
    onClick: function(bounds, win) {
      var coords, positioner;
      positioner = new Position(win);
      coords = positioner.calculate("trayCenter", bounds);
      Updater.setCoords(coords);
      win.setPosition(coords.x, coords.y);
      if (win.isVisible()) {
        return win.hide();
      } else {
        return win.show();
      }
    },
    onRightClick: function() {},
    onWindowAllClosed: function(app) {
      Events.stop();
      return app.exit(0);
    },
    getRendererArgs: function(coords) {
      var common;
      common = {
        width: 300,
        height: 400,
        resizable: false,
        type: "INDEX",
        onBlur: function() {
          if (this.webContents.isDevToolsOpened()) {
            return;
          }
          return Renderer.hideAllUnlessAnotherWindowIsFocused();
        },
        onFocus: function() {
          return Renderer.showAll();
        }
      };
      _.extend(common, this.platformArgs());
      if (coords) {
        _.extend(common, coords, {
          show: true
        });
      }
      return common;
    },
    platformArgs: function() {
      return {
        darwin: {
          show: false,
          frame: false,
          transparent: true
        },
        linux: {
          show: true,
          frame: true,
          transparent: false,
          icon: image.createFromPath(cyIcons.getPathToIcon("icon_128x128.png"))
        }
      }[os.platform()];
    },
    ready: function(options) {
      if (options == null) {
        options = {};
      }
      options.app = app;
      return Renderer.create(this.getRendererArgs(options.coords)).then((function(_this) {
        return function(win) {
          Events.start(options);
          if (options.updating) {
            Updater.install(options);
          }
          return Tray.display({
            onDrop: function() {},
            onClick: function(e, bounds) {
              return _this.onClick(bounds, win);
            },
            onRightClick: function() {}
          });
        };
      })(this));
    },
    run: function(options) {
      return new Promise((function(_this) {
        return function(resolve, reject) {
          app.commandLine.appendSwitch("disable-renderer-backgrounding");
          app.on("window-all-closed", function() {
            return _this.onWindowAllClosed(app);
          });
          return app.on("ready", function() {
            return resolve(_this.ready(options));
          });
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/modes/headless.js",function (module, exports, require) {(function() {
  var Project, Promise, Renderer, chalk, errors, inquirer, project, user;

  chalk = require("chalk");

  Promise = require("bluebird");

  inquirer = require("inquirer");

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

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

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

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

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

  module.exports = {
    getId: function() {
      return Math.random();
    },
    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();
          }
          return _this.promptAddProject(projectPath).then(open);
        };
      })(this));
    },
    promptAddProject: function(projectPath) {
      var questions;
      console.log(chalk.yellow("We couldn't find a Cypress project at this path:"), chalk.blue(projectPath), "\n");
      questions = [
        {
          name: "add",
          type: "list",
          message: "Would you like to add this project to Cypress?",
          choices: [
            {
              name: "Yes: add this project and run the tests.",
              value: true
            }, {
              name: "No:  don't add this project.",
              value: false
            }
          ]
        }
      ];
      return new Promise((function(_this) {
        return function(resolve, reject) {
          return inquirer.prompt(questions, function(answers) {
            if (answers.add) {
              return Project.add(projectPath).then(function() {
                console.log(chalk.green("\nOk great, added the project.\n"));
                return resolve();
              })["catch"](reject);
            } else {
              return reject(errors.get("PROJECT_DOES_NOT_EXIST"));
            }
          });
        };
      })(this));
    },
    openProject: function(id, options) {
      return project.open(options.projectPath, {
        morgan: false,
        socketId: id,
        reporter: true,
        isHeadless: true,
        port: options.port,
        environmentVariables: options.environmentVariables
      })["catch"]({
        portInUse: true
      }, function(err) {
        return errors["throw"]("PORT_IN_USE_LONG", err.port);
      });
    },
    createRenderer: function(url) {
      return Renderer.create({
        url: url,
        width: 0,
        height: 0,
        show: false,
        frame: false,
        type: "PROJECT"
      }).then(function(win) {
        win.hide();
        return win.setSize(1280, 720);
      });
    },
    waitForRendererToConnect: function(project, id) {
      return this.waitForSocketConnection(project, id).timeout(10000)["catch"](Promise.TimeoutError, function(err) {
        return errors["throw"]("TESTS_DID_NOT_START");
      });
    },
    waitForSocketConnection: function(project, id) {
      return new Promise(function(resolve, reject) {
        var fn;
        fn = function(socketId) {
          if (socketId === id) {
            project.removeListener("socket:connected", fn);
            return resolve();
          }
        };
        return project.on("socket:connected", fn);
      });
    },
    waitForTestsToFinishRunning: function(project) {
      return new Promise(function(resolve, reject) {
        return project.once("end", resolve);
      });
    },
    runTests: function(project, id, url) {
      return Promise.props({
        connection: this.waitForRendererToConnect(project, id),
        stats: this.waitForTestsToFinishRunning(project),
        renderer: this.createRenderer(url)
      });
    },
    ready: function(options) {
      var ready;
      if (options == null) {
        options = {};
      }
      ready = (function(_this) {
        return function() {
          var id;
          id = _this.getId();
          return _this.ensureAndOpenProjectByPath(id, options).then(function(project) {
            return project.ensureSpecUrl(options.spec).then(function(url) {
              console.log("\nTests should begin momentarily...\n");
              return _this.runTests(project, id, url).get("stats");
            });
          });
        };
      })(this);
      if (options.ensureSession !== false) {
        return user.ensureSession().then(ready);
      } else {
        return ready();
      }
    },
    run: function(options) {
      var app, waitForReady;
      app = require("electron").app;
      app.commandLine.appendSwitch("disable-renderer-backgrounding");
      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, Settings, Support, Watchers, _, api, cache, errors, fixture, fs, ids, logger, path, 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,
    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; };

  path = require("path");

  EE = require("events");

  _ = require("lodash");

  fs = require("fs-extra");

  Promise = require("bluebird");

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

  ids = require("./ids");

  api = require("./api");

  user = require("./user");

  cache = require("./cache");

  logger = require("./logger");

  errors = require("./errors");

  Server = require("./server");

  Support = require("./support");

  fixture = require("./fixture");

  Watchers = require("./watchers");

  Reporter = require("./reporter");

  fs = Promise.promisifyAll(fs);

  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 = projectRoot;
      this.server = Server(projectRoot);
      this.watchers = Watchers();
    }

    Project.prototype.open = function(options) {
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        type: "opened",
        sync: false,
        reporter: false,
        changeEvents: false
      });
      return this.server.open(options).bind(this).then(function(config) {
        this.sync(options);
        this.config = config;
        return this.watchSettingsAndStartWebsockets(options).then((function(_this) {
          return function() {
            return _this.scaffold(config);
          };
        })(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"
      });
      this.sync(options);
      this.removeAllListeners();
      return Promise.join((ref = this.server) != null ? ref.close() : void 0, (ref1 = this.watchers) != null ? ref1.close() : void 0);
    };

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

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

    Project.prototype.watchSettingsAndStartWebsockets = function(options) {
      var reporter;
      this.watchSettings(options);
      if (options.reporter) {
        reporter = Reporter();
      }
      return this.server.startWebsockets(this.watchers, {
        onConnect: (function(_this) {
          return function(id) {
            return _this.emit("socket:connected", id);
          };
        })(this),
        onMocha: (function(_this) {
          return function() {
            var args, event, stats;
            event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
            if (!reporter) {
              return;
            }
            args = [event].concat(args);
            reporter.emit.apply(reporter, args);
            if (event === "end") {
              stats = reporter.stats();
              _this.server.end();
              return Promise.delay(1000).then(function() {
                return _this.emit("end", stats);
              });
            }
          };
        })(this)
      });
    };

    Project.prototype.getConfig = function() {
      var ref;
      return (ref = this.config) != null ? ref : {};
    };

    Project.prototype.ensureSpecUrl = function(spec) {
      return Promise["try"]((function(_this) {
        return function() {
          if (spec) {
            return _this.ensureSpecExists(spec).then(function(str) {
              return _this.getUrlBySpec(str);
            });
          } else {
            return _this.getUrlBySpec("/__all");
          }
        };
      })(this));
    };

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

    Project.prototype.getUrlBySpec = function(spec) {
      return [this.getConfig().clientUrl, "#/tests", spec, "?__ui=satellite"].join("");
    };

    Project.prototype.scaffold = function(config) {
      return Promise.join(fixture.scaffold(config.projectRoot, config.fixturesFolder), Support(config).scaffold());
    };

    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 user.ensureSession().bind(this).then(function(session) {
        return api.createProject(session);
      }).then(this.writeProjectId);
    };

    Project.prototype.getProjectId = function() {
      return this.verifyExistance().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.verifyExistance = 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).verifyExistance().then(function(project) {
        var config;
        config = project.server.config;
        return ids.remove(path.join(config.projectRoot, config.testFolder));
      });
    };

    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.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, createErr, createRunnable, createSuite, events,
    slice = [].slice;

  _ = require("lodash");

  Mocha = require("mocha");

  chalk = require("chalk");

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

  createSuite = function(obj) {
    var p, suite;
    suite = new Mocha.Suite(obj.title, {});
    if (p = obj.parent) {
      suite.parent = createSuite(p);
    }
    return suite;
  };

  createRunnable = function(obj) {
    var p, runnable;
    runnable = new Mocha.Runnable(obj.title, function() {});
    runnable.timedOut = obj.timedOut;
    runnable.async = obj.async;
    runnable.sync = obj.sync;
    runnable.duration = obj.duration;
    runnable.state = obj.state;
    if (p = obj.parent) {
      runnable.parent = createSuite(p);
    }
    return runnable;
  };

  createErr = function(test, err) {
    return [createRunnable(test), err];
  };

  events = {
    "start": true,
    "end": true,
    "suite": createSuite,
    "suite end": createSuite,
    "test": createRunnable,
    "test end": createRunnable,
    "hook": createRunnable,
    "hook end": createRunnable,
    "pass": createRunnable,
    "pending": createRunnable,
    "fail": createErr
  };

  Reporter = (function() {
    function Reporter(options) {
      if (options == null) {
        options = {};
      }
      if (!(this instanceof Reporter)) {
        return new Reporter(options);
      }
      this.reporterName = "spec";
      this.mocha = new Mocha({
        reporter: this.reporterName
      });
      this.runner = new Mocha.Runner(this.mocha.suite);
      this.reporter = new this.mocha._reporter(this.runner, {});
      this.runner.ignoreLeaks = true;
    }

    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);
        }
        return [event].concat(args);
      }
    };

    Reporter.prototype.stats = function() {
      return _.extend({
        reporter: this.reporterName
      }, _.pick(this.reporter.stats, STATS));
    };

    return Reporter;

  })();

  module.exports = Reporter;

}).call(this);

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

  _ = require("lodash");

  request = require("request-promise");

  module.exports = {
    contentTypeIsJson: function(response) {
      var ref, ref1;
      return response != null ? (ref = response.headers) != null ? (ref1 = ref["content-type"]) != null ? ref1.includes("application/json") : void 0 : void 0 : void 0;
    },
    parseJsonBody: function(body) {
      var e, error;
      try {
        return JSON.parse(body);
      } catch (error) {
        e = error;
        return body;
      }
    },
    normalizeResponse: function(response) {
      response = _.pick(response, "statusCode", "body", "headers");
      response.status = response.statusCode;
      delete response.statusCode;
      if (_.isString(response.body) && this.contentTypeIsJson(response)) {
        response.body = this.parseJsonBody(response.body);
      }
      return response;
    },
    reduceCookieToArray: function(c) {
      return _.reduce(c, function(memo, val, key) {
        memo.push([key.trim(), val.trim()].join("="));
        return memo;
      }, []);
    },
    createCookieString: function(c) {
      return this.reduceCookieToArray(c).join("; ");
    },
    send: function(options) {
      var c, ms;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        headers: {},
        gzip: true
      });
      _.extend(options, {
        strictSSL: false,
        simple: false,
        resolveWithFullResponse: true
      });
      if (c = options.cookies) {
        options.headers["Cookie"] = this.createCookieString(c);
      }
      ms = Date.now();
      return request(options).then(this.normalizeResponse.bind(this)).then(function(resp) {
        resp.duration = Date.now() - ms;
        return resp;
      });
    }
  };

}).call(this);

});
require.register("./lib/routes.js",function (module, exports, require) {(function() {
  var CacheBuster, cwd, path;

  path = require("path");

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

  cwd = require("./cwd");

  module.exports = function(app) {
    var controllers;
    controllers = require('./controllers')(app);
    app.get("/__cypress/tests", function(req, res, next) {
      var test;
      test = CacheBuster.strip(req.query.p);
      return controllers.specProcessor.handle(test, req, res, next);
    });
    app.get("/__cypress/files", function(req, res) {
      return controllers.files.handleFiles(req, res);
    });
    app.get("/__cypress/builds", function(req, res, next) {
      return controllers.builds.handleBuilds(req, res, next);
    });
    app.get("/__cypress/iframes/*", function(req, res) {
      return controllers.files.handleIframe(req, res);
    });
    app.all("/__cypress/xhrs/*", function(req, res, next) {
      return controllers.xhrs.handleXhr(req, res, next);
    });
    app.get("/__root/*", function(req, res, next) {
      var file;
      file = path.join(app.get("cypress").projectRoot, req.params[0]);
      return res.sendFile(file, {
        etag: false
      });
    });
    app.get(app.get("cypress").clientRoute, function(req, res) {
      return res.render(cwd("lib", "public", "index.html"), {
        config: JSON.stringify(app.get("cypress"))
      });
    });
    return app.all("*", function(req, res, next) {
      return controllers.proxy.handle(req, res, next);
    });
  };

}).call(this);

});
require.register("./lib/server.js",function (module, exports, require) {(function() {
  var Promise, Server, Settings, Socket, _, allowDestroy, cwd, cypressEnvRe, errors, express, fs, hbs, http, isCypressEnvLike, logger, path, str;

  express = require("express");

  http = require("http");

  fs = require("fs-extra");

  hbs = require("hbs");

  path = require("path");

  _ = require("underscore");

  str = require("underscore.string");

  allowDestroy = require("server-destroy");

  Promise = require("bluebird");

  cwd = require("./cwd");

  errors = require("./errors");

  logger = require("./logger");

  Socket = require("./socket");

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

  cypressEnvRe = /^(cypress_)/i;

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

  Server = (function() {
    function Server(projectRoot) {
      if (!(this instanceof Server)) {
        return new Server(projectRoot);
      }
      if (!projectRoot) {
        throw new Error("Instantiating lib/server requires a projectRoot!");
      }
      this.app = express();
      this.server = null;
      this.io = null;
      this.initialize(projectRoot);
    }

    Server.prototype.initialize = function(projectRoot) {
      var err, error;
      try {
        this.config = this.getCypressJson(projectRoot);
        this.setCypressJson(this.config);
        return logger.setSettings(this.config);
      } catch (error) {
        err = error;
        err.jsonError = true;
        return this.config = err;
      }
    };

    Server.prototype.getCypressJson = function(projectRoot) {
      var obj;
      obj = Settings.readSync(projectRoot);
      obj.projectRoot = projectRoot;
      obj.envFile = Settings.readEnvSync(projectRoot);
      return obj;
    };

    Server.prototype.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)] = value;
        }
        return memo;
      }, {});
    };

    Server.prototype.parseEnv = function(env, envFile) {
      if (env == null) {
        env = {};
      }
      if (envFile == null) {
        envFile = {};
      }
      return _.extend(env, envFile, this.getProcessEnvVars(process.env));
    };

    Server.prototype.setCypressDefaults = function(obj) {
      var url;
      if (obj == null) {
        obj = {};
      }
      if (url = obj.baseUrl) {
        obj.baseUrl = str.rtrim(url, "/");
      }
      _.defaults(obj, {
        baseUrl: null,
        clientRoute: "/__/",
        xhrRoute: "/xhrs/",
        socketIoRoute: "/__socket.io",
        commandTimeout: 4000,
        visitTimeout: 30000,
        requestTimeout: 5000,
        responseTimeout: 20000,
        port: 2020,
        waitForAnimations: true,
        animationDistanceThreshold: 5,
        autoOpen: false,
        viewportWidth: 1000,
        viewportHeight: 660,
        testFolder: "tests",
        fixturesFolder: "tests/_fixtures",
        supportFolder: "tests/_support",
        javascripts: [],
        namespace: "__cypress"
      });
      obj.environmentVariables = this.parseEnv(obj.env, obj.envFile);
      obj.env = process.env["CYPRESS_ENV"];
      delete obj.envFile;
      this.setUrls(obj);
      return obj;
    };

    Server.prototype.setCypressJson = function(obj) {
      this.setCypressDefaults(obj);
      return this.app.set("cypress", obj);
    };

    Server.prototype.setUrls = function(obj) {
      var rootUrl;
      rootUrl = "http://localhost:" + obj.port;
      return _.extend(obj, {
        clientUrlDisplay: rootUrl,
        clientUrl: rootUrl + obj.clientRoute,
        xhrUrl: obj.namespace + obj.xhrRoute
      });
    };

    Server.prototype.configureApplication = function(options) {
      var base, envs, p, sid;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        morgan: true,
        isHeadless: false,
        port: null,
        socketId: null,
        environmentVariables: null
      });
      _.extend(this.config, _.pick(options, "isHeadless"));
      if (envs = options.environmentVariables) {
        if ((base = this.config).environmentVariables == null) {
          base.environmentVariables = {};
        }
        _.extend(this.config.environmentVariables, envs);
      }
      if (p = options.port) {
        this.config.port = p;
        this.setUrls(this.config);
      }
      if (sid = options.socketId) {
        this.config.socketId = sid;
      }
      this.app.set("port", this.config.port);
      this.app.set("view engine", "html");
      this.app.engine("html", hbs.__express);
      this.app.use(require("cookie-parser")());
      this.app.use(require("compression")());
      if (options.morgan) {
        this.app.use(require("morgan")("dev"));
      }
      this.app.use("/__cypress/static", express["static"](cwd("lib", "public")));
      this.app.use(require("errorhandler")());
      this.app.disable("x-powered-by");
      return this.createRoutes();
    };

    Server.prototype.createRoutes = function() {
      return require("./routes")(this.app);
    };

    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.open = function(options) {
      if (options == null) {
        options = {};
      }
      if (this.config.jsonError) {
        return Promise.reject(this.config);
      }
      return Promise["try"]((function(_this) {
        return function() {
          _this.configureApplication(options);
          return _this._open(options);
        };
      })(this));
    };

    Server.prototype._open = function(options) {
      return new Promise((function(_this) {
        return function(resolve, reject) {
          var onError;
          _this.server = http.createServer(_this.app);
          allowDestroy(_this.server);
          onError = function(err) {
            if (err.code === "EADDRINUSE") {
              return reject(_this.portInUseErr(_this.config.port));
            }
          };
          _this.server.once("error", onError);
          return _this.server.listen(_this.config.port, function() {
            _this.isListening = true;
            logger.info("Server listening", {
              port: _this.config.port
            });
            _this.server.removeListener("error", onError);
            return resolve(_this.config);
          });
        };
      })(this));
    };

    Server.prototype._close = function() {
      return new Promise((function(_this) {
        return function(resolve) {
          logger.unsetSettings();
          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;
      return Promise.join(this._close(), (ref = this.socket) != null ? ref.close() : void 0);
    };

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

    Server.prototype.startWebsockets = function(watchers, options) {
      this.socket = Socket(this.app);
      return this.socket.startListening(this.server, watchers, options);
    };

    return Server;

  })();

  module.exports = Server;

}).call(this);

});
require.register("./lib/socket.js",function (module, exports, require) {(function() {
  var Reporter, Request, Socket, _, cwd, fixture, fs, leadingSlashesRe, logger, path, socketIo, uuid,
    slice = [].slice;

  _ = require("lodash");

  fs = require("fs-extra");

  path = require("path");

  uuid = require("node-uuid");

  socketIo = require("socket.io");

  cwd = require("./cwd");

  fixture = require("./fixture");

  Request = require("./request");

  logger = require("./logger");

  Reporter = require("./reporter");

  leadingSlashesRe = /^\/+/;

  Socket = (function() {
    function Socket(app) {
      if (!(this instanceof Socket)) {
        return new Socket(app);
      }
      if (!app) {
        throw new Error("Instantiating lib/socket requires an app instance!");
      }
      this.app = app;
    }

    Socket.prototype.onTestFileChange = function(filePath, stats) {
      logger.info("onTestFileChange", {
        filePath: filePath
      });
      if (this.app.enabled("editFileMode")) {
        return;
      }
      if (!/\.(js|coffee)$/.test(filePath)) {
        return;
      }
      return fs.statAsync(filePath).bind(this).then(function() {
        var strippedPath;
        filePath = filePath.split(this.app.get("cypress").projectRoot).join("").replace(leadingSlashesRe, "");
        strippedPath = filePath.replace(this.app.get("cypress").testFolder, "").replace(leadingSlashesRe, "");
        return this.io.emit("test:changed", {
          file: strippedPath
        });
      })["catch"](function() {});
    };

    Socket.prototype.watchTestFileByPath = function(testFilePath, watchers) {
      testFilePath = path.join(this.testsDir, testFilePath);
      if (testFilePath === this.testFilePath) {
        return;
      }
      logger.info("watching test file", {
        path: testFilePath
      });
      watchers.remove(testFilePath);
      this.testFilePath = testFilePath;
      return watchers.watchAsync(testFilePath, {
        onChange: this.onTestFileChange.bind(this)
      });
    };

    Socket.prototype.onRequest = function(options, cb) {
      return Request.send(options).then(cb)["catch"](function(err) {
        return cb({
          __error: err.message
        });
      });
    };

    Socket.prototype.onFixture = function(file, cb) {
      var fixturesFolder, projectRoot, ref;
      ref = this.app.get("cypress"), projectRoot = ref.projectRoot, fixturesFolder = ref.fixturesFolder;
      return fixture.get(projectRoot, fixturesFolder, file).then(cb)["catch"](function(err) {
        return cb({
          __error: err.message
        });
      });
    };

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

    Socket.prototype._startListening = function(server, watchers, options) {
      var chromiums, messages, projectRoot, ref, socketIoRoute, testFolder;
      _.defaults(options, {
        socketId: null,
        onMocha: function() {},
        onConnect: function() {},
        onChromiumRun: function() {},
        checkForAppErrors: function() {}
      });
      messages = {};
      chromiums = {};
      ref = this.app.get("cypress"), projectRoot = ref.projectRoot, testFolder = ref.testFolder, socketIoRoute = ref.socketIoRoute;
      this.io = this.createIo(server, socketIoRoute);
      this.io.on("connection", (function(_this) {
        return function(socket) {
          logger.info("socket connected");
          socket.on("chromium:connected", function() {
            if (socket.inChromiumRoom) {
              return;
            }
            socket.inChromiumRoom = true;
            socket.join("chromium");
            return socket.on("chromium:history:response", function(id, response) {
              var message;
              if (message = chromiums[id]) {
                delete chromiums[id];
                return message(response);
              }
            });
          });
          socket.on("history:entries", function(cb) {
            var id;
            id = uuid.v4();
            chromiums[id] = cb;
            if (_.keys(_this.io.sockets.adapter.rooms.chromium).length > 0) {
              messages[id] = cb;
              return _this.io.to("chromium").emit("chromium:history:request", id);
            } else {
              return cb({
                __error: "Could not process 'history:entries'. No chromium servers connected."
              });
            }
          });
          socket.on("remote:connected", function() {
            logger.info("remote:connected");
            if (socket.inRemoteRoom) {
              return;
            }
            socket.inRemoteRoom = true;
            socket.join("remote");
            return socket.on("remote:response", function(id, response) {
              var message;
              if (message = messages[id]) {
                delete messages[id];
                logger.info("remote:response", {
                  id: id,
                  response: response
                });
                return message(response);
              }
            });
          });
          socket.on("client:request", function(message, data, cb) {
            var id;
            if (!_.isFunction(cb)) {
              cb = data;
              data = null;
            }
            id = uuid.v4();
            logger.info("client:request", {
              id: id,
              msg: message,
              data: data
            });
            if (_.keys(_this.io.sockets.adapter.rooms.remote).length > 0) {
              messages[id] = cb;
              return _this.io.to("remote").emit("remote:request", id, message, data);
            } else {
              return cb({
                __error: "Could not process '" + message + "'. No remote servers connected."
              });
            }
          });
          socket.on("run:tests:in:chromium", function(src) {
            return options.onChromiumRun(src);
          });
          socket.on("watch:test:file", function(filePath) {
            return _this.watchTestFileByPath(filePath, watchers);
          });
          socket.on("request", function() {
            return _this.onRequest.apply(_this, arguments);
          });
          socket.on("fixture", function() {
            return _this.onFixture.apply(_this, arguments);
          });
          _.each("load:spec:iframe url:changed page:loading command:add command:attrs:changed runner:start runner:end before:run before:add after:add suite:add suite:start suite:stop test test:add test:start test:end after:run test:results:ready exclusive:test".split(" "), function(event) {
            return socket.on(event, function() {
              var args, ref1;
              args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
              args = _.chain(args).reject(_.isUndefined).reject(_.isFunction).value();
              return (ref1 = _this.io).emit.apply(ref1, [event].concat(slice.call(args)));
            });
          });
          socket.on("app:connect", function(socketId) {
            return options.onConnect(socketId, socket);
          });
          return socket.on("mocha", function() {
            return options.onMocha.apply(options, arguments);
          });
        };
      })(this));
      this.testsDir = path.join(projectRoot, testFolder);
      return fs.ensureDirAsync(this.testsDir).bind(this);
    };

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

    Socket.prototype.startListening = function(server, watchers, options) {
      if (process.env["CYPRESS_ENV"] === "development") {
        this.listenToCssChanges(watchers);
      }
      return this._startListening(server, watchers, 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/support.js",function (module, exports, require) {(function() {
  var Promise, Support, cwd, fs, path;

  Promise = require("bluebird");

  fs = require("fs-extra");

  path = require("path");

  cwd = require("./cwd");

  fs = Promise.promisifyAll(fs);

  Support = (function() {
    function Support(config) {
      var pr, sf;
      if (config == null) {
        config = {};
      }
      if (!(this instanceof Support)) {
        return new Support(config);
      }
      if (!(pr = config.projectRoot)) {
        throw new Error("Instantiating lib/support requires a projectRoot!");
      }
      if (!(sf = config.supportFolder)) {
        throw new Error("Instantiating lib/support requires a supportFolder!");
      }
      this.folder = path.join(pr, sf);
    }

    Support.prototype.copyExample = function(folder) {
      var dest, src;
      src = cwd("lib", "scaffold", "spec_helper.js");
      dest = path.join(folder, "spec_helper.js");
      return fs.copyAsync(src, dest);
    };

    Support.prototype.scaffold = function() {
      return fs.statAsync(this.folder).bind(this)["catch"](function() {
        return this.copyExample(this.folder);
      });
    };

    return Support;

  })();

  module.exports = Support;

}).call(this);

});
require.register("./lib/updater.js",function (module, exports, require) {(function() {
  var NwUpdater, Promise, Updater, _, argsUtil, chmodr, config, coords, cwd, fs, glob, logger, path, tar, trash,
    slice = [].slice;

  fs = require("fs-extra");

  tar = require("tar-fs");

  path = require("path");

  Promise = require("bluebird");

  _ = require("lodash");

  glob = require("glob");

  chmodr = require("chmodr");

  trash = require("trash");

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

  cwd = require("./cwd");

  config = require("./config");

  logger = require("./logger");

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

  trash = Promise.promisify(trash);

  chmodr = Promise.promisify(chmodr);

  coords = null;

  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.getCoords = function() {
      var c;
      if (!(c = coords)) {
        return;
      }
      return "--coords=" + c.x + "x" + c.y;
    };

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

    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 = config.app.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 trash([appPath]);
    };

    Updater.prototype.install = function(argsObj) {
      var appPath, args, c, execPath;
      if (argsObj == null) {
        argsObj = {};
      }
      c = this.getClient();
      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.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.copyCyDataTo = function(newAppPath) {
      var p;
      p = new Promise(function(resolve, reject) {
        return glob("**/app/package.json", {
          cwd: newAppPath,
          ignore: "**/node_modules/**"
        }, function(err, files) {
          var newAppConfigPath;
          if (err) {
            return reject(err);
          }
          newAppConfigPath = path.join(newAppPath, path.dirname(files[0]), config.app.cy_path);
          return resolve(newAppConfigPath);
        });
      });
      return p.then(function(newAppConfigPath) {
        var cyConfigPath;
        cyConfigPath = cwd(config.app.cy_path);
        logger.info("copying .cy to tmp destination", {
          src: cyConfigPath,
          destination: newAppConfigPath
        });
        return fs.copyAsync(cyConfigPath, newAppConfigPath).then(function() {
          return chmodr(newAppConfigPath, 0x1ed);
        });
      });
    };

    Updater.prototype.runInstaller = function(newAppPath) {
      return this.copyCyDataTo(newAppPath).bind(this).then(function() {
        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 (undefined) {}
    };

    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.setCoords = function(c) {
      return coords = c;
    };

    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/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.session_token;
        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.session_token)) {
          return st;
        } else {
          return errors["throw"]("NOT_LOGGED_IN");
        }
      });
    }
  };

}).call(this);

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

  _ = require("lodash");

  path = require("path");

  minimist = require("minimist");

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

  whitelist = "appPath execPath apiKey smokeTest getKey generateKey runProject project spec reporter ci updating ping coords key logs clearLogs port returnPkg environmentVariables getChromiumVersion mode autoOpen removeIds".split(" ");

  parseCoords = function(coords) {
    var ref, x, y;
    ref = _.map(coords.split("x"), parseFloat), x = ref[0], y = ref[1];
    return {
      x: x,
      y: y
    };
  };

  parseEnv = function(envs) {
    return _(envs.split(",")).map(function(pair) {
      return pair.split("=");
    }).object().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 envs, options, p, ref, 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",
          "get-chromium-version": "getChromiumVersion"
        }
      });
      _.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 (options.coords) {
        backup("coords", options);
        options.coords = parseCoords(options.coords);
      }
      if (envs = options.environmentVariables) {
        backup("environmentVariables", options);
        options.environmentVariables = parseEnv(envs);
      }
      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/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/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/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/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, Uri, _, addQueryParams, api_url, config, parseArgs, routes,
    slice = [].slice;

  _ = require("lodash");

  Uri = require("jsuri");

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

  api_url = config.app.api_url;

  routes = {
    api: "",
    auth: "v1/auth",
    ping: "ping",
    token: "token",
    signin: "signin",
    signout: "signout",
    ci: "ci/:id",
    tests: "tests/:id",
    projects: "projects",
    project: "projects/:id",
    projectCi: "projects/:id/ci",
    projectKeys: "projects/:id/keys",
    projectToken: "projects/:id/token",
    exceptions: "exceptions"
  };

  addQueryParams = function(url, params) {
    return _.reduce(params, function(memo, value, key) {
      memo.addQueryParam(key, value);
      return memo;
    }, url);
  };

  parseArgs = function(url, args) {
    if (args == null) {
      args = [];
    }
    _.each(args, function(value) {
      switch (false) {
        case !_.isObject(value):
          return addQueryParams(url, value);
        case !_.isString(value):
          return url.setPath(url.path().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 Uri(api_url).setPath(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, fs, path;

  _ = require("lodash");

  Promise = require("bluebird");

  path = require("path");

  fs = require("fs-extra");

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

  fs = Promise.promisifyAll(fs);

  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);
    },
    _stringify: function(obj) {
      return JSON.stringify(obj, null, 2);
    },
    _get: function(method, projectRoot, options) {
      var file;
      if (options == null) {
        options = {};
      }
      if (!projectRoot) {
        throw new Error("Settings requires projectRoot to be defined!");
      }
      _.defaults(options, {
        writeInitial: true
      });
      file = this._pathToFile(projectRoot, options.file);
      if (!fs.existsSync(file) && options.writeInitial) {
        this._writeSync(file, {});
      }
      return fs[method](file);
    },
    _write: function(file, obj) {
      if (obj == null) {
        obj = {};
      }
      return fs.writeFileAsync(file, this._stringify(obj))["return"](obj)["catch"]((function(_this) {
        return function(err) {
          return _this._logWriteErr(file, err);
        };
      })(this));
    },
    _writeSync: function(file, obj) {
      var err, error;
      if (obj == null) {
        obj = {};
      }
      try {
        fs.writeFileSync(file, this._stringify(obj));
        return obj;
      } catch (error) {
        err = error;
        return this._logWriteErr(file, err);
      }
    },
    read: function(projectRoot) {
      var file;
      file = this._pathToFile(projectRoot, "cypress.json");
      return Promise["try"]((function(_this) {
        return function() {
          return _this._get("readJsonAsync", projectRoot, {
            file: "cypress.json"
          }).then(function(obj) {
            var settings;
            if (settings = obj.cypress) {
              return _this._write(file, settings);
            } else {
              return obj;
            }
          })["catch"](function(err) {
            if (errors.isCypressErr(err)) {
              throw err;
            }
            return _this._logReadErr(file, err);
          });
        };
      })(this));
    },
    readEnvSync: function(projectRoot) {
      var err, error, options;
      options = {
        file: "cypress.env.json",
        writeInitial: false
      };
      try {
        return this._get("readJsonSync", projectRoot, options);
      } catch (error) {
        err = error;
        if (err.code === "ENOENT") {
          return {};
        }
        if (errors.isCypressErr(err)) {
          throw err;
        }
        return this._logReadErr(projectRoot, err, options.file);
      }
    },
    readSync: function(projectRoot) {
      var err, error, file, obj, options, settings;
      options = {
        file: "cypress.json"
      };
      file = this._pathToFile(projectRoot, "cypress.json");
      try {
        obj = this._get("readJsonSync", projectRoot, options);
        if (settings = obj.cypress) {
          return this._writeSync(file, settings);
        } else {
          return obj;
        }
      } catch (error) {
        err = error;
        if (errors.isCypressErr(err)) {
          throw err;
        }
        return this._logReadErr(file, err);
      }
    },
    write: function(projectRoot, obj) {
      if (obj == null) {
        obj = {};
      }
      return this.read(projectRoot).bind(this).then(function(settings) {
        var file;
        _.extend(settings, obj);
        file = this._pathToFile(projectRoot, "cypress.json");
        return this._write(file, settings);
      });
    },
    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/url_helpers.js",function (module, exports, require) {(function() {
  var Url, _, fileRe, httpRe, jsUri;

  _ = require('lodash');

  Url = require('url');

  jsUri = require("jsuri");

  httpRe = /:\/\//;

  fileRe = /^file:\/\//;

  module.exports = {
    isFile: function(url) {
      return fileRe.test(url);
    },
    isAbsolute: function(url) {
      return httpRe.test(url) && !this.isFile(url);
    },
    isRelative: function(url) {
      return !this.isAbsolute(url) && !this.isFile(url);
    },
    detectScheme: function(url) {
      if (url == null) {
        url = "";
      }
      switch (false) {
        case !this.isFile(url):
          return "file";
        case !this.isAbsolute(url):
          return "absolute";
        case !this.isRelative(url):
          return "relative";
        default:
          throw new Error("Url: " + url + " did not match 'absolute', 'relative', or 'file' scheme.");
      }
    },
    mergeOrigin: function(origin, redirect) {
      var originUrl, redirectUrl;
      originUrl = Url.parse(origin);
      redirectUrl = Url.parse(redirect);
      _.each(_.pick(redirectUrl, "protocol", "auth", "hostname", "port", "pathname"), function(value, key) {
        if (value == null) {
          return redirectUrl[key] = originUrl[key];
        }
      });
      return redirectUrl.format();
    },
    merge: function(origin, redirect) {
      var originUrl, redirectUrl;
      originUrl = Url.parse(origin, true);
      redirectUrl = Url.parse(redirect, true);
      _.each(redirectUrl, function(value, key) {
        if (value == null) {
          return redirectUrl[key] = originUrl[key];
        }
      });
      return redirectUrl.format();
    },
    replaceHost: function(original, remoteHost) {
      original = new jsUri(original);
      remoteHost = new jsUri(remoteHost);
      original.setProtocol(remoteHost.protocol());
      original.setHost(remoteHost.host());
      original.setPort(remoteHost.port());
      return original.toString();
    },
    getOriginFromFqdnUrl: function(url) {
      url = Url.parse(url.slice(1));
      if (url.protocol && url.host) {
        url.pathname = "";
        url.search = "";
        url.hash = "";
        return url.format();
      }
    }
  };

}).call(this);

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

  _ = require("lodash");

  Promise = require("bluebird");

  chokidar = require("chokidar");

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

    Watchers.prototype.remove = function(key) {
      var watched;
      if (!(watched = this.watched[key])) {
        return;
      }
      watched.close();
      return delete this.watched[key];
    };

    Watchers.prototype._add = function(pathToFile, watched) {
      this.remove(pathToFile);
      return this.watched[pathToFile] = watched;
    };

    Watchers.prototype.close = function() {
      var key, ref, results, val;
      ref = this.watched;
      results = [];
      for (key in ref) {
        val = ref[key];
        results.push(this.remove(key));
      }
      return results;
    };

    Watchers.prototype.watchAsync = function(pathToFile, options) {
      var _this;
      if (options == null) {
        options = {};
      }
      _this = this;
      return new Promise((function(_this) {
        return function(resolve, reject) {
          options.onReady = function() {
            return resolve();
          };
          return _this.watch(pathToFile, options);
        };
      })(this));
    };

    Watchers.prototype.watch = function(pathToFile, 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(pathToFile, options);
      this._add(pathToFile, 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;
    };

    return Watchers;

  })();

  module.exports = Watchers;

}).call(this);

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