if (typeof process === 'object' && process !== null &&
    process.env !== null && typeof process.env === 'object') {
  process.env.DD_GIT_REPOSITORY_URL = 'https://token@github.com/superblocksteam/superblocks.git';
  process.env.DD_GIT_COMMIT_SHA = '71329cb2a26133447acee36261ec5a5145024e84';
}
import { createRequire as $dd_createRequire } from 'module';
import { fileURLToPath as $dd_fileURLToPath } from 'url';
import { dirname as $dd_dirname } from 'path';
globalThis.require ??= $dd_createRequire(import.meta.url);
globalThis.__filename ??= $dd_fileURLToPath(import.meta.url);
globalThis.__dirname ??= $dd_dirname(globalThis.__filename);

import {
  cloneDeep_default,
  init_lodash,
  require_constants,
  require_dist,
  require_lib,
  require_slugify
} from "./chunk-DNVZMNUA.js";
import {
  __esm,
  __toESM,
  init_cjs_shims
} from "./chunk-MTQ2JLIW.js";

// ../util/dist/api-files/api.mjs
function slugifyName(originalName) {
  return (0, import_slugify.default)(originalName, {
    replacement: "_",
    lower: true
  });
}
function findUnusedFilePath(filename, extension, existingFilePaths) {
  let proposedFilename = `${filename}.${extension}`;
  let i = 1;
  while (existingFilePaths.has(proposedFilename)) {
    proposedFilename = `${filename}_${i}.${extension}`;
    i++;
  }
  existingFilePaths.add(proposedFilename);
  return proposedFilename;
}
function extractAdditionalStepFiles(api, additionalStepFiles, stepPathMap, currentStepNames, apiRepresentation) {
  if (!api.blocks || !apiRepresentation?.extractLargeSourceFiles) {
    return api;
  }
  const apiClone = cloneDeep_default(api);
  const minLinesForExtraction = apiRepresentation?.minLinesForExtraction ?? import_constants.DEFAULT_LINES_FOR_LARGE_STEPS;
  const existingFilePaths = /* @__PURE__ */ new Set();
  extractAdditionalStepFilesFromBlocks(apiClone.blocks ?? [], additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
  return apiClone;
}
function extractAdditionalStepFilesFromStep(step, name, additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames) {
  if (step && "integration" in step) {
    const integration = step.integration;
    const extension = import_constants.LANGUAGE_STEP_EXTENSIONS[integration];
    if (extension) {
      const languageContent = step[integration];
      if (languageContent) {
        const blockBody = languageContent.body;
        if (blockBody && typeof blockBody === "string") {
          const lines = blockBody?.split("\n");
          const linesNum = lines?.length;
          if (linesNum && linesNum > minLinesForExtraction) {
            let relativePath;
            if (stepPathMap?.[name]) {
              relativePath = stepPathMap[name].startsWith("./") ? stepPathMap[name].split("./")?.[1] : stepPathMap[name];
            } else {
              relativePath = findUnusedFilePath(slugifyName(name), extension, existingFilePaths);
              stepPathMap[name] = `./${relativePath}`;
            }
            additionalStepFiles.push({
              relativePath,
              contents: blockBody,
              language: integration
            });
            currentStepNames.push(name);
            languageContent.body = {
              path: `./${relativePath}`
            };
          }
        }
      }
    }
  }
}
function extractAdditionalStepFilesFromBlocks(blocks, additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames) {
  for (const block of blocks) {
    if (block.step) {
      extractAdditionalStepFilesFromStep(block.step, block.name, additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
    }
    extractAdditionalStepFilesFromBlocks(block.loop?.blocks ?? [], additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
    if (block.tryCatch) {
      extractAdditionalStepFilesFromBlocks(block.tryCatch.try?.blocks ?? [], additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
      extractAdditionalStepFilesFromBlocks(block.tryCatch.catch?.blocks ?? [], additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
      extractAdditionalStepFilesFromBlocks(block.tryCatch.finally?.blocks ?? [], additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
    }
    if (block.conditional) {
      extractAdditionalStepFilesFromBlocks(block.conditional.if?.blocks ?? [], additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
      for (const elseIfBlock of block.conditional.elseIf ?? []) {
        extractAdditionalStepFilesFromBlocks(elseIfBlock.blocks, additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
      }
      extractAdditionalStepFilesFromBlocks(block.conditional.else?.blocks ?? [], additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
    }
    if (block.parallel) {
      for (const path of Object.values(block.parallel?.static?.paths ?? {})) {
        extractAdditionalStepFilesFromBlocks(path.blocks, additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
      }
      extractAdditionalStepFilesFromBlocks(block.parallel?.dynamic?.blocks ?? [], additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
    }
    if (block.stream) {
      const trigger = block.stream.trigger;
      if (trigger && trigger.step) {
        extractAdditionalStepFilesFromStep(trigger.step, trigger.name, additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
      }
      extractAdditionalStepFilesFromBlocks(block.stream.process?.blocks ?? [], additionalStepFiles, existingFilePaths, minLinesForExtraction, stepPathMap, currentStepNames);
    }
  }
}
async function readYamlFile(path) {
  return (0, import_yaml.parse)(await import_fs_extra.default.readFile(path, "utf8"));
}
async function resolveLanguageSpecificStepContentFromBlocks(parentPath, blocks, stepPathMap) {
  for (const block of blocks) {
    if (block.step) {
      const step = block.step;
      await resolveLanguageSpecificStepContentFromStep(parentPath, step, block.name, stepPathMap);
    }
    if (block.conditional) {
      await resolveLanguageSpecificStepContentFromBlocks(parentPath, block.conditional.if?.blocks ?? [], stepPathMap);
      for (const elseIfBlock of block.conditional.elseIf) {
        await resolveLanguageSpecificStepContentFromBlocks(parentPath, elseIfBlock.blocks, stepPathMap);
      }
      await resolveLanguageSpecificStepContentFromBlocks(parentPath, block.conditional.else?.blocks ?? [], stepPathMap);
    }
    await resolveLanguageSpecificStepContentFromBlocks(parentPath, block.loop?.blocks ?? [], stepPathMap);
    if (block.tryCatch) {
      await resolveLanguageSpecificStepContentFromBlocks(parentPath, block.tryCatch.try?.blocks ?? [], stepPathMap);
      await resolveLanguageSpecificStepContentFromBlocks(parentPath, block.tryCatch.catch?.blocks ?? [], stepPathMap);
      await resolveLanguageSpecificStepContentFromBlocks(parentPath, block.tryCatch.finally?.blocks ?? [], stepPathMap);
    }
    if (block.parallel) {
      for (const path of Object.values(block.parallel?.static?.paths ?? {})) {
        await resolveLanguageSpecificStepContentFromBlocks(parentPath, path.blocks, stepPathMap);
      }
      await resolveLanguageSpecificStepContentFromBlocks(parentPath, block.parallel?.dynamic?.blocks ?? [], stepPathMap);
    }
    if (block.stream) {
      await resolveLanguageSpecificStepContentFromBlocks(parentPath, block.stream.process?.blocks ?? [], stepPathMap);
      await resolveLanguageSpecificStepContentFromStep(parentPath, block.stream.trigger?.step ?? {}, block.stream.trigger?.name, stepPathMap);
    }
  }
}
async function resolveLanguageSpecificStepContentFromStep(parentPath, step, stepName, stepPathMap) {
  if (!step?.integration || !import_constants.LANGUAGE_STEP_EXTENSIONS[step.integration]) {
    return;
  }
  const languageContent = step[step.integration];
  if (languageContent.body && typeof languageContent.body === "object" && "path" in languageContent.body) {
    const languageFilePath = `${parentPath}/${languageContent.body.path}`;
    if (await import_fs_extra.default.pathExists(languageFilePath)) {
      const stepBodyContent = await import_fs_extra.default.readFile(languageFilePath, "utf8");
      if (stepBodyContent && languageContent) {
        if (stepPathMap && stepName) {
          stepPathMap[stepName] = languageContent.body.path;
        }
        languageContent.body = stepBodyContent;
      }
    }
  }
}
async function writeApiFiles(api, apiNameSlug, directoryPath, nestedApiFiles, apiPromises, additionalStepFiles, apiRepresentation, existingFilePaths, stepPathMap) {
  let pathForApiFile = directoryPath;
  let yamlFileName = `${apiNameSlug}.yaml`;
  const currentStepNames = [];
  const updatedApi = extractAdditionalStepFiles(api.apiPb, additionalStepFiles, stepPathMap ?? {}, currentStepNames, apiRepresentation);
  if (stepPathMap) {
    Object.keys(stepPathMap).forEach((stepName) => {
      if (!currentStepNames.includes(stepName)) {
        const stepFileName = stepPathMap[stepName].startsWith("./") ? stepPathMap[stepName].split("./")[1] : stepPathMap[stepName];
        import_fs_extra.default.remove(`${pathForApiFile}/${stepFileName}`);
        delete stepPathMap[stepName];
      }
    });
  }
  if (apiRepresentation?.extractLargeSourceFiles) {
    if (nestedApiFiles) {
      pathForApiFile = `${pathForApiFile}/${apiNameSlug}`;
      yamlFileName = "api.yaml";
    }
    await import_fs_extra.default.ensureDir(pathForApiFile);
    for (const stepFile of additionalStepFiles) {
      const sourceFilePath = `${pathForApiFile}/${stepFile.relativePath}`;
      const handleApi2 = async () => {
        await import_fs_extra.default.outputFile(sourceFilePath, stepFile.contents);
      };
      apiPromises.push(handleApi2());
      existingFilePaths?.delete(sourceFilePath);
    }
  } else {
    existingFilePaths?.add(`${directoryPath}/${apiNameSlug}`);
  }
  const apiContent = (0, import_yaml.stringify)(updatedApi, {
    sortMapEntries: true,
    blockQuote: "literal"
  });
  const yamlFilePath = `${pathForApiFile}/${yamlFileName}`;
  const handleApi = async () => {
    await import_fs_extra.default.outputFile(yamlFilePath, apiContent);
  };
  apiPromises.push(handleApi());
  existingFilePaths?.delete(yamlFilePath);
}
async function readAppApiYamlFile(parentDirectory, apiName, slugifyDirectoryName = true) {
  const apiNameSlug = slugifyName(apiName ?? "api");
  const singularApiYamlPath = `${parentDirectory}/${apiNameSlug}.yaml`;
  const apiDirPath = `${parentDirectory}/${slugifyDirectoryName ? apiNameSlug : apiName}`;
  const nestedApiYamlPath = `${apiDirPath}/api.yaml`;
  let yamlPath;
  let yamlParentPath;
  if (await import_fs_extra.default.pathExists(singularApiYamlPath)) {
    yamlPath = singularApiYamlPath;
    yamlParentPath = parentDirectory;
  } else if (await import_fs_extra.default.pathExists(nestedApiYamlPath)) {
    yamlPath = nestedApiYamlPath;
    yamlParentPath = apiDirPath;
  } else {
    throw new Error(`API ${apiName ?? ""} not found at ${parentDirectory}`);
  }
  const apiDefn = await readYamlFile(yamlPath);
  const stepPathMap = {};
  await resolveLanguageSpecificStepContentFromBlocks(yamlParentPath, apiDefn.blocks ?? [], stepPathMap);
  return { api: apiDefn, stepPathMap };
}
var import_fs_extra, import_slugify, import_yaml, import_constants;
var init_api = __esm({
  "../util/dist/api-files/api.mjs"() {
    init_cjs_shims();
    import_fs_extra = __toESM(require_lib(), 1);
    init_lodash();
    import_slugify = __toESM(require_slugify(), 1);
    import_yaml = __toESM(require_dist(), 1);
    import_constants = __toESM(require_constants(), 1);
  }
});
init_api();
export {
  readAppApiYamlFile,
  resolveLanguageSpecificStepContentFromBlocks,
  writeApiFiles
};
//# sourceMappingURL=api-OCSWZT57.js.map
