'use strict';

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

var path = require('node:path');
var openBrowser = require('react-dev-utils/openBrowser');
var cliCommon = require('@backstage/cli-common');
var httpServer = require('../../lib/httpServer.cjs.js');
var mkdocsServer = require('../../lib/mkdocsServer.cjs.js');
var utility = require('../../lib/utility.cjs.js');
var pluginTechdocsNode = require('@backstage/plugin-techdocs-node');
var fs = require('fs-extra');
var utils = require('./utils.cjs.js');

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

var path__default = /*#__PURE__*/_interopDefaultCompat(path);
var openBrowser__default = /*#__PURE__*/_interopDefaultCompat(openBrowser);
var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);

function findPreviewBundlePath() {
  try {
    return path__default.default.join(
      path__default.default.dirname(require.resolve("techdocs-cli-embedded-app/package.json")),
      "dist"
    );
  } catch {
    return cliCommon.findOwnPaths(__dirname).resolve("dist/embedded-app");
  }
}
function getPreviewAppPath(opts) {
  return opts.previewAppBundlePath ?? findPreviewBundlePath();
}
async function serve(opts) {
  const logger = utility.createLogger({ verbose: opts.verbose });
  const isDevMode = Object.keys(process.env).includes("TECHDOCS_CLI_DEV_MODE") ? true : false;
  const backstageBackendPort = 7007;
  const mkdocsDockerAddr = `http://0.0.0.0:${opts.mkdocsPort}`;
  const mkdocsLocalAddr = `http://127.0.0.1:${opts.mkdocsPort}`;
  const mkdocsExpectedDevAddr = opts.docker ? mkdocsDockerAddr : mkdocsLocalAddr;
  const mkdocsConfigFileName = opts.mkdocsConfigFileName;
  const siteName = opts.siteName;
  const { path: mkdocsYmlPath, configIsTemporary } = await pluginTechdocsNode.getMkdocsYml("./", {
    name: siteName,
    mkdocsConfigFileName
  });
  if (opts.docker) {
    const isDockerOperational = await utils.checkIfDockerIsOperational(logger);
    if (!isDockerOperational) {
      return;
    }
  }
  let mkdocsServerHasStarted = false;
  const mkdocsLogFunc = (data) => {
    const logLines = data.toString().split("\n");
    const logPrefix = opts.docker ? "[docker/mkdocs]" : "[mkdocs]";
    logLines.forEach((line) => {
      if (line === "") {
        return;
      }
      logger.verbose(`${logPrefix} ${line}`);
      if (!mkdocsServerHasStarted && line.includes(`Serving on ${mkdocsExpectedDevAddr}`)) {
        mkdocsServerHasStarted = true;
      }
    });
  };
  logger.info("Starting mkdocs server.");
  const mkdocsChildProcess = mkdocsServer.runMkdocsServer({
    port: opts.mkdocsPort,
    dockerImage: opts.dockerImage,
    dockerEntrypoint: opts.dockerEntrypoint,
    dockerOptions: opts.dockerOption,
    useDocker: opts.docker,
    onStdout: mkdocsLogFunc,
    onStderr: mkdocsLogFunc,
    mkdocsConfigFileName: mkdocsYmlPath,
    mkdocsParameterClean: opts.mkdocsParameterClean,
    mkdocsParameterDirtyReload: opts.mkdocsParameterDirtyreload,
    mkdocsParameterStrict: opts.mkdocsParameterStrict
  });
  for (let attempt = 0; attempt < 30; attempt++) {
    await new Promise((r) => setTimeout(r, 3e3));
    if (mkdocsServerHasStarted) {
      break;
    }
    logger.info("Waiting for mkdocs server to start...");
  }
  if (!mkdocsServerHasStarted) {
    logger.error(
      "mkdocs server did not start. Exiting. Try re-running command with -v option for more details."
    );
  }
  const port = isDevMode ? backstageBackendPort : opts.previewAppPort;
  const previewAppPath = getPreviewAppPath(opts);
  const httpServer$1 = new httpServer.default(
    previewAppPath,
    port,
    mkdocsExpectedDevAddr,
    opts.verbose
  );
  httpServer$1.serve().catch((err) => {
    logger.error("Failed to start HTTP server", err);
    mkdocsChildProcess.kill();
    process.exit(1);
  }).then(() => {
    openBrowser__default.default(`http://localhost:${port}/docs/default/component/local/`);
    logger.info(
      `Serving docs in Backstage at http://localhost:${port}/docs/default/component/local/
Opening browser.`
    );
  });
  await mkdocsChildProcess.waitForExit();
  if (configIsTemporary) {
    process.on("exit", async () => {
      fs__default.default.rmSync(mkdocsYmlPath, {});
    });
  }
}

exports.default = serve;
//# sourceMappingURL=serve.cjs.js.map
