// MIT License
// Copyright (c) 2021 Marton Lederer
// https://github.com/martonlederer/esbuild-plugin-yaml/tree/d8d14d18c999f6507e906a7015ace0c991b507b4
import { isAbsolute, join } from "path"
import { TextDecoder } from "util"
import { promises as fs } from "fs"
import type { Plugin } from "esbuild"
import type { LoadOptions } from "js-yaml"
import yaml from "js-yaml"

interface YamlPluginOptions {
  loadOptions?: LoadOptions
}

export const yamlPlugin = (options: YamlPluginOptions = {}): Plugin => ({
  name: "yaml",
  setup(build) {
    // resolve .yaml and .yml files
    build.onResolve({ filter: /\.(yml|yaml)$/ }, ({ path, resolveDir }) => {
      if (resolveDir === "") return

      return {
        path: isAbsolute(path) ? path : join(resolveDir, path),
        namespace: "yaml",
      }
    })

    // load files with "yaml" namespace
    build.onLoad({ filter: /.*/, namespace: "yaml" }, async ({ path }) => {
      const yamlContent = await fs.readFile(path)
      const parsed = yaml.load(
        new TextDecoder().decode(yamlContent),
        options?.loadOptions,
      ) as any

      return {
        contents: JSON.stringify(parsed),
        loader: "json",
      }
    })
  },
})
