'use strict';

var chunkTFTEYV3L_cjs = require('./chunk-TFTEYV3L.cjs');
var chunkOTH2GDR2_cjs = require('./chunk-OTH2GDR2.cjs');
var chunkAF3E2D32_cjs = require('./chunk-AF3E2D32.cjs');
var types$1 = require('@stryke/env/types');
var camelCase = require('@stryke/string-format/camel-case');
var isString = require('@stryke/type-checks/is-string');
var loadEnv$1 = require('@stryke/env/load-env');
var joinPaths = require('@stryke/path/join-paths');
var c12 = require('c12');
var defu = require('defu');
var types = require('@storm-software/config-tools/types');
var parseTypeDefinition = require('@stryke/convert/parse-type-definition');
var exists = require('@stryke/path/exists');
var isObject = require('@stryke/type-checks/is-object');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var defu__default = /*#__PURE__*/_interopDefault(defu);

// src/helpers/dotenv/docgen.ts
function generateDotenvMarkdown(packageJson, properties) {
  return `<!-- Generated by Storm Stack -->

# Environment variables configuration

Below is a list of environment variables used by the [${packageJson.name}](https://www.npmjs.com/package/${packageJson.name}) package. These values can be updated in the \`.env\` file in the root of the project.

## Variables

The below list of environment variables are used as configuration parameters to drive the processing of the application. The data contained in these variables are **not** considered sensitive or confidential. Any values provided in these variables will be available in plain text to the public.

| Name | Description | Type | Default Value | Required |
| ---- | ----------- | ---- | ------------- | :------: |
${properties.filter((property) => property.getNameAsString() !== "__STORM_INJECTED__").sort((a, b) => a.getNameAsString().localeCompare(b.getNameAsString())).map((reflectionProperty) => {
    return `| ${reflectionProperty.getNameAsString().trim()} | ${(reflectionProperty.getDescription()?.replaceAll("\r", "")?.replaceAll("\n", "") ?? "").trim()} | ${(void 0)(reflectionProperty.getType()).trim().replaceAll(" | ", ", or ")} | ${reflectionProperty.hasDefault() ? String(reflectionProperty.getDefaultValue())?.includes('"') ? reflectionProperty.getDefaultValue() : `\`${reflectionProperty.getDefaultValue()}\`` : ""} | ${reflectionProperty.isValueRequired() ? "" : "\u2714"} |`;
  }).join("\n")}
`;
}
chunkAF3E2D32_cjs.__name(generateDotenvMarkdown, "generateDotenvMarkdown");
var removeEnvPrefix = /* @__PURE__ */ chunkAF3E2D32_cjs.__name((env) => {
  if (isString.isString(env)) {
    let name = types$1.ENV_PREFIXES.reduce((ret, prefix) => {
      if (ret.startsWith(prefix)) {
        ret = ret.slice(prefix.length);
      }
      return ret;
    }, env.toUpperCase());
    while (name.startsWith("_")) {
      name = name.slice(1);
    }
    return name;
  }
  return Object.keys(env).reduce((ret, key) => {
    const name = removeEnvPrefix(key);
    if (name) {
      ret[name] = env[key];
    }
    return ret;
  }, {});
}, "removeEnvPrefix");
var formatEnvField = /* @__PURE__ */ chunkAF3E2D32_cjs.__name((key) => {
  return camelCase.camelCase(removeEnvPrefix(key));
}, "formatEnvField");
var loadEnvFiles = /* @__PURE__ */ chunkAF3E2D32_cjs.__name(async (options, cwd, dotenv) => {
  let env = await loadEnv$1.loadEnv(cwd, options.mode);
  if (dotenv.additionalFiles.length > 0) {
    const additionalEnvFiles = await Promise.all(dotenv.additionalFiles.map(async (additionalEnvFile) => loadEnv$1.loadEnvFile(additionalEnvFile, cwd)));
    for (const additionalEnvFile of additionalEnvFiles) {
      env = defu__default.default(additionalEnvFile, env);
    }
  }
  return removeEnvPrefix(env);
}, "loadEnvFiles");
var loadEnvDirectory = /* @__PURE__ */ chunkAF3E2D32_cjs.__name(async (directory, options, dotenv, cacheDir, packageJson, workspaceConfig) => {
  const [envResult, c12Result] = await Promise.all([
    loadEnvFiles(options, directory, dotenv),
    c12.loadConfig({
      cwd: directory,
      name: "storm",
      envName: options.mode,
      defaults: {
        NAME: packageJson.name?.replace(`@${workspaceConfig.namespace}/`, ""),
        MODE: options.mode,
        ORG: workspaceConfig.organization
      },
      globalRc: true,
      packageJson: true,
      dotenv: true,
      jitiOptions: {
        fsCache: joinPaths.joinPaths(cacheDir, "jiti"),
        moduleCache: true
      }
    })
  ]);
  return defu__default.default(envResult, c12Result.config, workspaceConfig);
}, "loadEnvDirectory");
var loadEnv = /* @__PURE__ */ chunkAF3E2D32_cjs.__name(async (options, dotenv, cacheDir, configDir, packageJson, workspaceConfig) => {
  const [project, workspace, config] = await Promise.all([
    loadEnvDirectory(options.projectRoot, options, dotenv, cacheDir, packageJson, workspaceConfig),
    loadEnvDirectory(workspaceConfig.workspaceRoot, options, dotenv, cacheDir, packageJson, workspaceConfig),
    loadEnvDirectory(configDir, options, dotenv, cacheDir, packageJson, workspaceConfig)
  ]);
  return defu__default.default(project, workspace, config);
}, "loadEnv");
async function reflectDotenvSecrets(log, context, file, name) {
  const secretsType = await chunkTFTEYV3L_cjs.reflectType(context, {
    file,
    name
  });
  return (void 0)(secretsType);
}
chunkAF3E2D32_cjs.__name(reflectDotenvSecrets, "reflectDotenvSecrets");
async function reflectDotenvVariables(log, context, file, name) {
  let vars;
  if (file) {
    const varsType = await chunkTFTEYV3L_cjs.reflectType(context, {
      file,
      name
    });
    vars = (void 0)(varsType);
  }
  const defaultVarsType = await chunkTFTEYV3L_cjs.reflectType(context, chunkOTH2GDR2_cjs.getDotenvDefaultTypeDefinition(context));
  const defaultVars = (void 0)(defaultVarsType);
  if (vars) {
    defaultVars.getProperties().forEach((prop) => {
      if (!vars.hasProperty(prop.getName())) {
        vars.addProperty(prop.property);
      }
    });
  } else {
    vars = defaultVars;
  }
  return vars;
}
chunkAF3E2D32_cjs.__name(reflectDotenvVariables, "reflectDotenvVariables");
async function reflectDotenvTypes(log, context) {
  const result = {};
  let params = {
    variables: `${chunkOTH2GDR2_cjs.getDotenvDefaultTypeDefinition(context).file}#${chunkOTH2GDR2_cjs.getDotenvDefaultTypeDefinition(context).name}`
  };
  if (!context.dotenv?.types) {
    log(types.LogLevelLabel.WARN, "No environment variable type definitions were provided in the `dotenv.types` configuration.");
  } else {
    params = isObject.isObject(context.dotenv.types) ? context.dotenv.types : {
      variables: `${context.dotenv.types}#Variables`,
      secrets: `${context.dotenv.types}#Secrets`
    };
  }
  result.variables ??= {};
  if (params.variables) {
    result.variables.typeDefinition = parseTypeDefinition.parseTypeDefinition(params.variables);
    if (result.variables.typeDefinition?.file && exists.existsSync(joinPaths.joinPaths(context.projectRoot, result.variables.typeDefinition.file))) {
      result.variables.reflection = await reflectDotenvVariables(log, context, result.variables.typeDefinition.file, result.variables.typeDefinition.name);
    } else {
      log(types.LogLevelLabel.WARN, "Cannot find the `dotenv.types.variables` type definition in the provided configuration.");
      result.variables.reflection = await reflectDotenvVariables(log, context);
    }
  } else {
    log(types.LogLevelLabel.WARN, "The `dotenv.types.variables` configuration parameter was not provided. Please ensure this is expected.");
    result.variables.reflection = await reflectDotenvVariables(log, context);
  }
  if (params.secrets) {
    result.secrets ??= {};
    result.secrets.typeDefinition = parseTypeDefinition.parseTypeDefinition(params.secrets);
    if (!result.secrets.typeDefinition?.file) {
      throw new Error("Invalid type definition for secrets found in `dotenv.types.secrets` of the provided configuration.");
    }
    if (exists.existsSync(joinPaths.joinPaths(context.projectRoot, result.secrets.typeDefinition.file))) {
      result.secrets.reflection = await reflectDotenvSecrets(log, context, result.secrets.typeDefinition.file, result.secrets.typeDefinition.name);
    } else {
      log(types.LogLevelLabel.WARN, "Cannot find the `dotenv.types.secrets` type definition in the provided configuration.");
    }
  } else {
    log(types.LogLevelLabel.WARN, "The `dotenv.types.secrets` configuration parameter was not provided. Please ensure this is expected.");
  }
  const varsReflection = (void 0).from(result.variables.reflection);
  let secretsReflection;
  if (result.secrets) {
    secretsReflection = (void 0).from(result.secrets.reflection);
  }
  log(types.LogLevelLabel.TRACE, `Resolved ${varsReflection.getProperties().length ?? 0} variable and ${secretsReflection?.getProperties().length ?? 0} secret dotenv definitions`);
  return result;
}
chunkAF3E2D32_cjs.__name(reflectDotenvTypes, "reflectDotenvTypes");

exports.formatEnvField = formatEnvField;
exports.generateDotenvMarkdown = generateDotenvMarkdown;
exports.loadEnv = loadEnv;
exports.reflectDotenvTypes = reflectDotenvTypes;
exports.removeEnvPrefix = removeEnvPrefix;
//# sourceMappingURL=chunk-OUQKSIVE.cjs.map
//# sourceMappingURL=chunk-OUQKSIVE.cjs.map