"use strict";

var _Object$keys = require("@babel/runtime-corejs2/core-js/object/keys");
var _Object$getOwnPropertySymbols = require("@babel/runtime-corejs2/core-js/object/get-own-property-symbols");
var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptor");
var _Object$getOwnPropertyDescriptors = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptors");
var _Object$defineProperties = require("@babel/runtime-corejs2/core-js/object/define-properties");
var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
var _parseInt2 = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/parse-int"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
function ownKeys(object, enumerableOnly) { var keys = _Object$keys(object); if (_Object$getOwnPropertySymbols) { var symbols = _Object$getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return _Object$getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(target, _Object$getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { _Object$defineProperty(target, key, _Object$getOwnPropertyDescriptor(source, key)); }); } return target; }
/*!
 * Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
 */

/* eslint max-nested-callbacks: [2, 3] */
/* eslint no-console: [0] */

var btoa = require("btoa");
var bodyParser = require("body-parser");
var browserify = require("browserify-middleware");
var compression = require("compression");
var cors = require("cors");
var express = require("express");
var fs = require("fs");
var glob = require("glob");
var http = require("http");
var morgan = require("morgan");
var path = require("path");
var querystring = require("querystring");
var request = require("request");
var url = require("url");
var base64 = require("urlsafe-base64");
var app = express();

// Configure Logging
// -----------------

if (process.env.DEBUG) {
  app.use(morgan("short", {
    immediate: true
  }));
}

// Configure CORS
// --------------

app.use(cors({
  credentials: true,
  origin: function origin(o, callback) {
    callback(null, true);
  }
}));

// Configure body processing
// -------------------------

app.use(bodyParser.raw({
  type: "image/*"
}));

// Enable gzip/deflate
// -------------------

app.use(compression());

// Close all connections
// ---------------------

// This *should* help tests run faster in IE, which has a very low number of
// allowed connections to the same origin.
app.use(function (req, res, next) {
  res.set("connection", "close");
  next();
});

// Configure Browserify
// --------------------

var appPattern = "packages/{*,*/*}/test/automation/fixtures/app.js";
glob.sync(appPattern).forEach(function (appjs) {
  var packageName = appjs.replace("packages/", "").replace("/test/automation/fixtures/app.js", "");

  // eslint-disable-next-line no-sync
  fs.statSync(appjs);
  app.use("/".concat(packageName, "/app.js"), browserify(appjs, {
    debug: true,
    transform: ["babelify", "envify"]
  }));
});

// Enable active routes
// --------------------

app.get('/', function (req, res) {
  res.send("<!DOCTYPE html>\n<html>\n  <head>\n    <title>Redirect Dispatcher</title>\n    <script>\n    try {\n      var state = /state=(.+?)(&.*)?$/.exec(window.location)[1]\n      console.info('state', state);\n      var name = JSON.parse(atob(state)).name;\n      console.info('name', name);\n      window.location.pathname = name;\n    }\n    catch(err) {\n      console.warn(err);\n    }\n    </script>\n  </head>\n  <body>\n\n  </body>\n</html>");
});
app.use("/cookies", require("./cookies"));
app.use("/json", require("./json"));
app.use("/form", require("./form"));
app.use("/files", require("./files"));
app.use("/jwt", require("@webex/test-helper-appid").router);
app.get("/requires-basic-auth", function (req, res) {
  if (req.headers.authorization === "Basic ".concat(btoa("basicuser:basicpass"))) {
    res.status(200).send().end();
  } else {
    res.status(403).send().end();
  }
});
app.get("/requires-bearer-auth", function (req, res) {
  if (req.headers.authorization === "Bearer bearertoken") {
    res.status(200).send().end();
  } else {
    res.status(403).send().end();
  }
});
app.get("/return-qs-as-object", function (req, res) {
  res.status(200).json(req.query).end();
});
app.get("/embargoed", function (req, res) {
  res.status(451).end();
});

// Enable static routes
// --------------------

var fixturePattern = "packages/{*,*/*}/test/automation/fixtures";
glob.sync(fixturePattern).forEach(function (fixturePath) {
  var packageName = fixturePath.replace("packages/", "").replace("/test/automation/fixtures", "");
  app.get("/".concat(packageName), function (req, res, next) {
    if (!req.query.code) {
      next();
      return;
    }
    var state = JSON.parse(base64.decode(req.query.state));
    if (state.exchange === false) {
      next();
      return;
    }
    request({
      /* eslint-disable camelcase */
      method: "POST",
      uri: "".concat(process.env.IDBROKER_BASE_URL || "https://idbroker.webex.com", "/idb/oauth2/v1/access_token"),
      form: {
        grant_type: "authorization_code",
        redirect_uri: process.env.WEBEX_REDIRECT_URI,
        code: req.query.code,
        self_contained_token: true
      },
      auth: {
        user: process.env.WEBEX_CLIENT_ID,
        pass: process.env.WEBEX_CLIENT_SECRET,
        sendImmediately: true
      }
      /* eslint-enable camelcase */
    }, function (err, response) {
      if (err) {
        console.warn("Request to CI failed with non-HTTP error");
        next(err);
        return;
      }
      if (response.statusCode >= 400) {
        console.warn("Got unexpected response from CI");
        next(new Error(response.body));
        return;
      }
      var redirect = url.parse(req.url, true);
      var qs = querystring.stringify(_objectSpread({
        state: req.query.state
      }, JSON.parse(response.body)));
      redirect = "".concat(redirect.pathname, "#").concat(qs);
      console.info("redirecting to ".concat(redirect));
      res.redirect(redirect);
    });
  });
  app.use("/".concat(packageName), express.static(fixturePath));
});
app.post("/refresh", bodyParser.json(), function (req, res, next) {
  if (!req.body.refresh_token) {
    next(new Error("`refresh_token` is required"));
    return;
  }
  console.info("Refreshing access token");
  request({
    /* eslint-disable camelcase */
    method: "POST",
    uri: "".concat(process.env.IDBROKER_BASE_URL || "https://idbroker.webex.com", "/idb/oauth2/v1/access_token"),
    form: {
      grant_type: "refresh_token",
      redirect_uri: process.env.WEBEX_REDIRECT_URI,
      refresh_token: req.body.refresh_token
    },
    auth: {
      user: process.env.WEBEX_CLIENT_ID,
      pass: process.env.WEBEX_CLIENT_SECRET,
      sendImmediately: true
    }
    /* eslint-enable camelcase */
  }, function (err, response) {
    if (err) {
      console.warn("Request to CI failed with non-HTTP error");
      next(err);
      return;
    }
    if (response.statusCode >= 400) {
      console.warn("Got unexpected response from CI");
      next(new Error(response.body));
      return;
    }
    console.info("Returning new access token");
    res.status(200).json(JSON.parse(response.body)).end();
  });
});
app.use(express.static(path.resolve(__dirname, '..', "static")));

// Start the server
// ----------------

var port = (0, _parseInt2.default)(process.env.SERVER_PORT, 10) || 8000;
http.createServer(app).listen(port, function () {
  console.log("Express server listening on port ".concat(port));
});
var fixtureport = (0, _parseInt2.default)(process.env.FIXTURE_PORT, 10) || 3000;
http.createServer(app).listen(fixtureport, function () {
  console.log("Express server listening on port ".concat(fixtureport));
});
var corsport = (0, _parseInt2.default)(process.env.CORS_PORT, 10) || 3002;
http.createServer(app).listen(corsport, function () {
  console.log("Express server listening on port ".concat(corsport));
});
//# sourceMappingURL=index.js.map
