// src/prebuild.ts
import { mkdir } from "fs/promises";
import { join as join2 } from "path";

// src/feature/function/prebuild.ts
import { days, seconds, toDays, toSeconds } from "@awsless/duration";
import { mebibytes, toMebibytes } from "@awsless/size";
import { aws } from "@terraforge/aws";
import { Future, resolveInputs } from "@terraforge/core";
import { pascalCase } from "change-case";
import { writeFile } from "fs/promises";
import { join } from "path";

// src/feature/function/build/typescript/bundle.ts
import commonjs from "@rollup/plugin-commonjs";
import json from "@rollup/plugin-json";
import nodeResolve from "@rollup/plugin-node-resolve";
import { createHash } from "crypto";
import { dirname } from "path";
import { rollup } from "rollup";
import natives from "rollup-plugin-natives";
import { importAsString } from "rollup-plugin-string-import";
import { swc, minify as swcMinify } from "rollup-plugin-swc3";

// src/cli/ui/style.ts
import chalk from "chalk";
var color = {
  primary: chalk.bold.hex("#FF9000"),
  // primary: chalk.bold.magentaBright,
  // title: chalk.white,
  normal: chalk.reset.white,
  label: chalk.reset.white.bold,
  dim: chalk.dim,
  line: chalk.black,
  // link: chalk.cyan,
  info: chalk.blue,
  success: chalk.green,
  warning: chalk.yellow,
  error: chalk.red,
  attr: chalk.yellow
  // cursor: chalk.bgWhite.blackBright,
};

// src/cli/debug.ts
var queue = [];
var debugError = (error) => {
  queue.push({
    date: /* @__PURE__ */ new Date(),
    type: color.error.dim("error"),
    message: typeof error === "string" ? error : error instanceof Error ? color.error(error.message || "") : JSON.stringify(error)
  });
};

// src/feature/function/build/typescript/bundle.ts
var bundleTypeScript = async ({
  format = "esm",
  minify = true,
  file,
  nativeDir,
  external,
  importAsString: importAsStringList
}) => {
  const bundle = await rollup({
    input: file,
    external: (importee) => {
      return importee.startsWith("@aws-sdk") || importee.startsWith("aws-sdk") || external?.includes(importee);
    },
    onwarn: (error) => {
      debugError(error.message);
    },
    treeshake: {
      preset: "smallest",
      moduleSideEffects: (id) => file === id
    },
    plugins: [
      commonjs({ sourceMap: true }),
      nodeResolve({ preferBuiltins: true }),
      // @ts-ignore
      nativeDir ? natives({
        copyTo: nativeDir,
        targetEsm: format === "esm",
        sourcemap: true
      }) : void 0,
      swc({
        // minify,
        // module: true,
        jsc: {
          baseUrl: dirname(file),
          minify: { sourceMap: true }
        },
        sourceMaps: true
      }),
      minify ? swcMinify({
        module: format === "esm",
        sourceMap: true,
        compress: true
      }) : void 0,
      json(),
      importAsStringList ? importAsString({
        include: importAsStringList
      }) : void 0
    ]
  });
  const ext = format === "esm" ? "mjs" : "js";
  const result = await bundle.generate({
    format,
    sourcemap: "hidden",
    exports: "auto",
    manualChunks: {},
    entryFileNames: `index.${ext}`,
    chunkFileNames: `[name].${ext}`
  });
  const hash = createHash("sha1");
  const files = [];
  for (const item of result.output) {
    if (item.type !== "chunk") {
      continue;
    }
    const code = Buffer.from(item.code, "utf8");
    const map = item.map ? Buffer.from(item.map.toString(), "utf8") : void 0;
    item.map?.version;
    hash.update(code);
    files.push({
      name: item.fileName,
      code,
      map
    });
  }
  return {
    hash: hash.digest("hex"),
    files
  };
};

// src/feature/function/build/zip.ts
import { createReadStream } from "fs";
import JSZip from "jszip";
var zipFiles = (files) => {
  const zip = new JSZip();
  for (const file of files) {
    if ("path" in file) {
      zip.file(file.name, createReadStream(file.path));
    } else {
      zip.file(file.name, file.code);
    }
  }
  return zip.generateAsync({
    type: "nodebuffer",
    compression: "DEFLATE",
    compressionOptions: {
      level: 9
    }
  });
};

// src/feature/function/prebuild.ts
var prebuild = async (file, output, external = []) => {
  const bundle = await bundleTypeScript({
    file,
    minify: true,
    external
  });
  const archive = await zipFiles(bundle.files);
  await writeFile(join(output, "HASH"), bundle.hash);
  await writeFile(join(output, "bundle.zip"), archive);
};

// src/prebuild.ts
var cwd = join2(process.cwd(), "./dist");
var builds = {
  rpc: "../src/feature/rpc/server/handle.ts",
  image: "../src/feature/image/server/handle.ts",
  icon: "../src/feature/icon/server/handle.ts"
};
for (const [name, file] of Object.entries(builds)) {
  const output = join2(cwd, "prebuild", name);
  await mkdir(output, { recursive: true });
  await prebuild(join2(cwd, file), output, ["sharp"]);
}
