"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/analytics/log-build.js
var log_build_exports = {};
__export(log_build_exports, {
  default: () => log_build_default
});
module.exports = __toCommonJS(log_build_exports);

// src/eventcatalog-config-file-utils.js
var import_promises = require("fs/promises");
var import_node_fs = require("fs");
var import_node_path = __toESM(require("path"), 1);
var import_uuid = require("uuid");
var import_url = require("url");
var import_node_os = require("os");
var import_gray_matter = __toESM(require("gray-matter"), 1);
async function cleanup(projectDirectory) {
  const filePath = import_node_path.default.join(projectDirectory, "eventcatalog.config.mjs");
  if ((0, import_node_fs.existsSync)(filePath)) {
    await (0, import_promises.rm)(filePath);
  }
}
var findNodeModulesDirectory = (directory) => {
  let currentDirectory = directory;
  while (true) {
    const nodeModulesDirectory = import_node_path.default.join(currentDirectory, "node_modules");
    if ((0, import_node_fs.existsSync)(nodeModulesDirectory)) {
      return nodeModulesDirectory;
    }
    const parentDirectory = import_node_path.default.dirname(currentDirectory);
    if (parentDirectory === currentDirectory) {
      return void 0;
    }
    currentDirectory = parentDirectory;
  }
};
var linkNodeModulesIntoTempDirectory = async ({ projectDirectory, tempDir }) => {
  const nodeModulesDirectory = findNodeModulesDirectory(projectDirectory);
  if (!nodeModulesDirectory) {
    return;
  }
  await (0, import_promises.symlink)(nodeModulesDirectory, import_node_path.default.join(tempDir, "node_modules"), "dir");
};
var createTemporaryConfigDirectory = async (projectDirectory) => {
  const nodeModulesDirectory = findNodeModulesDirectory(projectDirectory);
  if (nodeModulesDirectory) {
    return (0, import_promises.mkdtemp)(import_node_path.default.join(nodeModulesDirectory, ".eventcatalog-config-"));
  }
  const tempDir = await (0, import_promises.mkdtemp)(import_node_path.default.join((0, import_node_os.tmpdir)(), "eventcatalog-config-"));
  await linkNodeModulesIntoTempDirectory({ projectDirectory, tempDir });
  return tempDir;
};
var getEventCatalogConfigFile = async (projectDirectory) => {
  let tempDir;
  try {
    let configFilePath = import_node_path.default.join(projectDirectory, "eventcatalog.config.js");
    const filePath = import_node_path.default.join(projectDirectory, "package.json");
    const packageJson = JSON.parse(await (0, import_promises.readFile)(filePath, "utf-8"));
    if (packageJson?.type !== "module") {
      tempDir = await createTemporaryConfigDirectory(projectDirectory);
      configFilePath = import_node_path.default.join(tempDir, "eventcatalog.config.mjs");
      await (0, import_promises.copyFile)(import_node_path.default.join(projectDirectory, "eventcatalog.config.js"), configFilePath);
    }
    const configFileURL = `${(0, import_url.pathToFileURL)(configFilePath).href}?t=${Date.now()}`;
    const config = await import(
      /* @vite-ignore */
      configFileURL
    );
    return config.default;
  } finally {
    await cleanup(projectDirectory);
    if (tempDir) {
      await (0, import_promises.rm)(tempDir, { recursive: true, force: true });
    }
  }
};
var writeEventCatalogConfigFile = async (projectDirectory, newConfig) => {
  try {
    const configFilePath = import_node_path.default.join(projectDirectory, "eventcatalog.config.js");
    let content = await (0, import_promises.readFile)(configFilePath, "utf8");
    const startIndex = content.indexOf("export default {");
    if (startIndex === -1) {
      return;
    }
    Object.entries(newConfig).forEach(([key, value]) => {
      const valueString = JSON.stringify(value, null, 2).replace(/"/g, "'").replace(/\n/g, "\n  ");
      const keyRegex = new RegExp(`(${key}\\s*:)([^,}]+)`, "g");
      if (content.match(keyRegex)) {
        content = content.replace(keyRegex, `$1 ${valueString}`);
      } else {
        const insertPosition = content.indexOf("{", startIndex) + 1;
        content = content.slice(0, insertPosition) + `
  ${key}: ${valueString},` + content.slice(insertPosition);
      }
    });
    await (0, import_promises.writeFile)(configFilePath, content);
  } finally {
    await cleanup(projectDirectory);
  }
};
var verifyRequiredFieldsAreInCatalogConfigFile = async (projectDirectory) => {
  try {
    const config = await getEventCatalogConfigFile(projectDirectory);
    if (!config.cId) {
      await writeEventCatalogConfigFile(projectDirectory, { cId: (0, import_uuid.v4)() });
    }
  } catch (error) {
  }
};

// src/analytics/analytics.js
var import_os = __toESM(require("os"), 1);

// package.json
var version = "3.44.0";

// src/constants.ts
var VERSION = version;

// src/analytics/analytics.js
async function raiseEvent(eventData) {
  const url = "https://queue.simpleanalyticscdn.com/events";
  const userAgent = `@eventcatalog/eventcatalog@${VERSION} (${import_os.default.platform()}; ${import_os.default.arch()}; Node/${process.version})`;
  const headers = {
    "Content-Type": "application/json"
  };
  const payload = {
    type: "event",
    hostname: "eventcatalog.dev",
    event: "@eventcatalog/eventcatalog",
    metadata: {
      ...eventData,
      t: `t;${(/* @__PURE__ */ new Date()).toISOString()}`,
      ua: userAgent
    },
    ua: userAgent
  };
  try {
    const response = await fetch(url, {
      method: "POST",
      headers,
      body: JSON.stringify(payload)
    });
    if (!response.ok) {
      throw new Error(`Failed to raise analytics event: ${response.status}`);
    }
  } catch (error) {
  }
}

// src/analytics/count-resources.js
var import_glob = require("glob");
var RESOURCE_PATTERNS = {
  adrs: ["**/adrs/*/index.@(md|mdx)"],
  agents: ["**/agents/*/index.@(md|mdx)"],
  events: ["**/events/*/index.@(md|mdx)"],
  commands: ["**/commands/*/index.@(md|mdx)"],
  queries: ["**/queries/*/index.@(md|mdx)"],
  services: ["**/services/*/index.@(md|mdx)"],
  domains: ["domains/*/index.@(md|mdx)", "domains/*/subdomains/*/index.@(md|mdx)"],
  flows: ["**/flows/*/index.@(md|mdx)"],
  channels: ["**/channels/**/index.@(md|mdx)"],
  entities: ["**/entities/*/index.@(md|mdx)"],
  containers: ["**/containers/**/index.@(md|mdx)"],
  "data-products": ["**/data-products/*/index.@(md|mdx)"],
  teams: ["teams/*.@(md|mdx)"],
  users: ["users/*.@(md|mdx)"],
  designs: ["**/*.ecstudio"],
  diagrams: ["**/diagrams/**/index.@(md|mdx)"],
  ubiquitousLanguages: ["domains/*/ubiquitous-language.@(md|mdx)", "domains/*/subdomains/*/ubiquitous-language.@(md|mdx)"]
};
async function countResources(projectDir) {
  const counts = {};
  for (const [type, patterns] of Object.entries(RESOURCE_PATTERNS)) {
    let total = 0;
    for (const pattern of patterns) {
      const files = await (0, import_glob.glob)(pattern, {
        cwd: projectDir,
        ignore: ["**/versioned/**", "**/dist/**", "**/node_modules/**"]
      });
      total += files.length;
    }
    counts[type] = total;
  }
  return counts;
}
function serializeCounts(counts) {
  return Object.entries(counts).map(([k, v]) => `${k}:${v}`).join(",");
}

// src/analytics/log-build.js
var getFeatures = async (configFile) => {
  return {
    llmsTxt: configFile.llmsTxt?.enabled || false,
    rss: configFile.rss?.enabled || false,
    chat: configFile.chat?.enabled || false,
    output: configFile.output || "static"
  };
};
var getDirectoryProvider = (source) => {
  if (!source?.name || typeof source.name !== "string") return "unknown";
  return source.name.split(":")[0] || "unknown";
};
var serializeDirectorySources = (configFile) => {
  const sources = configFile.directory?.sources;
  if (!Array.isArray(sources) || sources.length === 0) return "none";
  const providerCounts = sources.reduce((counts, source) => {
    const provider = getDirectoryProvider(source);
    counts[provider] = (counts[provider] || 0) + 1;
    return counts;
  }, {});
  const providers = Object.keys(providerCounts).sort().map((provider) => `${provider}:${providerCounts[provider]}`).join(",");
  const hasUsers = sources.some((source) => typeof source?.loadUsers === "function");
  const hasTeams = sources.some((source) => typeof source?.loadTeams === "function");
  return `sources:${sources.length},providers:${providers},users:${hasUsers},teams:${hasTeams}`;
};
var CLOUD_ANALYTICS_ENDPOINT = "https://api.ecingest.dev/v1/analytics/ingest";
var toCloudResourceCounts = (counts) => ({
  adrs: counts.adrs || 0,
  agents: counts.agents || 0,
  domains: counts.domains || 0,
  services: counts.services || 0,
  events: counts.events || 0,
  commands: counts.commands || 0,
  queries: counts.queries || 0,
  flows: counts.flows || 0,
  channels: counts.channels || 0,
  entities: counts.entities || 0,
  containers: counts.containers || 0,
  dataProducts: counts["data-products"] || 0,
  teams: counts.teams || 0,
  users: counts.users || 0,
  designs: counts.designs || 0,
  diagrams: counts.diagrams || 0,
  ubiquitousLanguages: counts.ubiquitousLanguages || 0
});
var reportCloudResourceInventory = async (configFile, resourceCounts) => {
  const analytics = configFile.cloud?.analytics;
  if (!analytics?.enabled || !analytics.trackingId || !analytics.writeKey) return;
  const endpoint = analytics.endpoint || CLOUD_ANALYTICS_ENDPOINT;
  await fetch(endpoint, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-EventCatalog-Analytics-Key": analytics.writeKey
    },
    body: JSON.stringify({
      trackingId: analytics.trackingId,
      event: "catalog.resource_inventory_reported",
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      counts: toCloudResourceCounts(resourceCounts)
    })
  });
};
var main = async (projectDir, { isEventCatalogStarterEnabled, isEventCatalogScaleEnabled, isBackstagePluginEnabled }) => {
  try {
    await verifyRequiredFieldsAreInCatalogConfigFile(projectDir);
    const configFile = await getEventCatalogConfigFile(projectDir);
    const { cId, organizationName, generators = [] } = configFile;
    let generatorNames = generators.length > 0 ? generators.map((generator) => generator[0]) : ["none"];
    if (isEventCatalogStarterEnabled) {
      generatorNames.push("@eventcatalog/eventcatalog-starter");
    }
    if (isEventCatalogScaleEnabled) {
      generatorNames.push("@eventcatalog/eventcatalog-scale");
    }
    if (isBackstagePluginEnabled) {
      generatorNames.push("@eventcatalog/backstage-plugin-eventcatalog");
    }
    const features = await getFeatures(configFile);
    const resourceCounts = await countResources(projectDir);
    await reportCloudResourceInventory(configFile, resourceCounts);
    await raiseEvent({
      command: "build",
      org: organizationName,
      cId,
      generators: generatorNames.toString(),
      features: Object.keys(features).map((feature) => `${feature}:${features[feature]}`).join(","),
      directorySources: serializeDirectorySources(configFile),
      resources: serializeCounts(resourceCounts)
    });
  } catch (error) {
  }
};
var log_build_default = main;
