"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);

// src/watcher.js
var watcher_exports = {};
__export(watcher_exports, {
  watch: () => watch
});
module.exports = __toCommonJS(watcher_exports);
var import_watcher = __toESM(require("@parcel/watcher"), 1);
var import_node_fs = __toESM(require("fs"), 1);

// src/map-catalog-to-astro.js
var import_node_path = __toESM(require("path"), 1);
var COLLECTION_KEYS = [
  "agents",
  "events",
  "commands",
  "services",
  "domains",
  "flows",
  "pages",
  "changelogs",
  "queries",
  "channels",
  "ubiquitousLanguages",
  "dependencies"
];
function mapCatalogToAstro({ filePath, astroDir, projectDir }) {
  const relativeFilePath = removeBasePath(filePath, projectDir);
  if (!isCatalogRelated(relativeFilePath)) {
    return [];
  }
  const baseTargetPaths = getBaseTargetPaths(relativeFilePath);
  const relativeTargetPath = getRelativeTargetPath(relativeFilePath);
  return baseTargetPaths.map((base) => import_node_path.default.join(astroDir, base, relativeTargetPath));
}
function removeBasePath(fullPath, basePath) {
  const relativePath = import_node_path.default.relative(basePath, fullPath);
  return relativePath.startsWith("..") ? fullPath : relativePath;
}
function isCollectionKey(key) {
  return COLLECTION_KEYS.includes(key);
}
function isCatalogRelated(filePath) {
  const filePathArr = filePath.split(import_node_path.default.sep).filter(Boolean);
  if ([
    "eventcatalog.config.js",
    // config file at root
    "eventcatalog.styles.css",
    // custom styles file at root
    "components",
    // custom components
    "snippets",
    // custom snippets
    "public",
    // public assets
    ".env",
    // env file
    ...COLLECTION_KEYS
  ].includes(filePathArr[0])) {
    return true;
  }
  return false;
}
function getBaseTargetPaths(filePath) {
  const filePathArr = filePath.split(import_node_path.default.sep).filter(Boolean);
  if (isCollectionKey(filePathArr[0])) {
    const hasExtension = (str) => /\.[a-zA-Z0-9]{2,}$/.test(str);
    if (hasExtension(filePath)) {
      return [import_node_path.default.join("public", "generated")];
    }
    return [import_node_path.default.join("public", "generated")];
  }
  if (filePathArr[0] == "components") {
    return [import_node_path.default.join("src", "custom-defined-components")];
  }
  if (filePathArr[0] == "snippets") {
    return [import_node_path.default.join("src")];
  }
  if (filePathArr[0] == "public") {
    return [import_node_path.default.join("public")];
  }
  return [import_node_path.default.join("/")];
}
function getRelativeTargetPath(filePath) {
  const filePathArr = filePath.split(import_node_path.default.sep).filter(Boolean);
  if (filePathArr[0] == "public" || filePathArr[0] == "components") {
    filePathArr.shift();
  }
  if (filePathArr[0] == "snippets") {
    return import_node_path.default.join("snippets", ...filePathArr.slice(1));
  }
  const relativePath = [];
  for (let i = filePathArr.length - 1; i >= 0; i--) {
    relativePath.unshift(filePathArr[i]);
    if (isCollectionKey(filePathArr[i]) && filePathArr[i] != "snippets") break;
  }
  return import_node_path.default.join(...relativePath);
}

// src/watcher.js
var import_rimraf = require("rimraf");
async function watch(projectDirectory, catalogDirectory, callback = void 0) {
  const subscription = await import_watcher.default.subscribe(
    projectDirectory,
    compose(
      /**
       * @param {Error|null} err
       * @param {Event[]} events
       * @returns {unknown}
       */
      (err, events) => {
        if (err) {
          return;
        }
        for (let event of events) {
          const { path: filePath, type } = event;
          if (filePath.endsWith(".lock")) {
            continue;
          }
          if ((filePath.endsWith(".mdx") || filePath.endsWith(".md")) && !filePath.includes("snippets")) {
            continue;
          }
          const astroPaths = mapCatalogToAstro({
            filePath,
            astroDir: catalogDirectory,
            projectDir: projectDirectory
          });
          for (const astroPath of astroPaths) {
            switch (type) {
              case "create":
              case "update": {
                let stat;
                try {
                  stat = import_node_fs.default.statSync(filePath);
                } catch (err2) {
                  if (err2.code === "ENOENT") break;
                  throw err2;
                }
                if (stat.isDirectory()) {
                  import_node_fs.default.mkdirSync(astroPath, { recursive: true });
                } else {
                  retryEPERM(import_node_fs.default.cpSync)(filePath, astroPath);
                }
                break;
              }
              case "delete":
                retryEPERM(import_rimraf.rimrafSync)(astroPath);
                break;
            }
          }
        }
      },
      callback
    ),
    {
      ignore: [`**/${catalogDirectory}/!(${projectDirectory})**`]
    }
  );
  return () => subscription.unsubscribe();
}
function compose(...fns) {
  return function(err, events) {
    fns.filter(Boolean).forEach((fn, i) => {
      try {
        fn(err, events);
      } catch (error) {
        console.error({ error });
        throw error;
      }
    });
  };
}
var MAX_RETRIES = 5;
var DELAY_MS = 100;
function retryEPERM(fn) {
  return (...args) => {
    let retries = 0;
    while (retries < MAX_RETRIES) {
      try {
        return fn(...args);
      } catch (err) {
        if (err.code !== "EPERM") throw err;
        setTimeout(() => {
        }, DELAY_MS);
        retries += 1;
      }
    }
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  watch
});
