'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var serveHandler = require('serve-handler');
var http = require('node:http');
var httpProxy = require('http-proxy');
var utility = require('./utility.cjs.js');
var livereload = require('./livereload.cjs.js');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }

var serveHandler__default = /*#__PURE__*/_interopDefaultCompat(serveHandler);
var http__default = /*#__PURE__*/_interopDefaultCompat(http);
var httpProxy__default = /*#__PURE__*/_interopDefaultCompat(httpProxy);

class HTTPServer {
  proxyEndpoint;
  backstageBundleDir;
  backstagePort;
  mkdocsTargetAddress;
  verbose;
  constructor(backstageBundleDir, backstagePort, mkdocsTargetAddress, verbose) {
    this.proxyEndpoint = "/api/techdocs/";
    this.backstageBundleDir = backstageBundleDir;
    this.backstagePort = backstagePort;
    this.mkdocsTargetAddress = mkdocsTargetAddress;
    this.verbose = verbose;
  }
  // Create a Proxy for mkdocs server
  createProxy() {
    const proxy = httpProxy__default.default.createProxyServer({
      target: this.mkdocsTargetAddress
    });
    return (request) => {
      const proxyEndpointPath = new RegExp(`^${this.proxyEndpoint}`, "i");
      const forwardPath = request.url?.replace(proxyEndpointPath, "") || "";
      return [proxy, forwardPath];
    };
  }
  async serve() {
    return new Promise((resolve, reject) => {
      const proxyHandler = this.createProxy();
      const server = http__default.default.createServer(
        (request, response) => {
          if (request.url === "/api/techdocs/.backstage/auth/v1/cookie") {
            const oneHourInMilliseconds = 60 * 60 * 1e3;
            const expiresAt = new Date(Date.now() + oneHourInMilliseconds);
            const cookie = { expiresAt: expiresAt.toISOString() };
            response.setHeader("Content-Type", "application/json");
            response.end(JSON.stringify(cookie));
            return;
          }
          if (request.url?.startsWith(this.proxyEndpoint)) {
            if (request.url?.endsWith(".html")) {
              livereload.proxyHtmlWithLivereloadInjection({
                request,
                response,
                mkdocsTargetAddress: this.mkdocsTargetAddress,
                proxyEndpoint: this.proxyEndpoint,
                onError: (error) => reject(error)
              });
              return;
            }
            const [proxy, forwardPath] = proxyHandler(request);
            proxy.on("error", (error) => {
              reject(error);
            });
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
            request.url = forwardPath;
            proxy.web(request, response);
            return;
          }
          if (request.url === "/.detect") {
            response.setHeader("Content-Type", "text/plain");
            response.end("techdocs-cli-server");
            return;
          }
          if (request.url?.startsWith("/.livereload")) {
            livereload.proxyMkdocsLivereload({
              request,
              response,
              mkdocsTargetAddress: this.mkdocsTargetAddress,
              onError: (error) => reject(error)
            });
            return;
          }
          serveHandler__default.default(request, response, {
            public: this.backstageBundleDir,
            trailingSlash: true,
            rewrites: [{ source: "**", destination: "index.html" }]
          });
        }
      );
      const logger = utility.createLogger({ verbose: false });
      server.listen(this.backstagePort, () => {
        if (this.verbose) {
          logger.info(
            `[techdocs-preview-bundle] Running local version of Backstage at http://localhost:${this.backstagePort}`
          );
        }
        resolve(server);
      });
      server.on("error", (error) => {
        reject(error);
      });
    });
  }
}

exports.default = HTTPServer;
//# sourceMappingURL=httpServer.cjs.js.map
