"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 devServer_exports = {};
__export(devServer_exports, {
  HMR_SOCK_PATH: () => HMR_SOCK_PATH,
  formatRoutes: () => formatRoutes,
  getDevOptions: () => getDevOptions,
  isClientCompiler: () => isClientCompiler,
  mergeDevOptions: () => mergeDevOptions,
  printServerURLs: () => printServerURLs,
  setupServerHooks: () => setupServerHooks
});
module.exports = __toCommonJS(devServer_exports);
var import_port = require("./port");
var import_deepmerge = __toESM(require("../compiled/deepmerge"));
var import_color = require("./color");
var import_logger = require("./logger");
var import_constants = require("./constants");
var import_url = require("./url");
const formatRoutes = (entry, prefix) => {
  return Object.keys(entry).map((name) => ({
    name,
    route: (prefix ? `${prefix}/` : "") + (name === "index" ? "" : 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_color.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 }) => {
      message += `  ${import_color.color.bold(`> ${label}`)}
`;
      routes.forEach((r) => {
        message += `    ${import_color.color.yellow("○")}  ${import_color.color.yellow(
          r.name.padEnd(maxNameLength + 8)
        )}${import_color.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: ""
    },
    compress: true,
    port,
    devMiddleware: {
      writeToDisk: (file) => !file.includes(".hot-update.")
    }
  };
  const devServerConfig = rsbuildConfig.dev ? (0, import_deepmerge.default)(defaultDevConfig, rsbuildConfig.dev) : defaultDevConfig;
  devServerConfig.port = port;
  return devServerConfig;
};
const getDevOptions = async ({
  rsbuildConfig,
  strictPort,
  getPortSilently
}) => {
  var _a, _b, _c;
  const port = await (0, import_port.getPort)(((_a = rsbuildConfig.dev) == null ? void 0 : _a.port) || import_constants.DEFAULT_PORT, {
    strictPort,
    silent: getPortSilently
  });
  const host = ((_b = rsbuildConfig.dev) == null ? void 0 : _b.host) || import_constants.DEFAULT_DEV_HOST;
  const https = Boolean((_c = rsbuildConfig.dev) == null ? void 0 : _c.https) || false;
  const devServerConfig = mergeDevOptions({ rsbuildConfig, port });
  return { devServerConfig, 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,
  isClientCompiler,
  mergeDevOptions,
  printServerURLs,
  setupServerHooks
});
