"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var server_exports = {};
__export(server_exports, {
  HMR_SOCK_PATH: () => HMR_SOCK_PATH,
  formatRoutes: () => formatRoutes,
  getDevOptions: () => getDevOptions,
  getServerOptions: () => getServerOptions,
  isClientCompiler: () => isClientCompiler,
  mergeDevOptions: () => mergeDevOptions,
  printServerURLs: () => printServerURLs,
  setupServerHooks: () => setupServerHooks
});
module.exports = __toCommonJS(server_exports);
var import_port = require("./port");
var import_deepmerge = __toESM(require("../compiled/deepmerge"));
var import_utils = require("./utils");
var import_logger = require("./logger");
var import_constants = require("./constants");
var import_url = require("./url");
const formatRoutes = (entry, prefix, outputStructure) => {
  return Object.keys(entry).map((name) => ({
    name,
    route: (prefix ? `${prefix}/` : "") + // fix case: /html/index/index.html
    (name === "index" && outputStructure !== "nested" ? "" : name)
  })).sort((a) => a.name === "index" ? -1 : 1);
};
function printServerURLs(urls, routes, logger = import_logger.logger) {
  let message = "";
  if (routes.length === 1) {
    message = urls.map(
      ({ label, url }) => `  ${`> ${label.padEnd(10)}`}${import_utils.color.cyan(
        (0, import_url.normalizeUrl)(`${url}/${routes[0].route}`)
      )}
`
    ).join("");
  } else {
    const maxNameLength = Math.max(...routes.map((r) => r.name.length));
    urls.forEach(({ label, url }, index) => {
      if (index > 0) {
        message += "\n";
      }
      message += `  ${`> ${label}`}
`;
      routes.forEach((r) => {
        message += `  ${import_utils.color.dim("-")} ${import_utils.color.dim(
          r.name.padEnd(maxNameLength + 4)
        )}${import_utils.color.cyan((0, import_url.normalizeUrl)(`${url}/${r.route}`))}
`;
      });
    });
  }
  logger.log(message);
}
const HMR_SOCK_PATH = "/rsbuild-hmr";
const mergeDevOptions = ({
  rsbuildConfig,
  port
}) => {
  const defaultDevConfig = {
    client: {
      path: HMR_SOCK_PATH,
      port: port.toString(),
      // By default it is set to "location.hostname"
      host: "",
      // By default it is set to "location.protocol === 'https:' ? 'wss' : 'ws'""
      protocol: ""
    },
    writeToDisk: false
  };
  const devConfig = rsbuildConfig.dev ? (0, import_deepmerge.default)(defaultDevConfig, rsbuildConfig.dev) : defaultDevConfig;
  return devConfig;
};
const getServerOptions = async ({
  rsbuildConfig,
  getPortSilently
}) => {
  const host = rsbuildConfig.server?.host || import_constants.DEFAULT_DEV_HOST;
  const port = await (0, import_port.getPort)({
    host,
    port: rsbuildConfig.server?.port || import_constants.DEFAULT_PORT,
    strictPort: rsbuildConfig.server?.strictPort || false,
    silent: getPortSilently
  });
  const https = Boolean(rsbuildConfig.server?.https) || false;
  return { port, host, https, serverConfig: rsbuildConfig.server || {} };
};
const getDevOptions = async ({
  rsbuildConfig,
  getPortSilently
}) => {
  const { port, host, https, serverConfig } = await getServerOptions({
    rsbuildConfig,
    getPortSilently
  });
  const devConfig = mergeDevOptions({ rsbuildConfig, port });
  return {
    devServerConfig: {
      ...serverConfig,
      ...devConfig
    },
    port,
    host,
    https
  };
};
const setupServerHooks = (compiler, hookCallbacks) => {
  if (compiler.name === "server") {
    return;
  }
  const { compile, invalid, done } = compiler.hooks;
  compile.tap("rsbuild-dev-server", hookCallbacks.onInvalid);
  invalid.tap("rsbuild-dev-server", hookCallbacks.onInvalid);
  done.tap("rsbuild-dev-server", hookCallbacks.onDone);
};
const isClientCompiler = (compiler) => {
  const { target } = compiler.options;
  if (target) {
    return Array.isArray(target) ? target.includes("web") : target === "web";
  }
  return false;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  HMR_SOCK_PATH,
  formatRoutes,
  getDevOptions,
  getServerOptions,
  isClientCompiler,
  mergeDevOptions,
  printServerURLs,
  setupServerHooks
});
