/**
 * 打包单个组件
 */
import path from "path";
import { customConfig, rollupOptions } from "../config";
import { onReadDirectory, isDirectory, onWriteFile } from "./utils";
import { build, defineConfig, InlineConfig, UserConfig } from "vite";

// 单组件按需构建
const buildSingle = async (entryPath: string, outputDirPath: string) => {
  const buildConfig = {
    ...customConfig,
    build: {
      rollupOptions,
      lib: {
        entry: entryPath,
        name: "index",
        fileName: () => "index.js",
        formats: ["es"],
      },
      outDir: outputDirPath,
    },
  };
  await build(defineConfig(buildConfig as UserConfig) as InlineConfig);
};

// 生成组件的 package.json 文件
const createPackageJson = (outputDirPath: string, name: string) => {
  const fileStr = `{
    "name": "${name}",
    "version": "0.0.0",
    "main": "index.js"
  }`;
  onWriteFile(path.resolve(outputDirPath, `${name}/package.json`), fileStr);
};

const buildLib = async (compDirPath: string, outputDirPath: string) => {
  // 获取组件名称组成的数组
  const components = await onReadDirectory(compDirPath);
  components.filter(async (name) => {
    const componentDir = path.resolve(compDirPath, name);
    const isDir = await isDirectory(componentDir);
    const compFiles = await onReadDirectory(componentDir);
    return isDir && compFiles.includes("index.ts");
  });
  // 循环一个一个组件构建
  for (const name of components) {
    // 构建单组件
    await buildSingle(path.resolve(compDirPath, name), path.resolve(outputDirPath, name));
    // 生成组件的 package.json 文件
    await createPackageJson(outputDirPath, name);
  }
};

export default buildLib;
